{"library":"next-api-middleware","title":"Next.js API Middleware","description":"next-api-middleware is a library designed to bring clean, composable middleware patterns to Next.js API routes, addressing the limitations of Next.js's native middleware recommendations. It provides an API inspired by Express.js and Koa.js, enabling developers to build a \"winding and unwinding stack\" of middleware functions for request processing and response modification. The current stable version is 3.0.0, which notably dropped support for Node.js 12 and 14. While actively maintained, it is explicitly built for and tested with the Next.js Pages Router and has not been verified for compatibility with the newer App Router. Its core differentiator lies in offering structured middleware orchestration using `label` and `use` functions, allowing for modular and reusable backend logic within Next.js applications.","language":"javascript","status":"active","last_verified":"Sun Apr 19","install":{"commands":["npm install next-api-middleware"],"cli":null},"imports":["import { label } from 'next-api-middleware';","import type { Middleware } from 'next-api-middleware';","import { use } from 'next-api-middleware';"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import { label, Middleware } from \"next-api-middleware\";\nimport * as Sentry from \"@sentry/nextjs\";\nimport { nanoid } from \"nanoid\";\n\n// 1 – Create middleware functions\n\nconst captureErrors: Middleware = async (req, res, next) => {\n  try {\n    // Catch any errors that are thrown in remaining\n    // middleware and the API route handler\n    await next();\n  } catch (err) {\n    const eventId = Sentry.captureException(err);\n\n    res.status(500);\n    res.json({ error: err instanceof Error ? err.message : 'An unexpected error occurred.' });\n  }\n};\n\nconst addRequestId: Middleware = async (req, res, next) => {\n  // Let remaining middleware and API route execute\n  await next();\n\n  // Apply header\n  res.setHeader(\"X-Response-ID\", nanoid());\n};\n\n// 2 – Use `label` to assemble all middleware\n\nconst withMiddleware = label(\n  {\n    addRequestId,\n    sentry: captureErrors // <-- Optionally alias middleware\n  },\n  [\"sentry\"] // <-- Provide a list of middleware to call automatically\n);\n\n// 3 – Define your API route handler\n\nconst apiRouteHandler = async (req: any, res: any) => {\n  res.status(200);\n  res.send(\"Hello world!\");\n};\n\n// 4 – Choose middleware to invoke for this API route\n\nexport default withMiddleware(\"addRequestId\")(apiRouteHandler);\n","lang":"typescript","description":"Demonstrates how to create, compose, and apply API middleware using `label` for error capturing (Sentry) and adding unique request IDs to responses.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}