nextjs-middleware-chain
raw JSON → 0.0.8 verified Sat Apr 25 auth: no javascript
A lightweight, zero-dependency Next.js middleware library for chaining middleware functions across API routes and SSR (getServerSideProps) data fetching. Version 0.0.8 (early-stage). Allows reuse of middleware functions by composing them in a chainable API. Differentiators: unified middleware interface for both API and SSR routes, chainable methods, global and per-route options. Release cadence: infrequent, no stable release yet.
Common errors
error TypeError: middlewareFunctionsArray is not iterable ↓
cause createMiddleware expects an array but a single function was passed.
fix
Wrap the function in an array: createMiddleware([myFn])
error TypeError: Cannot read properties of undefined (reading 'finish') ↓
cause Middleware factory returned undefined because no chainable method was called before finish.
fix
Ensure chaining syntax: mwFactory().middlewareFn().finish(handler)
error Error: middleware function must return a promise or call next ↓
cause Middleware function did not call next() or return next().
fix
Add 'return next();' at the end of each middleware function.
Warnings
gotcha Middleware functions must call next() and return its result, or the chain breaks. ↓
fix Always return next() at the end of each middleware function.
breaking Package is in early stage (v0.0.8); API may change without major semver bump. ↓
fix Pin exact version and test upgrades carefully.
gotcha The 'finish' method is required at the end of the chain; otherwise the route handler is never called. ↓
fix Always chain .finish(handler, name) after middleware functions.
gotcha Options passed to createMiddleware or the factory are not deeply merged; they override defaults entirely. ↓
fix Pass full options object each time; do not rely on partial overrides.
Install
npm install nextjs-middleware-chain yarn add nextjs-middleware-chain pnpm add nextjs-middleware-chain Imports
- createMiddleware wrong
const createMiddleware = require('nextjs-middleware-chain')correctimport { createMiddleware } from 'nextjs-middleware-chain' - default export wrong
import { default as mwFactory } from './middleware'correctimport mwFactory from './middleware' - finished route wrong
mwFactory().finish(routeFunction)correctmwFactory().mwFunction().finish(routeFunction, 'Route Name')
Quickstart
// middleware.js
import { createMiddleware } from 'nextjs-middleware-chain';
const logger = (req, res, next) => {
console.log('Request:', req.method, req.url);
return next();
};
const mwFactory = createMiddleware([logger], { useChainOrder: true });
export default mwFactory;
// pages/api/hello.js
import mwFactory from '../../middleware';
const handler = (req, res) => {
res.status(200).json({ message: 'Hello' });
};
export default mwFactory().logger().finish(handler, 'Hello API');