Registry / web-framework / next-compose-middleware

next-compose-middleware

JSON →
library1.0.0jsnpmunverified

next-compose-middleware is a library designed to simplify the creation of complex and declarative middleware for Next.js applications, particularly leveraging Next.js's Edge Runtime middleware. It enables developers to construct highly readable and maintainable middleware logic by composing multiple functions. The current stable version is 2.0.4, indicating active development with incremental releases. Key differentiators include its path-based middleware execution, allowing for "Nested Middleware" behavior, and the ability to compose functions with early exit mechanisms (`breakAll`, `breakOnce`) for fine-grained control over execution flow. This approach helps in organizing middleware into logical, reusable units, enhancing maintainability for applications with intricate authorization, authentication, or request transformation requirements in a single `middleware.ts` file.

npm install next-compose-middleware
INSTALL
IMPORT
SIG · NEXT-COMPOSE-MIDDL
N
next-compose-middleware
web-frameworkjavascriptv1.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.

composeMiddleware
import { composeMiddleware } from 'next-compose-middleware';
const composeMiddleware = require('next-compose-middleware');
The library is primarily used in Next.js middleware files, which are typically ESM. Avoid CommonJS `require()` syntax.
ComposableMiddleware
import type { ComposableMiddleware } from 'next-compose-middleware';
This type is used for type-checking custom middleware functions. It should be imported as a type, not a runtime value.

Demonstrates how to set up `next-compose-middleware` with path-based execution for different routes and compose multiple middleware functions, including an example of conditional logic for early exit.

import { NextRequest, NextResponse } from 'next/server'; import { composeMiddleware, ComposableMiddleware } from 'next-compose-middleware'; // Example middleware functions const root1: ComposableMiddleware = async (req, res) => { console.log('Executing root1 for path:', req.nextUrl.pathname); // Example: Modify response headers or cookies res.headers.set('X-Root-Middleware-1', 'processed'); return res; }; const root2: ComposableMiddleware = async (req, res) => { console.log('Executing root2 for path:', req.nextUrl.pathname); return res; }; const foo: ComposableMiddleware = async (req, res) => { console.log('Executing foo for path:', req.nextUrl.pathname); return res; }; const fooBar: ComposableMiddleware = async (req, res) => { console.log('Executing fooBar for path:', req.nextUrl.pathname); // Early exit example: if a condition is met, stop further middleware if (req.nextUrl.searchParams.has('exit')) { console.log('Early exiting from fooBar!'); return res; // Returning res without breakAll/breakOnce continues chain, but no further changes here. } return res; }; const fooId: ComposableMiddleware = async (req, res) => { const id = req.nextUrl.pathname.split('/')[2]; console.log('Executing fooId for path:', req.nextUrl.pathname, 'ID:', id); return res; }; const fooIdBaz: ComposableMiddleware = async (req, res) => { console.log('Executing fooIdBaz for path:', req.nextUrl.pathname); return res; }; const fooQux: ComposableMiddleware = async (req, res) => { console.log('Executing fooQux for path:', req.nextUrl.pathname); return res; }; export default async function middleware(req: NextRequest) { console.log(`\n--- Incoming Request for ${req.nextUrl.pathname} ---`); // Compose middleware based on paths return composeMiddleware(req, NextResponse.next(), { scripts: [root1, root2], // Applied to all matching paths '/foo': { scripts: [foo], // Applied to /foo and its children '/bar': { scripts: [fooBar], // Applied to /foo/bar and its children }, '/[id]': { // Dynamic segment scripts: [fooId], // Applied to /foo/:id and its children '/baz': [fooIdBaz] // Applied to /foo/:id/baz }, '/qux': [fooQux] // Applied to /foo/qux } }); }
Debug
Known issues
gotchaThis library requires Next.js v12.2.0 or higher for stable middleware support. Older versions of Next.js do not fully support the middleware API that this library leverages, especially regarding nested middleware, which was deprecated in favor of a single root middleware file.
fix
Upgrade your Next.js project to version 12.2.0 or newer to ensure compatibility and access to stable middleware features.
affects: <12.2.0 of next
gotchaMisunderstanding 'breakAll' vs 'breakOnce' in early exit scenarios can lead to unexpected middleware execution flow. 'breakAll' completely halts all subsequent middleware in the entire composition, while 'breakOnce' only stops subsequent middleware at the current nesting level, allowing parent or sibling middleware branches to continue.
fix
Carefully choose between `breakAll(res)` to completely halt middleware execution or `breakOnce(res)` to only skip siblings in the current path segment, based on your desired control flow.
affects: >=1.0.0
gotchaNext.js Middleware functions (and thus ComposableMiddleware) run in the Edge Runtime, which has limitations compared to Node.js environments. This means certain Node.js APIs and global objects are unavailable, and environment variables are often resolved at build time, not runtime.
fix
Avoid Node.js-specific APIs within your middleware. For dynamic environment variables or complex logic, consider using API routes or native Web APIs like `fetch`. Ensure environment variables are configured correctly for the Edge runtime.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: next_compose_middleware_1.composeMiddleware is not a function
Attempting to import `composeMiddleware` using CommonJS `require()` syntax in an ESM context, or an incorrect named import.
fix
Ensure you are using ESM `import { composeMiddleware } from 'next-compose-middleware';` syntax, especially in Next.js middleware files which are typically ESM. Verify the symbol name is correct and not a default export.
TypeError: Cannot read properties of undefined (reading 'cookies') or 'headers' is undefined
A middleware function is not returning a valid `NextResponse` object, causing subsequent middleware to receive an undefined or invalid response object.
fix
Always ensure your `ComposableMiddleware` functions, especially those implementing early exit logic, explicitly return a `NextResponse` instance (e.g., `return res;`, `return breakAll(res);`, or `return breakOnce(res);`).
Upgrade
Version history
1.0.0latest on npm
Audit
Dependencies
nextrequiredRequired for Next.js middleware functionality, specifically v12.2.0+ for stable middleware support.
Agent activity
2 hits · last 30 days
node
2
Resources
next-compose-middleware — npm install next-compose-middleware · libregistry