{"library":"next-connect","title":"Next.js Connect Router","description":"next-connect is a promise-based routing and middleware layer designed specifically for Next.js applications, supporting various environments including API Routes, Edge API Routes, Middleware, App Router Route Handlers, and `getServerSideProps`. Currently at stable version 1.0.0, the library has historically followed an active release cadence, with pre-releases leading up to major versions. Its key differentiators include asynchronous middleware support, a lightweight footprint suitable for serverless environments, and significantly faster performance compared to traditional Express.js setups. It also offers robust TypeScript support and handles asynchronous handlers with integrated error catching, providing a flexible and efficient alternative for managing server-side logic in Next.js projects.","language":"javascript","status":"active","last_verified":"Wed Apr 22","install":{"commands":["npm install next-connect"],"cli":null},"imports":["import { createRouter } from 'next-connect';","import { createEdgeRouter } from 'next-connect';","import { expressWrapper } from 'next-connect';","import type { NextConnect } from 'next-connect';"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import type { NextApiRequest, NextApiResponse } from \"next\";\nimport { createRouter } from \"next-connect\";\n\n// Mock dependencies for a runnable example\nconst getUser = (id: string) => ({ id, name: `User ${id}`, email: `${id}@example.com` });\nconst updateUser = async (data: any) => ({ ...data, updatedAt: new Date().toISOString() });\nclass ForbiddenError extends Error {\n  statusCode: number;\n  constructor(message: string) {\n    super(message);\n    this.name = 'ForbiddenError';\n    this.statusCode = 403;\n  }\n}\n\nconst router = createRouter<NextApiRequest, NextApiResponse>();\n\nrouter\n  .use(async (req, res, next) => {\n    const start = Date.now();\n    // Simulate authentication or logging\n    console.log(`Incoming request to ${req.url}`);\n    await next(); // call next in chain\n    const end = Date.now();\n    console.log(`Request to ${req.url} took ${end - start}ms`);\n  })\n  .get((req, res) => {\n    const { id } = req.query;\n    if (typeof id !== 'string') {\n      res.status(400).json({ message: 'Invalid user ID' });\n      return;\n    }\n    const user = getUser(id);\n    res.json({ user });\n  })\n  .put(async (req, res) => {\n    // Simulate user context (e.g., from session/token)\n    const currentUser = { id: 'currentUserId123' }; // Mock current user\n    const { id } = req.query;\n    if (typeof id !== 'string') {\n      throw new Error('Invalid user ID for update');\n    }\n\n    // Example authorization check\n    if (currentUser.id !== id) {\n      throw new ForbiddenError(\"You can't update other user's profile\");\n    }\n    const updatedUser = await updateUser({ id, ...req.body });\n    res.json({ user: updatedUser });\n  });\n\nexport default router.handler({\n  onError: (err, req, res) => {\n    console.error(err.stack); // Log the error for debugging\n    const statusCode = (err as ForbiddenError).statusCode || 500;\n    res.status(statusCode).end(err.message || \"Something broke!\");\n  },\n  onNoMatch: (req, res) => {\n    res.status(404).end(`Route ${req.method} ${req.url} not found`);\n  },\n});","lang":"typescript","description":"This example demonstrates creating an API route with `next-connect`, handling GET and PUT requests, implementing asynchronous middleware for logging, and setting up global error handling for unmatched routes and exceptions.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}