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.
npm install next-connectVerified import paths — ran on the pinned version, not inferred.
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.
For Express.js middleware, import and wrap it with `expressWrapper(middleware)`. For error handling, instead of calling `next(err)`, simply `throw new Error('...')` or a custom error object. The `onError` handler in `.handler()` will catch these.Ensure your error handling is configured within the `.handler({ onError: ... })` options object, as this is the standard and supported approach for catching errors thrown in middleware or route handlers.Always `await next()` in your `async` middleware functions: `router.use(async (req, res, next) => { /* ... */ await next(); /* ... */ });`Use `createRouter` when targeting `pages/api` (Node.js runtime). Use `createEdgeRouter` when targeting the Edge Runtime in `pages/api` (with `export const config = { runtime: 'edge' };`) or in App Router Route Handlers (`app/api`).Update your import statements to use named exports: `import { createRouter } from 'next-connect';` or `import { createEdgeRouter } from 'next-connect';`Replace calls to `next(err)` with `throw err;` or `throw new Error('...')`. Errors will be caught by the `onError` handler configured in `.handler()`.Ensure all middleware functions are correctly structured `(req, res, next) => { ... }` and that `async` middleware explicitly `await next();`. Double-check any `expressWrapper` usage for correct integration.Ensure that `res` is always available and that all asynchronous operations either return a value or explicitly call `next()` or `res.end()`/`res.json()`. Await all `next()` calls in async middleware. Implement a robust `onError` handler in `router.handler()` to catch and gracefully respond to errors.
No dependency data recorded yet.