Set up, write, migrate and debug @zanreal/nemo middleware in Next.js apps.
- GitHub stars
- 360
Install
/plugin install nemo@zanreal-nemoRun it inside Claude Code after adding the marketplace with /plugin marketplace add zanreal-labs/nemo.
Contents
Discovered from sourceSkills 4
Debug and test NEMO
Work from the symptom table first, then use the debug options, then write a test that reproduces it.
Symptom to cause
| Symptom | Likely cause | Fix |
|---|---|---|
Route for /foo does not run on /foo/bar | A top-level function or array key matches the exact path only | Use "/foo/:path*" or a nested object |
| Nested child runs on deeper paths than expected | Nested keys match as prefixes ("/a": { "/b": fn } runs on /a/b/c) | Check request.nextUrl.pathname in the child, or use a top-level key for the exact path |
"/Pricing" does not run on /pricing | Plain paths are compared case sensitively | Use the exact case, or a pattern (patterns are case insensitive) |
"/" route does not run on other pages | "/" is exact root only | Use globalMiddleware.before for every request |
| Route never runs, no exception | Invalid pattern: NEMO prints Error creating regexp for pattern with console.error and the route never matches. Common: /api{/*path} (v8 syntax), (!api) | Use path-to-regexp v6 syntax, see nemo-middleware-patterns/references/matching.md |
| Route never runs for assets or an API path | config.matcher excludes the path so Next.js never calls the proxy | Fix the matcher |
new NextResponse("...", { status: 401 }) has no effect, request continues | A NextResponse without rewrite, Location or JSON type continues the chain | Return new Response(...) or NextResponse.json(...) |
| Redirect throws or goes nowhere | Relative URL | NextResponse.redirect(new URL("/login", request.url)) |
| Later middleware does not see a header | Header set on a response that stopped the chain, or set after the redirect | Set request.headers.set(...) before, in an earlier middleware |
Page cannot read header with headers() | Header set only on the response, not on the request | Set it with request.headers.set(...), NEMO forwards request header changes |
| Cookie lost on redirect | Cookie set on an unrelated NextResponse, not returned | Set on the response you return, or on a continuing response from an earlier middleware |
| Data from one request appears in another | On 3.0.2 and older the default storage is shared by all requests of that createNEMO (security issue). Fixed in the next release: the default is per request. A ready-made instance (storage: new Adapter()) is still shared | Upgrade; on 3.0.2 and older pass storage: () => new MemoryStorageAdapter(). Always prefer a factory |
event.log() prints nothing, even with debug: true | Check that debug: true is in the third argument of createNEMO. On 3.0.2 and older event.log is not wired to debug inside chains (fixed in the next release) | Upgrade; on 3.0.2 and older use event.warn / event.error or console.log |
Work started with event.waitUntil is cut off | On 3.0.2 and older waitUntil is not forwarded to the platform (fixed in the next release) | Upgrade; on 3.0.2 and older use after() from next/server |
req.params is undefined | It does not exist | event.params (or event.getParams(...)) |
StorageAdapter import fails | Not exported from the main entry | import { StorageAdapter } from "@zanreal/nemo/storage" |
NemoMiddlewareError: Middleware execution failed | A middleware threw and silent is false | Read error.originalError (the thrown value) and error.metadata (chain, pathname, routeKey, index); the message also names chain, path, route key and index; fix, or handle it with errorHandler |
| Next.js 16 ignores the file | Wrong name or export | proxy.ts with export const proxy, or legacy middleware.ts with export const middleware |
Debug options (third argument of createNEMO)
import { createNEMO } from "@zanreal/nemo";
import { NextResponse } from "next/server";
export const proxy = createNEMO(
{ "/api/:path*": () => {} },
undefined,
{
debug: true, // internal logs: matched routes, execution, errors
enableTiming: true, // time per chain (before/main/after)
silent: false, // true: swallow errors and continue instead of throwing
errorHandler: (error, metadata) => {
console.error("NEMO failed", metadata.chain, metadata.routeKey, metadata.index, error);
// return a response to use it, or nothing to fall back to throw/silent behavior
return NextResponse.json({ error: "Internal error" }, { status: 500 });
},
},
);
Error flow: a thrown error goes to errorHandler(error, metadata). A truthy return value becomes the response. Otherwise silent: false throws NemoMiddlewareError, silent: true continues with the next middleware.
metadata is { chain: "before" | "main" | "after"; index: number; pathname: string; routeKey: string; nestLevel?: number }.
Turn debug off in production unless you need it, it is verbose.
Bisecting a chain
- Add a header marker at the top of each suspect middleware:
request.headers.set("x-hit-a", "1"). - Request the path and inspect response headers (or
x-middleware-request-x-hit-ain tests). - The first marker that is missing shows where the chain stopped or where the route did not match.
- Check for the earlier middleware returning a stopping response.
Writing tests
Call the handler directly with a NextRequest and a stub event. No server needed. Templates for bun, vitest and jest are in references/testing.md. Core shape:
import { NextRequest, type NextFetchEvent } from "next/server";
import { createNEMO } from "@zanreal/nemo";
const event = { waitUntil: () => {} } as unknown as NextFetchEvent;
const proxy = createNEMO({ "/dashboard/:path*": () => Response.redirect("http://localhost/login") });
const res = await proxy(new NextRequest("http://localhost/dashboard/x"), event);
// res?.status === 302, res?.headers.get("location") === "http://localhost/login"
What to assert:
- redirect:
res.statusandres.headers.get("location") - rewrite:
res.headers.get("x-middleware-rewrite") - blocking response:
res.status - forwarded request header
x-foo:res.headers.get("x-middleware-request-x-foo") - response header:
res.headers.get("x-foo") - continue with no changes: a
NextResponse.next()-style response with headerx-middleware-next: 1
NEMO middleware patterns
Everything here describes @zanreal/nemo 3.0.x as the source and tests implement it. If the docs or README disagree, trust this file and the source.
Signature of every middleware:
import type { NextMiddleware } from "@zanreal/nemo";
// (request: NextRequest, event: NemoEvent) => NextResponse | Response | null | undefined | void (or a Promise of it)
event is a NemoEvent: a NextFetchEvent plus event.storage, event.params, event.getParams(), event.skip() and event.log/warn/error.
Continue or stop
| Return value | Chain |
|---|---|
undefined, null, nothing | continues |
NextResponse.next() (with or without { headers }) | continues, its headers are merged |
NextResponse.redirect(url) | stops |
NextResponse.rewrite(url) | stops |
NextResponse.json(...) | stops |
new Response(...), Response.redirect(...) | stops |
| thrown error | goes to errorHandler, see nemo-debugging |
The rule in the source: a NextResponse continues unless it has x-middleware-rewrite, a Location header or a JSON content type. Any other kind of result stops.
Trap: new NextResponse("Unauthorized", { status: 401 }) has none of those, so it CONTINUES and the 401 is lost. For a blocking response use new Response("Unauthorized", { status: 401 }) or NextResponse.json({ error: "Unauthorized" }, { status: 401 }).
Trap: NextResponse.redirect and rewrite need absolute URLs. Use new URL("/login", request.url) or request.nextUrl.clone().
Route matching in short
- Function or array at top level: exact path only (
"/foo"does not run for/foo/bar). - Object with child keys: prefix match, children joined to the parent path,
middlewarekey holds the parent's own function(s). Nested children are prefix matches too. "/"only runs for/.- Dynamic or wildcard patterns (
:,*,() use path-to-regexp v6, case insensitive. Plain paths are compared exactly (case sensitive). - Order: global
before, matched routes (by nesting depth, parents first; at the same depth, longer patterns first), globalafter. Within an array, in array order. - Details and syntax pitfalls:
references/matching.md.
Core patterns
Gate by path, redirect when not authenticated
import { createNEMO } from "@zanreal/nemo";
import { NextResponse } from "next/server";
export const proxy = createNEMO({
"/dashboard": {
middleware: (request) => {
if (!request.cookies.has("session")) {
const url = new URL("/login", request.url);
url.searchParams.set("next", request.nextUrl.pathname);
return NextResponse.redirect(url);
}
},
"/admin": (request) => {
if (request.cookies.get("role")?.value !== "admin") {
return new Response("Forbidden", { status: 403 });
}
},
},
});
The /dashboard function guards /dashboard and everything under it. /dashboard/admin (and /dashboard/admin/x, since nested children match as prefixes) runs the parent first, then the child. If the parent redirects, the child never runs.
Pass data to later middleware and to pages
Set request headers. NEMO diffs request headers at the end of the chain and forwards the changes to the page (readable with headers() from next/headers) and also puts them on the response.
import { createNEMO } from "@zanreal/nemo";
export const proxy = createNEMO(
{
"/:locale(en|pl)/:path*": (request, event) => {
const { locale } = event.params;
request.headers.set("x-locale", String(locale));
},
},
{
before: (request) => {
request.headers.set("x-request-id", crypto.randomUUID());
},
},
);
NextResponse.next({ request: { headers } }) and NextResponse.next({ headers }) from a continuing middleware are also merged for later middleware. Details: references/responses-and-headers.md.
Shared state inside one chain: event.storage
import { createNEMO } from "@zanreal/nemo";
import { MemoryStorageAdapter } from "@zanreal/nemo/storage";
export const proxy = createNEMO(
{
"/app/:path*": [
(request, event) => {
event.storage.set("userId", request.cookies.get("uid")?.value);
},
(request, event) => {
const userId = event.storage.get<string>("userId");
if (userId) request.headers.set("x-user-id", userId);
},
],
},
undefined,
{ storage: () => new MemoryStorageAdapter() },
);
Important: with no storage option, or with a storage INSTANCE, the same storage is shared by every request handled by that createNEMO. Data written in one request is visible in the next. Pass a factory storage: () => new MemoryStorageAdapter() for per-request isolation. event.storage is synchronous (get, set, has, delete, clear, keys, values, entries, size). Do not use the Storage interface exported from types, it is async and unused. See references/storage.md.
Skip the rest of a section
import { createNEMO } from "@zanreal/nemo";
export const proxy = createNEMO(
{
"/api/:path*": [
(request, event) => {
if (request.headers.get("x-internal") === "1") event.skip();
},
(request) => {
request.headers.set("x-checked", "1"); // skipped for internal calls
},
],
},
{ after: () => {} },
);
event.skip() skips the remaining middlewares of the current section (before, main or after). event.skip({ skipAfter: true }) also skips the global after chain.
Global before and after
import { createNEMO } from "@zanreal/nemo";
export const proxy = createNEMO(
{ "/": () => {} },
{
before: [(request) => { request.headers.set("x-start", String(Date.now())); }],
after: (request) => { request.headers.set("x-end", String(Date.now())); },
},
);
before and after accept one function or an array.
Work after the response
event.waitUntil(promise) hands the promise to the platform, so background work such as logging or analytics keeps running after the response is sent. Version note: this works in the first release after 3.0.2. On 3.0.2 and older the promise is not awaited and may be cut off; there, use after() from next/server (Next.js 15.1+) or move the work into the route handler.
More
references/matching.md: pattern syntax, what not to write, negative lookaheadreferences/responses-and-headers.md: headers, cookies, rewritesreferences/storage.md: adapter contract, per-request isolation, custom adapterreferences/recipes.md: auth gate, role check, i18n rewrite, Supabase session, other auth libraries, rate limit, logging
Migrate to NEMO
Pick the path that matches the project.
| Situation | Go to |
|---|---|
Imports from @rescale/nemo | references/from-rescale.md |
One big middleware.ts / proxy.ts with if (pathname...) branches | references/from-next-middleware.md |
| Next.js 15 to 16 (file and export rename) | references/next16-proxy.md |
Uses createMiddleware from NEMO | replace with createNEMO, same arguments |
Quick path: from @rescale/nemo
The API did not change in 3.0.0, only the package name. Projects still on @rescale/nemo 1.x must first move to the 2.x API (see the v1.4 docs), then rename.
npx @zanreal/nemo-codemod --dry # preview
npx @zanreal/nemo-codemod # apply to the current directory
Then reinstall with the project's package manager so the lockfile picks up @zanreal/nemo (npm install, pnpm install, yarn, bun install). The codemod does not touch lockfiles. Details and flags: references/from-rescale.md.
Quick path: from a single middleware
- Read the existing file and list every branch by path, plus anything that runs for all requests.
- Move each branch into a key of the NEMO config. Shared preamble goes to
globalMiddleware.before. - Keep the existing
config.matcherunchanged at first. - Replace
export function middleware(orproxy) byexport const middleware = createNEMO(...)(orproxy). - Test the old and new behavior on the same set of URLs.
Full mapping rules with before/after code: references/from-next-middleware.md.
Rules to keep behavior identical
- Old code usually returned early. In NEMO, "return nothing" continues the chain,
NextResponse.redirect/rewrite/jsonornew Response(...)stop it. Anew NextResponse(body, { status })does NOT stop it, convert tonew Response(...). startsWithchecks become prefix patterns ("/dashboard/:path*"or a nested object). A bare"/dashboard"matches only that exact path.- A
pathname === "/"branch becomes the"/"key, which also matches only the exact root. - Logic that must run for every request goes to
before(orafter), not to"/". - Do not copy
req.params,new NEMO(...)without.middleware, orNextResponse.redirect("/relative")from older blog posts.
Set up NEMO in a Next.js app
NEMO (@zanreal/nemo) composes many Next.js middlewares into one proxy.ts / middleware.ts. You describe routes as an object, NEMO runs the matching functions in a defined order and stops the chain when one returns a redirect, rewrite or other final response.
1. Detect the Next.js version and file name
Read next in package.json.
| Next.js | File | Export name |
|---|---|---|
| 16 or newer | proxy.ts | export const proxy |
| 15 or older | middleware.ts | export const middleware |
Put the file next to app/ (or inside src/ when the project uses src/). If the project already has one of these files, do not overwrite it: read it and follow the nemo-migrate skill.
2. Install
Use the project's package manager (check the lockfile):
npm install @zanreal/nemo
pnpm add @zanreal/nemo
yarn add @zanreal/nemo
bun add @zanreal/nemo
Peer dependency is next >=13. The package ships ESM only (its require condition points at the same ESM build). Next.js handles that; in Jest see nemo-debugging/references/testing.md.
3. Minimal file
Next.js 16+ (proxy.ts):
import { createNEMO, type MiddlewareConfig } from "@zanreal/nemo";
import { NextResponse } from "next/server";
const middlewares = {
"/dashboard/:path*": async (request, event) => {
request.headers.set("x-section", "dashboard");
return NextResponse.next();
},
} satisfies MiddlewareConfig;
export const proxy = createNEMO(middlewares);
export const config = {
matcher: ["/((?!_next/|_static|_vercel|[\\w-]+\\.\\w+).*)"],
};
Older Next.js (middleware.ts): same code, but export const middleware = createNEMO(middlewares);.
Rules that matter:
createNEMO(middlewares, globalMiddleware?, config?)returns the handler directly. Do not writenew NEMO(...)unless you also use.middleware(export const proxy = new NEMO({...}).middleware).- Do not use
createMiddleware. It is deprecated and prints a console warning. - Import
NextResponseandNextRequestfromnext/server.StorageAdapterandMemoryStorageAdaptercome from@zanreal/nemo/storage, not from the main entry. config.matchermust be a static literal in the same file (a Next.js rule). Next.js only calls the file for paths the matcher accepts, NEMO routes are applied after that.
4. Routes
The first argument maps path patterns to a function, an array of functions, or a nested object.
import { createNEMO } from "@zanreal/nemo";
import { NextResponse } from "next/server";
export const proxy = createNEMO(
{
// exact path only: runs for "/pricing", not for "/pricing/anything"
"/pricing": (request) => {
request.headers.set("x-page", "pricing");
},
// prefix with parameters: runs for "/blog", "/blog/a", "/blog/a/b"
"/blog/:path*": [
(request) => {
request.headers.set("x-section", "blog");
},
(request) => {
request.headers.set("x-blog", "1");
},
],
// nested: parent runs for the whole subtree, children add on top
// (nested children match as prefixes too: "/settings" also runs for /app/settings/x)
"/app": {
middleware: (request) => {
request.headers.set("x-app", "1");
},
"/settings": (request) => {
request.headers.set("x-settings", "1");
},
},
},
{
// global chains run on every request that reaches NEMO
before: (request) => {
request.headers.set("x-request-start", String(Date.now()));
},
after: () => NextResponse.next(),
},
{ debug: false, silent: false },
);
Key facts:
- A top-level key whose value is a function or array matches that exact path only.
"/foo"does NOT run for/foo/bar. Use"/foo/:path*"or a nested object for prefix matching. - A key whose value is an object with child keys matches as a prefix and children are joined to the parent path. Nested children also match as prefixes (
"/app": { "/settings": fn }runsfnfor/app/settingsand/app/settings/x). "/"runs only for the exact root path/. It is not a catch-all. For "every request" useglobalMiddleware.before.- Pattern syntax is path-to-regexp v6 (
:param,:param*,:param+,:param?,(regex)). Patterns with:,*or(match case insensitively; plain paths like"/pricing"are compared exactly, case included. An invalid pattern is logged withconsole.errorand never matches, nothing is thrown. - Order: global
before, then matched routes (parents before children; at the same depth, longer patterns first), then globalafter. - A middleware returning
undefinedorNextResponse.next()lets the chain continue.NextResponse.redirect,NextResponse.rewrite,NextResponse.jsonor a plainnew Response(...)end it. See thenemo-middleware-patternsskill for all rules.
5. Verify
- Start
next devand request a matched and an unmatched path. Setdebug: truein the third argument for NEMO's internal logs (event.logprints withdebug: truein the first release after 3.0.2; on 3.0.2 and older it prints nothing, useevent.warn). - Run the type checker.
satisfies MiddlewareConfiggives contextual types torequestandevent. - For unit tests see the
nemo-debuggingskill.
Checklist
- File name and export name match the Next.js version (
proxyvsmiddleware). -
export const config = { matcher: [...] }present and excludes_next, static files and assets. - No
createMiddleware, noreq.params(useevent.params), nonew NEMOwithout.middleware. - Prefix routes use
/:path*or nesting, not a bare path. - Redirect targets are absolute URLs:
new URL("/login", request.url). - Blocking responses use
new Response(...)orNextResponse.json(...), notnew NextResponse(body, { status }).
Sponsors
Details
- Marketplace
- zanreal-labs/nemo
- Category
- Community
