next-middleware

raw JSON →
0.0.1 verified Fri May 01 auth: no javascript

A lightweight middleware pipeline for Next.js applications, enabling developers to add reusable middleware functions that execute before page rendering. Current stable version is 0.0.1, with no frequent release cadence. Key differentiators: simple API using a pipeline pattern, designed specifically for Next.js pages directory. It allows chaining multiple async middleware functions that can inject props into pages.

error TypeError: middleware.build is not a function
cause Attempted to call middleware.build before adding any middleware or after invalid instantiation.
fix
Ensure you instantiate correctly: const middleware = new Middleware(); then add at least one middleware before exporting .build.
error Error: You're using the wrong import syntax. Use 'import Middleware from "next-middleware"' instead.
cause Using CommonJS require to import the ESM-only package.
fix
Switch to import statement: import Middleware from 'next-middleware';
gotcha Middleware functions must return an object; returned props are merged with page's getInitialProps.
fix Ensure each middleware returns a plain object with the props to inject.
gotcha The package is very early (v0.0.1); API may change without notice.
fix Pin version in package.json and test upgrades thoroughly.
gotcha Only works with Next.js pages directory; not compatible with App Router.
fix Use Next.js middleware feature for App Router instead.
npm install next-middleware
yarn add next-middleware
pnpm add next-middleware

Shows basic setup: import Middleware, create pipeline, add async middleware that fetches data, and export build method.

import Middleware from 'next-middleware';

const middleware = new Middleware();

middleware.add(async ({ req }) => {
  const res = await fetch(`https://api.example.com/users?id=${req.query.id}`);
  const users = await res.json();
  return { users };
});

export default middleware.build;