Fix: Module not found 'fs' in Next.js Edge Runtime

The Symptom

You deployed a Next.js application or created an API route/middleware that tries to read a file, execute a child process, or use a Node.js standard library. The build fails, or the endpoint crashes with one of these fatal errors:

Module not found: Can't resolve 'fs'

OR

Error: The Edge Runtime does not support Node.js 'fs' module.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime

The Cure

You cannot use native Node.js filesystem modules inside an Edge environment. You must explicitly tell Next.js/Vercel to run this specific API route or Server Component using the standard Node.js runtime instead of the Edge runtime.

Immediate Resolution (App Router / API Route):

Export the runtime constant at the very top of your file.

javascript
import fs from 'fs';
import path from 'path';

// 1. Force the standard Node.js runtime
export const runtime = 'nodejs'; 

export async function GET(request) {
  // 2. You can now safely use 'fs' to read files
  const filePath = path.join(process.cwd(), 'data', 'config.json');
  const fileContents = fs.readFileSync(filePath, 'utf8');
  
  return new Response(fileContents, { status: 200 });
}

The Breakdown

Not all servers are built the same. Modern hosting platforms like Vercel offer two distinct environments for running your backend code:

Prevention & Edge Alternatives

If you absolutely need your code to run on the Edge for maximum speed (such as inside Next.js middleware.js, which only supports Edge), you must rewrite your logic using standard Web APIs instead of Node.js modules.

javascript (Edge Safe Alternatives)
// INSTEAD OF NODE.JS CRYPTO:
// import crypto from 'crypto'; 
const uuid = crypto.randomUUID(); // Use standard Web Crypto API natively

// INSTEAD OF FS.READFILE:
// import fs from 'fs';
// You cannot read local files on the edge. You must fetch them from an external bucket/API.
const data = await fetch('https://your-bucket.s3.amazonaws.com/config.json').then(res => res.json());

Developer Logs

Loading logs...