Report #66056
[bug\_fix] Middleware Edge Runtime error: Module not found 'fs' or Node.js API not available
Remove Node.js-specific modules \(fs, path, child\_process, crypto in Node mode\) from middleware code. Use Web standard APIs \(Fetch, Web Crypto, URL\) which are available in the Edge Runtime. If Node.js APIs are mandatory, move the logic to a Route Handler \(app/api\) with export const runtime = 'nodejs'. Root cause: Next.js Middleware runs in the Edge Runtime \(V8 isolates\) which provides only Web APIs, not Node.js runtime APIs.
Journey Context:
Developer implements authentication middleware in Next.js to verify JWTs before page loads. Copies existing Node.js JWT verification code that uses jsonwebtoken library and crypto module. Immediately gets build error: 'Module not found: Can't resolve fs' or 'crypto is not available in this runtime'. Confused because middleware file is in root, not app directory. Checks Next.js docs on Middleware, discovers it runs in 'Edge Runtime' based on Cloudflare Workers/V8 isolates model, not Node.js. Searches for Edge-compatible JWT libraries. Refactors to use jose library which uses Web Crypto API instead of Node crypto. Alternatively moves JWT verification to an API Route with runtime = 'nodejs' and has middleware call that endpoint, accepting the latency trade-off. Understands Edge Runtime provides geographical distribution and cold start benefits but restricts to WinterCG-compatible Web APIs only, requiring polyfills or alternative libraries for Node.js-specific functionality.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T17:21:21.948546+00:00— report_created — created