{"id":17832,"library":"nextjs-middleware-wrappers","title":"Next.js Middleware Wrappers","description":"nextjs-middleware-wrappers is a utility package designed to streamline the composition of middleware functions in Next.js API routes and endpoints. It provides a `wrappers` function that allows developers to chain multiple higher-order middleware functions in a more readable and type-safe manner, contrasting with deeply nested function calls. The package, currently at version 1.3.0, is actively maintained with a structured release process informed by Angular JS commit message conventions, implying regular updates for fixes, features, and potential breaking changes. Its primary differentiator lies in its ability to preserve the input and output types across multiple middleware layers, significantly reducing the common type-mismatch issues encountered when manually composing such functions. This utility aims to improve code clarity and maintainability for applications heavily relying on request-based middleware patterns within the Next.js ecosystem, ensuring that complex middleware logic remains manageable and robust.","status":"active","version":"1.3.0","language":"javascript","source_language":"en","source_url":"git://github.com/seamapi/wrappers","tags":["javascript","typescript"],"install":[{"cmd":"npm install nextjs-middleware-wrappers","lang":"bash","label":"npm"},{"cmd":"yarn add nextjs-middleware-wrappers","lang":"bash","label":"yarn"},{"cmd":"pnpm add nextjs-middleware-wrappers","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary utility `wrappers` is a named export. Ensure to use named import syntax. While CommonJS `require` might work in some transpiled environments, modern Next.js projects predominantly use ESM, making the `import` statement the correct and idiomatic choice.","wrong":"const wrappers = require('nextjs-middleware-wrappers');","symbol":"wrappers","correct":"import { wrappers } from 'nextjs-middleware-wrappers';"},{"note":"The `wrappers` function is a named export, not a default export. Using a default import will result in a `TypeError` at runtime.","wrong":"import wrappers from 'nextjs-middleware-wrappers';","symbol":"wrappers (default import mistake)","correct":"import { wrappers } from 'nextjs-middleware-wrappers';"},{"note":"While `nextjs-middleware-wrappers` itself ships with TypeScript types, middleware functions often interact with Next.js specific types like `NextApiRequest` and `NextApiResponse`. These types should be imported directly from the `next` package for correct type inference and safety within your middleware.","symbol":"Types (Next.js specific)","correct":"import type { NextApiRequest, NextApiResponse } from 'next';"}],"quickstart":{"code":"import { NextApiRequest, NextApiResponse } from 'next';\nimport { wrappers } from 'nextjs-middleware-wrappers';\n\n// Example middleware: Adds a timestamp to the request object\nconst withTimestamp = (next) => async (req: NextApiRequest, res: NextApiResponse) => {\n  // For demonstration, cast req to any to add custom properties\n  (req as any).timestamp = Date.now();\n  console.log('Middleware: Timestamp added:', (req as any).timestamp);\n  return next(req, res);\n};\n\n// Example middleware: Logs the request method and path with a configurable prefix\nconst withRequestLogger = (logPrefix: string) =>\n  (next) =>\n  async (req: NextApiRequest, res: NextApiResponse) => {\n    console.log(`${logPrefix} GOT REQUEST ${req.method} ${req.url}`);\n    return next(req, res);\n  };\n\n// The actual Next.js API route handler function\nconst myApiHandler = async (req: NextApiRequest, res: NextApiResponse) => {\n  console.log('Handler received request at timestamp:', (req as any).timestamp);\n  res.status(200).json({\n    message: 'Hello from API!',\n    method: req.method,\n    url: req.url,\n    timestamp: (req as any).timestamp,\n  });\n};\n\n// Compose the handler with middleware using wrappers\n// Middleware are applied in the order they are listed.\nexport default wrappers(\n  withTimestamp,\n  withRequestLogger(\"[API_LOG]\"), // Middleware with parameters\n  myApiHandler\n);\n","lang":"typescript","description":"This quickstart demonstrates how to compose a Next.js API route handler using `nextjs-middleware-wrappers`. It chains two example middleware functions—one adding a timestamp to the request and another logging request details with a configurable prefix—before executing the main API handler, showcasing type-safe and cleaner middleware composition."},"warnings":[{"fix":"Consult the project's GitHub release notes or commit history for specific breaking changes relevant to your upgrade path and adjust your code accordingly.","message":"The package follows a strict semantic versioning policy, where `BREAKING CHANGE:` tags in commit messages indicate changes that may require adjustments to your code. Always review release notes or commit history when upgrading major versions to understand potential breaking changes.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Always define middleware as a function that accepts a `next` function and returns an asynchronous function that takes `req` and `res` as arguments, matching `(next) => async (req, res) => {...}`.","message":"Ensure all custom middleware functions passed to `wrappers` adhere to the expected higher-order function signature: `(next: Function) => async (req: NextApiRequest, res: NextApiResponse) => Promise<any>`. Incorrectly typed or structured middleware can lead to type errors during development or unexpected runtime behavior, especially when attempting to pass additional arguments.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Carefully design the order of your middleware to ensure dependencies are met and operations proceed logically. Place foundational middleware (e.g., authentication, logging, request parsing) before business logic-specific middleware.","message":"Middleware functions are executed in the exact order they are provided to the `wrappers` function. Be critically mindful of this sequence, as it dictates the flow of control and data transformation. Incorrect ordering can lead to logical errors, such as attempting to access data that an earlier middleware was supposed to set, or security vulnerabilities if validation occurs too late.","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":"Ensure all arguments to `wrappers` (except the very last one, which is the final API handler) are higher-order functions that accept a `next` argument and return an `async (req, res) => {...}` function. For example: `(next) => async (req, res) => { /* middleware logic */ return next(req, res); }`.","cause":"A function passed to `wrappers` is likely a direct API handler or a malformed middleware, rather than a higher-order middleware function that accepts a `next` parameter.","error":"Argument of type '(req: NextApiRequest, res: NextApiResponse) => Promise<void>' is not assignable to parameter of type '(next: any) => Promise<any>'"},{"fix":"Run `npm install nextjs-middleware-wrappers` or `yarn add nextjs-middleware-wrappers` to install the package. If the error persists, check your `tsconfig.json` to ensure `moduleResolution` is set appropriately (e.g., `NodeNext` or `Bundler`) for modern module systems.","cause":"The package is not installed in your project's `node_modules`, or there's an issue with your TypeScript configuration's module resolution.","error":"Cannot find module 'nextjs-middleware-wrappers' or its corresponding type declarations."},{"fix":"Change your import statement from `import wrappers from 'nextjs-middleware-wrappers'` to the correct named import: `import { wrappers } from 'nextjs-middleware-wrappers';`.","cause":"This error typically indicates that a default import was used for `wrappers` instead of a named import, or the build system is incorrectly interpreting the module's exports.","error":"TypeError: (0, nextjs_middleware_wrappers__WEBPACK_IMPORTED_MODULE_0__.wrappers) is not a function"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}