React & Next.js errors · Error 07 of 7

Next.js “Module not found: Can't resolve 'fs'”

By Muhammad Abdullah, full-stack, mobile and ai automation developer · Last reviewed

Module not found: Can't resolve 'fs'

Short answer

Server-only Node.js code (fs, path, database clients) is being bundled into browser code. Move it to a Server Component, a Route Handler or a server action, and import it only from server files.

Common causes

  • Importing a server utility from a component marked "use client".
  • A library meant for Node.js used in client code.

How to fix it

  1. Move file-system or database access into server code, such as a Route Handler:

                          // app/api/data/route.ts
    import { readFile } from "node:fs/promises";
    
    export async function GET() {
      const data = await readFile("data.json", "utf8");
      return Response.json(JSON.parse(data));
    }
                        
  2. Optionally add import "server-only"; to server modules so accidental client imports fail at build time.

Let’s talk about the next step

Have an idea, a stuck app, or a workflow toimprove?

Tell me what you are building, what is blocking you, and what a successful outcome looks like.