Registry / web-framework / next-api-route-middleware

next-api-route-middleware

JSON →
library1.0.2jsnpmunverified

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.

npm install next-api-route-middleware
INSTALL
IMPORT
SIG · NEXT-API-ROUTE-MID
N
next-api-route-middleware
web-frameworkjavascriptv1.0.2
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.

use
import { use } from 'next-api-route-middleware';
const { use } = require('next-api-route-middleware');
Primarily designed for ESM usage in modern Next.js projects. CommonJS 'require' is less common.
Middleware
import { Middleware } from 'next-api-route-middleware';
import Middleware from 'next-api-route-middleware';
Middleware is a named export, not a default export. Used for type hinting custom middleware functions.

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.

import { use, Middleware } from 'next-api-route-middleware'; import { NextApiRequest, NextApiResponse } from 'next'; // 1. Define custom types for augmented request to leverage TypeScript interface UserData { userId: string; } type NextApiRequestWithUser = NextApiRequest & UserData; // Mock user fetching for demonstration purposes const getUserByCookie = async (): Promise<UserData | null> => { // In a real application, this would involve reading cookies or a session return Math.random() > 0.5 ? { userId: 'user123' } : null; }; // 2. Define custom middleware functions const withUser: Middleware<NextApiRequestWithUser> = async (req, res, next) => { const authCookie = await getUserByCookie(); if (authCookie) { req.userId = authCookie.userId; // Augment the request object next(); // Pass control to the next middleware or handler } else { res.status(401).json({ message: 'Invalid authentication.' }); // Terminate if unauthorized } }; const allowMethods = (allowedMethods: string[]): Middleware => { return async function (req, res, next) { if (allowedMethods.includes(req.method!) || req.method === 'OPTIONS') { next(); } else { res.status(405).json({ message: `Method ${req.method} not allowed.` }); } }; }; const captureErrors: Middleware = async (req, res, next) => { try { await next(); } catch (error) { console.error('API Route Error:', error); res.status(500).json({ message: 'Server error!' }); } }; // 3. Define the main API route handler const handler = async ( req: NextApiRequestWithUser, res: NextApiResponse<UserData | { message: string }> ) => { // req.userId is guaranteed to be available here thanks to the 'withUser' middleware res.status(200).json({ userId: req.userId }); }; // 4. Export the composed middleware stack and handler // Middleware functions execute in the order they are provided export default use( captureErrors, allowMethods(['GET']), // Only GET requests are allowed withUser, handler // The final handler that processes the request );
Debug
Known issues
gotchaForgetting to call `next()` within a middleware function will halt the request processing, preventing subsequent middleware or the final API handler from executing. This can lead to hanging requests or unexpected behavior if a response is not explicitly sent.
fix
Ensure `next()` is called at the end of each middleware function unless `res.send()` or `res.json()` has been called to terminate the response.
affects: >=1.0.0
gotchaWhen augmenting the `NextApiRequest` object (e.g., adding `req.userId`), TypeScript will complain unless you explicitly define a new type that extends `NextApiRequest` and use it for your middleware and handler. This is crucial for type safety.
fix
Create an intersection type like `type NextApiRequestWithUser = NextApiRequest & { userId: string; };` and use this type for your middleware and handler function signatures.
affects: >=1.0.0
gotchaMiddleware functions execute in the order they are provided to the `use` function. Incorrect ordering can lead to issues, such as trying to access augmented `req` properties before the middleware that adds them has run, or error handlers not catching errors from preceding middleware.
fix
Carefully consider the logical flow of your middleware. Place setup/validation middleware before business logic, and error handlers typically at the beginning or wrapped around other middleware.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: next is not a function
A middleware function did not call `next()` or called it incorrectly, or the `use` function received something other than a middleware function or handler.
fix
Verify that every middleware function either calls `next()` or explicitly sends a response using `res.send()`/`res.json()`. Ensure all arguments passed to `use` are valid middleware or the final handler.
TS2339: Property 'userId' does not exist on type 'NextApiRequest'.
Attempting to access a custom property on the `req` object without properly extending the `NextApiRequest` type definition.
fix
Define a custom type (e.g., `interface CustomRequest extends NextApiRequest { userId: string; }`) and use this type annotation in your middleware and handler functions.
Error: Method GET Not Allowed
The `allowMethods` middleware (or similar method validation logic) rejected the request because its HTTP method was not in the allowed list.
fix
Check the `allowMethods` configuration to ensure the desired HTTP method is included in the array of allowed methods. For testing, ensure your client is sending the correct method.
Upgrade
Version history
1.0.2latest on npm
Audit
Dependencies
nextrequiredRequired as a peer dependency for Next.js API route functionality.
Agent activity
11 hits · last 30 days
node
10
OpenAI (training)
1
Resources
next-api-route-middleware — npm install next-api-route-middleware · libregistry