{"library":"next-api-route-middleware","title":"Next.js API Route Middleware","description":"next-api-route-middleware provides a concise and type-safe way to implement middleware patterns for Next.js API routes. It enables developers to abstract reusable logic that executes before the main API handler, such as authentication, request method validation, error capturing, or augmenting the `req` object with additional data. The package is currently at version 1.0.2, indicating a stable but relatively early stage of development. While there isn't an explicit release cadence stated, its current version suggests a focus on stability for its initial feature set. A key differentiator is its strong TypeScript support, allowing for straightforward extension of NextApiRequest types without casting, and its functional composition approach for applying multiple middleware.","language":"javascript","status":"active","last_verified":"Sun Apr 19","install":{"commands":["npm install next-api-route-middleware"],"cli":null},"imports":["import { use } from 'next-api-route-middleware';","import { Middleware } from 'next-api-route-middleware';"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import { use, Middleware } from 'next-api-route-middleware';\nimport { NextApiRequest, NextApiResponse } from 'next';\n\n// 1. Define custom types for augmented request to leverage TypeScript\ninterface UserData { userId: string; }\ntype NextApiRequestWithUser = NextApiRequest & UserData;\n\n// Mock user fetching for demonstration purposes\nconst getUserByCookie = async (): Promise<UserData | null> => {\n  // In a real application, this would involve reading cookies or a session\n  return Math.random() > 0.5 ? { userId: 'user123' } : null; \n};\n\n// 2. Define custom middleware functions\nconst withUser: Middleware<NextApiRequestWithUser> = async (req, res, next) => {\n  const authCookie = await getUserByCookie();\n  if (authCookie) {\n    req.userId = authCookie.userId; // Augment the request object\n    next(); // Pass control to the next middleware or handler\n  } else {\n    res.status(401).json({ message: 'Invalid authentication.' }); // Terminate if unauthorized\n  }\n};\n\nconst allowMethods = (allowedMethods: string[]): Middleware => {\n  return async function (req, res, next) {\n    if (allowedMethods.includes(req.method!) || req.method === 'OPTIONS') {\n      next();\n    } else {\n      res.status(405).json({ message: `Method ${req.method} not allowed.` });\n    }\n  };\n};\n\nconst captureErrors: Middleware = async (req, res, next) => {\n  try {\n    await next();\n  } catch (error) {\n    console.error('API Route Error:', error);\n    res.status(500).json({ message: 'Server error!' });\n  }\n};\n\n// 3. Define the main API route handler\nconst handler = async (\n  req: NextApiRequestWithUser,\n  res: NextApiResponse<UserData | { message: string }>\n) => {\n  // req.userId is guaranteed to be available here thanks to the 'withUser' middleware\n  res.status(200).json({ userId: req.userId });\n};\n\n// 4. Export the composed middleware stack and handler\n// Middleware functions execute in the order they are provided\nexport default use(\n  captureErrors,\n  allowMethods(['GET']), // Only GET requests are allowed\n  withUser,\n  handler // The final handler that processes the request\n);","lang":"typescript","description":"Demonstrates how to define custom middleware (for user authentication and method validation), compose them with an error-capturing middleware, and apply them sequentially to a Next.js API route using the `use` function.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}