Next.js middleware breaks when it imports Node.js crypto
Middleware or a package it imports fails to build because the Edge runtime does not support the Node.js crypto moduleShort answer
Middleware runs on the Edge runtime by default, and that runtime has no native Node.js modules such as crypto. Either rewrite the code with the Web Crypto API (crypto.subtle), switch the middleware to the Node.js runtime on Next.js 15.5 or later, or move to proxy.ts on Next.js 16, which runs on Node.js.
Fix it fast
1Find out which cause you have
Find what pulls crypto into the middleware bundle. Search the middleware file and the files it imports for Node-only imports.
grep -rnE "from ['\"](node:)?(crypto|fs|path|stream|buffer)['\"]|require\(" middleware.ts src/middleware.ts lib 2>/dev/null2Match what you see, then jump to its fix
- 1
The import is import crypto from 'crypto' or require('crypto') in a file the middleware loads.Your own code calls Node's crypto instead of the Web Crypto APIFix - 2
Your code has no crypto import, but the build trace points into node_modules (a JWT, session or password-hashing package).A package you import uses native Node.js APIsFix - 3
Next.js is 15.5 or newer, the code genuinely needs a Node.js module, and middleware.ts has no runtime setting.Middleware can run on Node.js from Next.js 15.5, but you did not select itFix - 4
Next.js is 16 or newer and the file is still middleware.ts, or the file is proxy.ts and still sets a runtime.On Next.js 16 the file should be proxy.ts, which uses Node.jsFix
- 1
What does the error look like?
Middleware or a package it imports fails to build because the Edge runtime does not support the Node.js crypto moduleA JWT or password library works in a route handler but fails as soon as middleware.ts imports it
Cause 1 of 4
Your own code calls Node's crypto instead of the Web Crypto API
1Check
The Edge runtime lists crypto, CryptoKey and SubtleCrypto from the web platform as supported, and says native Node.js APIs are not. So the global crypto object works, but the node:crypto module does not.
grep -rn "createHash\|createHmac\|randomBytes" middleware.ts lib2Fix
Replace the Node call with its Web Crypto equivalent. A SHA-256 hash, for example, becomes crypto.subtle.digest, which returns a promise, so the middleware function must be async.
// middleware.ts: no import needed, crypto is a global on the Edge runtime
async function sha256Hex(text: string) {
const data = new TextEncoder().encode(text)
const hash = await crypto.subtle.digest('SHA-256', data)
return Array.from(new Uint8Array(hash))
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
}3Verify
Run the build and request a route the middleware matches.
npm run buildConfirmed by nextjs.org
Cause 2 of 4
A package you import uses native Node.js APIs
1Check
The docs allow node_modules in the Edge runtime only when the package is an ES module and does not use native Node.js APIs. Open the package's entry file or its README to see whether it targets Edge or the Web Crypto API.
npm ls --all 2>/dev/null | grep -iE "jsonwebtoken|bcrypt|jose"2Fix
Use a package that is written for the Edge runtime or for Web Crypto, or keep the heavy check out of middleware and do it in a route handler or server code, where the full Node.js runtime is available.
// middleware.ts: keep only a cheap check here
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
if (!request.cookies.has('session')) {
return NextResponse.redirect(new URL('/login', request.url))
}
return NextResponse.next()
}3Verify
Rebuild; the Node-only package must no longer appear in the middleware bundle.
npm run buildConfirmed by nextjs.org
Cause 3 of 4
Middleware can run on Node.js from Next.js 15.5, but you did not select it
1Check
Middleware defaults to the Edge runtime. Node.js runtime support became stable in 15.5.0 (experimental in 15.2.0). Check your version first.
npx next --version2Fix
Set the runtime to nodejs in the config object of the middleware file.
// middleware.ts
export const config = {
runtime: 'nodejs',
matcher: '/dashboard/:path*',
}3Verify
Rebuild and request a matched route; the Node-only import now loads.
npm run buildConfirmed by nextjs.org
Cause 4 of 4
On Next.js 16 the file should be proxy.ts, which uses Node.js
1Check
In version 16 the middleware convention is renamed to proxy. Proxy defaults to the Node.js runtime and the runtime option is not available there; setting it throws an error. Edge is not supported in proxy, so keep middleware.ts only if you need Edge.
ls middleware.* proxy.* src/middleware.* src/proxy.* 2>/dev/null2Fix
Run the codemod to rename the file and the exported function, then delete any runtime line from the config.
npx @next/codemod@canary middleware-to-proxy .3Verify
Rebuild, then request a route the proxy matches.
npm run buildConfirmed by nextjs.org
How do I stop it coming back?
- Treat middleware as a thin gate: read cookies, redirect, rewrite. Put hashing, database calls and token signing in route handlers or server code.
- Before adding an auth or JWT package, check whether its docs say it supports the Edge runtime.
- Pin the Next.js version in package.json and read the middleware or proxy page of the matching docs version when you upgrade.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Web apps
Upgrading to Next.js 16: middleware becomes proxy, and the other things that break
Missing Required default.js for Parallel Route
Next.js 16 renames middleware.ts to proxy.ts and its exported function to proxy.
6 causes, each with a fixWeb apps
Apollo Server rejects a request as a potential CSRF
HTTP 400 Bad Request from the GraphQL endpoint
Apollo Server's CSRF prevention is on by default.
3 causes, each with a fixWeb apps
Clerk cannot read its publishable key in a Next.js app
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY is undefined
Clerk reads NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY.
3 causes, each with a fixWeb apps
The shell cannot find create-next-app
command not found: create-next-app
create-next-app is not meant to be installed as a shell command.
2 causes, each with a fixWeb apps
ESLint fails with: Cannot find module 'next/babel'
ESLint stops on the first file with a Babel or parser error instead of listing lint results
next/babel is a Babel preset that ships inside the next package.
3 causes, each with a fixWeb apps
Firebase Auth says the API key is not valid
Firebase: Error (auth/api-key-not-valid.-please-pass-a-valid-api-key.)
The apiKey your app sends is either empty, wrong, or blocked.
4 causes, each with a fix