Next.jsMedium

What runtime does middleware run on?

Since Next.js 16, Proxy (proxy.ts, the renamed middleware) runs on the Node.js runtime, and the runtime cannot be configured. Before that, middleware ran on the Edge runtime by default, with Node.js support added as stable in 15.5. The deprecated middleware.ts still uses the Edge runtime if you need it.

History

  • Next.js 12 to 14: middleware ran only on the Edge runtime (Web APIs, no fs, no native modules).
  • 15.2: experimental Node.js runtime for middleware.
  • 15.5: Node.js runtime for middleware became stable via export const config = { runtime: 'nodejs' }.
  • 16.0: middleware.ts renamed to proxy.ts. Proxy always uses Node.js; setting runtime in a proxy file throws an error.

What Node.js enables

  • Full npm compatibility: database clients, auth SDKs, node:crypto.
  • Easier code sharing with the rest of the app.

Still keep it fast

Proxy runs on every matched request, including client navigations and prefetches. Avoid slow network calls; if you need lookups (redirect maps, feature flags), use a fast store. fetch caching options and "use cache" do not work in Proxy.

Deployment note

Proxy is designed to run separately from your render code, and some platforms deploy it to their CDN layer. Do not rely on shared module state or globals between Proxy and the app; pass information via headers, cookies, rewrites or the URL.

Code example

tsx
1// proxy.ts - Node.js runtime: Node APIs are available
2import { createHmac, timingSafeEqual } from "node:crypto";
3import { NextResponse, type NextRequest } from "next/server";
4
5function validSignature(value: string, sig: string) {
6 const expected = createHmac("sha256", process.env.SIGNING_SECRET!).update(value).digest();
7 const given = Buffer.from(sig, "hex");
8 return given.length === expected.length && timingSafeEqual(given, expected);
9}
10
11export function proxy(request: NextRequest) {
12 const [value, sig] = (request.cookies.get("preview")?.value ?? "").split(".");
13 if (request.nextUrl.pathname.startsWith("/preview") && !(value && sig && validSignature(value, sig))) {
14 return new NextResponse("Forbidden", { status: 403 });
15 }
16}
17
18// export const config = { runtime: "edge" }; // Error in proxy.ts
19// Legacy middleware.ts can still run on Edge (deprecated).

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app