Registry / web-framework / next-api-middleware

next-api-middleware

JSON →
library3.0.0jsnpmunverified

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.

npm install next-api-middleware
INSTALL
IMPORT
SIG · NEXT-API-MIDDLEWAR
N
next-api-middleware
web-frameworkjavascriptv3.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

label
import { label } from 'next-api-middleware';
const { label } = require('next-api-middleware');
Since v2.0.0, the package provides dual ESM/CJS bundles, but ESM imports are the idiomatic approach, especially with Node.js >= 16 required by v3.0.0.
Middleware
import type { Middleware } from 'next-api-middleware';
import { Middleware } from 'next-api-middleware';
Middleware is a type definition. Using `import type` is the recommended practice in TypeScript to ensure type imports are stripped during compilation.
use
import { use } from 'next-api-middleware';
const { use } = require('next-api-middleware');
`use` is an alternative function to `label` for applying a single middleware or a linear chain directly to an API route.

Demonstrates how to create, compose, and apply API middleware using `label` for error capturing (Sentry) and adding unique request IDs to responses.

import { label, Middleware } from "next-api-middleware"; import * as Sentry from "@sentry/nextjs"; import { nanoid } from "nanoid"; // 1 – Create middleware functions const captureErrors: Middleware = async (req, res, next) => { try { // Catch any errors that are thrown in remaining // middleware and the API route handler await next(); } catch (err) { const eventId = Sentry.captureException(err); res.status(500); res.json({ error: err instanceof Error ? err.message : 'An unexpected error occurred.' }); } }; const addRequestId: Middleware = async (req, res, next) => { // Let remaining middleware and API route execute await next(); // Apply header res.setHeader("X-Response-ID", nanoid()); }; // 2 – Use `label` to assemble all middleware const withMiddleware = label( { addRequestId, sentry: captureErrors // <-- Optionally alias middleware }, ["sentry"] // <-- Provide a list of middleware to call automatically ); // 3 – Define your API route handler const apiRouteHandler = async (req: any, res: any) => { res.status(200); res.send("Hello world!"); }; // 4 – Choose middleware to invoke for this API route export default withMiddleware("addRequestId")(apiRouteHandler);
Debug
Known issues
breakingVersion 3.0.0 dropped support for Node.js 12 and 14. Ensure your project is running Node.js 16 or higher.
fix
Upgrade your Node.js environment to version 16 or newer.
affects: >=3.0.0
gotchaThis library is currently only tested and explicitly supports Next.js API routes using the Pages Router. It has not been tested or verified for compatibility with the newer App Router introduced in Next.js 13+.
fix
If using the App Router, evaluate alternative middleware solutions or proceed with caution and thorough testing.
affects: >=1.0.0
breakingVersion 2.0.0 replaced the 'main' field with 'exports' in package.json. This is a significant change for module resolution and may break builds in older Node.js environments or with bundlers that do not correctly handle the 'exports' field.
fix
Ensure your Node.js environment is up-to-date (>=12.7.0 for full 'exports' support, or prefer >=14.13.1) and that your bundler is configured to correctly resolve 'exports'.
affects: >=2.0.0
breakingVersion 2.0.0 introduced breaking API changes: `NextMiddleware` was renamed to `Middleware`, and `ExpressMiddleware` was removed entirely.
fix
Update all instances of `NextMiddleware` to `Middleware` in your type annotations. Replace or refactor any code relying on `ExpressMiddleware`.
affects: >=2.0.0
breakingVersion 2.0.0 moved the location of types and removed the internal logger. This might affect applications that relied on the previous type paths or internal logger functionality.
fix
Update type import paths if they were previously specific. The internal logger is no longer available; implement custom logging if needed.
affects: >=2.0.0
gotchaSince v2.0.0, the package outputs both CommonJS (CJS) and ECMAScript Modules (ESM) bundles. This might require explicit file extensions (.js) in import paths for ESM or specific bundler configurations to ensure the correct module format is loaded.
fix
Prefer ESM `import` statements. If encountering module resolution issues, check your `tsconfig.json` (for TypeScript) or bundler configuration for module resolution settings, and consider adding `.js` extensions for local ESM imports.
affects: >=2.0.0
Upgrade
Version history
3.0.0latest on npm
Audit
Dependencies
nextrequiredRequired as a peer dependency for Next.js API route functionality.
Agent activity
2 hits · last 30 days
node
2
Resources
next-api-middleware — npm install next-api-middleware · libregistry