{"id":17630,"library":"express-partial-response","title":"Express Partial Response Middleware","description":"express-partial-response is an Express.js middleware designed to filter parts of JSON responses based on a `fields` query-string parameter. It mimics the \"Partial Response\" feature found in Google APIs, allowing clients to request only a subset of data from an API endpoint, thereby reducing bandwidth and processing on the client side. The current stable version is 1.0.4. The project appears to be in a maintenance state, with no recent major updates mentioned, suggesting a stable and complete feature set rather than active development. Its core functionality is powered by the `json-mask` library, which handles the actual JSON object filtering according to the specified field syntax. This middleware differentiates itself by providing a direct, out-of-the-box integration for Express applications, simplifying the implementation of partial responses without requiring manual integration of `json-mask` into every route.","status":"maintenance","version":"1.0.4","language":"javascript","source_language":"en","source_url":"git://github.com/nemtsov/express-partial-response","tags":["javascript","express","partial-response","filter","mask","select","fields","projection","query"],"install":[{"cmd":"npm install express-partial-response","lang":"bash","label":"npm"},{"cmd":"yarn add express-partial-response","lang":"bash","label":"yarn"},{"cmd":"pnpm add express-partial-response","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Underlying library used for parsing the `fields` query string and applying the JSON filtering logic.","package":"json-mask","optional":false}],"imports":[{"note":"The package is CommonJS-only and exports a single middleware factory function as its default export. Attempting to destructure or use ESM `import` directly will fail.","wrong":"const { partialResponse } = require('express-partial-response');","symbol":"partialResponse","correct":"const partialResponse = require('express-partial-response');"},{"note":"The `partialResponse` function must be called (even without arguments like `partialResponse()`) to return the actual middleware function that Express expects for `app.use()`.","wrong":"app.use(partialResponse);","symbol":"partialResponse(options)","correct":"app.use(partialResponse({ query: 'filter' }));"}],"quickstart":{"code":"const express = require('express');\nconst partialResponse = require('express-partial-response');\nconst app = express();\n\n// Apply the partial response middleware globally\napp.use(partialResponse({ query: 'fields' })); // Default query param is 'fields'\n\napp.get('/users/:id', (req, res) => {\n  const userId = req.params.id;\n  const users = [\n    {\n      id: '1',\n      firstName: 'Mohandas',\n      lastName: 'Gandhi',\n      email: 'm.gandhi@example.com',\n      addresses: [{ street: '123 Peace Rd', city: 'Ahimsa', country: 'India' }],\n      aliases: [\n        { firstName: 'Mahatma', lastName: 'Gandhi' },\n        { firstName: 'Bapu', title: 'Father of the Nation' }\n      ],\n      secretInfo: 'Top Secret - Only for internal use'\n    },\n    {\n      id: '2',\n      firstName: 'Nelson',\n      lastName: 'Mandela',\n      email: 'n.mandela@example.com',\n      addresses: [{ street: '456 Freedom St', city: 'Ubuntu', country: 'South Africa' }],\n      aliases: [\n        { firstName: 'Madiba', lastName: 'Mandela' }\n      ],\n      secretInfo: 'Top Secret - Only for internal use'\n    }\n  ];\n  const user = users.find(u => u.id === userId);\n  if (user) {\n    res.json(user);\n  } else {\n    res.status(404).json({ message: 'User not found' });\n  }\n});\n\napp.get('/products', (req, res) => {\n  const products = [\n    { id: 'a1', name: 'Laptop', price: 1200, category: 'Electronics', description: 'Powerful laptop', supplier: 'TechCorp' },\n    { id: 'b2', name: 'Mouse', price: 25, category: 'Electronics', description: 'Wireless mouse', supplier: 'AccessoryCo' }\n  ];\n  res.json(products);\n});\n\nconst port = process.env.PORT ?? 4000;\napp.listen(port, () => {\n  console.log(`Server running on http://localhost:${port}`);\n  console.log('\\nTry these examples:');\n  console.log(`- Get user 1's first name and alias first names: curl 'http://localhost:${port}/users/1?fields=firstName,aliases(firstName)'`);\n  console.log(`- Get user 2's id and email: curl 'http://localhost:${port}/users/2?fields=id,email'`);\n  console.log(`- Get product names and prices: curl 'http://localhost:${port}/products?fields=name,price'`);\n  console.log(`- Get all fields for user 1 (no 'fields' param): curl 'http://localhost:${port}/users/1'`);\n});","lang":"javascript","description":"This quickstart demonstrates how to set up `express-partial-response` middleware with an Express application, creating two example routes (`/users/:id` and `/products`) that return JSON data. It shows how the middleware automatically filters the response based on the `?fields=` query parameter, illustrating various `json-mask` syntax examples with `curl` commands."},"warnings":[{"fix":"Consult the `json-mask` library documentation (e.g., `https://github.com/nemtsov/json-mask#syntax`) for the correct and full syntax of the `fields` parameter.","message":"The syntax for the `fields` query parameter is handled by the underlying `json-mask` library. Developers must refer to `json-mask`'s documentation for complex filtering patterns, nested fields, and array handling, as `express-partial-response` simply passes the string.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure `express-partial-response` is only used on routes that are expected to respond with JSON data. Consider applying it selectively using route-specific middleware if some routes serve non-JSON content.","message":"This middleware is designed exclusively for JSON responses. If applied to routes that return other content types (like HTML, plain text, or files) and `res.json()` is not eventually called, the middleware will have no effect or might lead to unexpected behavior.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Implement robust server-side authorization and data serialization logic to explicitly omit sensitive fields before they reach the `res.json()` call, or before `express-partial-response` processes them. Do not rely solely on client-requested field masks for security.","message":"As a general principle with field filtering, ensure that the fields available for filtering do not inadvertently expose sensitive data that should otherwise be protected. While the middleware filters based on client input, the original data might contain sensitive fields that could be exposed if requested via a wildcard or an overly broad mask. The `json-mask` library itself does not offer mechanisms for field-level access control.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"If working in a pure ESM project, you might need to use dynamic `import()` or configure your bundler to handle CJS modules. Alternatively, ensure your project is configured for CommonJS or use `require()` syntax.","message":"This package is written in CommonJS (CJS) and does not officially support ES Modules (ESM) directly. Attempting to use `import` statements in an ESM project will lead to errors.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Call the `partialResponse` function to get the actual middleware. Correct usage is `app.use(partialResponse());` or `app.use(partialResponse({ options }));`.","cause":"The `partialResponse` function was passed directly to `app.use()` without being called first, meaning `app.use()` received the factory function itself rather than the middleware instance.","error":"TypeError: app.use() requires a middleware function but got a Object"},{"fix":"Double-check the `fields` query parameter against the `json-mask` syntax documentation. Common mistakes include typos, incorrect nesting parentheses, or missing commas.","cause":"The `fields` query string parameter contains an incorrect or malformed `json-mask` syntax, causing the underlying `json-mask` library to either filter incorrectly or return an empty object.","error":"Response is not filtered as expected (or is empty) when using the 'fields' query parameter."},{"fix":"This package is CJS-only. You must either use a CommonJS environment, or if you must use ESM, use dynamic `import()` (e.g., `const partialResponse = await import('express-partial-response'); const middleware = partialResponse.default();`) or a build tool that handles CJS-to-ESM conversion.","cause":"Attempting to use `const partialResponse = require('express-partial-response');` in an ES Module (`type: \"module\"` in `package.json` or `.mjs` file).","error":"ReferenceError: require is not defined (in an ESM context)"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}