Skip to content
Happy Programming Guide
Start learning
JavaScript

Fixing “Module not found: Can’t resolve ‘fs'” in Next.js

This means Node-only code is being bundled for the browser. Here is how to find which import pulled it in, and the four ways to fix it.

Keys of a mechanical keyboard seen up close

Module not found: Can't resolve 'fs' in Next.js means something in your client bundle is importing a Node built-in. Browsers have no filesystem, so fs, path, crypto and child_process do not exist there. The fix is not to shim the module — it is to keep that code on the server.

What it means#

Next.js builds two bundles: one that runs on the server and one that is sent to the browser. Anything imported by a client component ends up in the second, and Node built-ins have no browser implementation.

JavaScript
"use client";

import fs from "fs";        // Module not found: Can't resolve 'fs'

export default function Page() {
  return <div>Hello</div>;
}

Often it is not your import at all. A library you use imports fs internally, and pulling that library into a client component drags it along.

Step 1: find what pulled it in#

The error usually shows an import trace. Read it from the bottom up — the last entry is your file, and the chain above shows how the Node module got there.

Output
Import trace for requested module:
./node_modules/some-lib/index.js
./lib/analytics.js
./app/dashboard/page.tsx

Here analytics.js is importing a library that uses fs. Either the page is a client component and should not be, or analytics.js should only run on the server.

Terminal
ANALYZE=true npm run build

The bundle analyser shows what is actually in the client bundle, which is worth checking when the trace is not obvious.

Fix 1: keep it in a Server Component#

In the App Router, components are server components by default. The "use client" directive is what moves a file — and everything it imports — into the browser bundle.

JavaScript
// app/page.tsx - no "use client", so this runs on the server
import fs from "node:fs/promises";

export default async function Page() {
  const data = await fs.readFile("data/config.json", "utf8");
  const config = JSON.parse(data);

  return <Dashboard config={config} />;
}

Server components can read files, query databases and use secrets, because none of that code is ever sent to the browser.

Fix 2: push the client boundary down#

JavaScript
// app/dashboard/page.tsx - server component
import { readConfig } from "@/lib/config";        // uses fs, stays on the server
import { Chart } from "./chart";                  // the only client part

export default async function Page() {
  const config = await readConfig();
  return (
    <section>
      <h1>{config.title}</h1>
      <Chart data={config.series} />
    </section>
  );
}
JavaScript
// app/dashboard/chart.tsx
"use client";

import { useState } from "react";

export function Chart({ data }) {
  const [zoom, setZoom] = useState(1);
  return <div onClick={() => setZoom(z => z + 1)}>{/* ... */}</div>;
}

The page stays on the server and only the interactive chart ships to the browser. This is the pattern that resolves most of these errors, and it makes the bundle smaller as a side effect.

Fix 3: mark modules server-only#

Terminal
npm install server-only
JavaScript
// lib/config.js
import "server-only";
import fs from "node:fs/promises";

export async function readConfig() {
  return JSON.parse(await fs.readFile("data/config.json", "utf8"));
}

Now importing this from a client component fails at build time with a clear message naming the file, rather than an obscure module resolution error. It is a guard rail, and it is worth adding to anything that touches secrets or the filesystem.

Fix 4: a route handler#

When the browser genuinely needs the data, fetch it rather than importing the code:

JavaScript
// app/api/config/route.js
import fs from "node:fs/promises";

export async function GET() {
  const data = await fs.readFile("data/config.json", "utf8");
  return Response.json(JSON.parse(data));
}
JavaScript
// A client component
"use client";
import { useEffect, useState } from "react";

export function Settings() {
  const [config, setConfig] = useState(null);

  useEffect(() => {
    fetch("/api/config").then(r => r.json()).then(setConfig);
  }, []);

  return config ? <pre>{JSON.stringify(config, null, 2)}</pre> : <p>Loading</p>;
}

The webpack fallback#

This is the fix most search results suggest, and it is the one to reach for last:

JavaScript
// next.config.js
module.exports = {
  webpack: (config, { isServer }) => {
    if (!isServer) {
      config.resolve.fallback = { ...config.resolve.fallback, fs: false };
    }
    return config;
  },
};

This tells webpack to replace fs with an empty module in the browser bundle. The build succeeds and any code path that actually calls it fails at run time instead.

The Pages Router equivalents#

JavaScript
// Only runs on the server; Next.js strips it from the client bundle
export async function getServerSideProps() {
  const fs = await import("node:fs/promises");
  const data = await fs.readFile("data/config.json", "utf8");
  return { props: { config: JSON.parse(data) } };
}
JavaScript
// Or load a browser-only library dynamically
import dynamic from "next/dynamic";

const Map = dynamic(() => import("../components/Map"), { ssr: false });

ssr: false is the mirror image of this problem — a library that needs window and breaks during server rendering.

The same error, other modules#

Module Usual cause Fix
fs reading files server component or route handler
path a utility used on both sides split it, or use browser APIs
crypto hashing the Web Crypto API in the browser
child_process running a command server only, always
net, tls a database driver server only, always

A database driver in a client bundle is worth stopping for — it means your connection string was about to be shipped to the browser.

Preventing it#

  • Default to server components. Add "use client" only where you need state, effects or event handlers.
  • Keep server code in its own folder — lib/server/ — and mark it with server-only.
  • Do not put shared utilities and filesystem code in the same module. One import pulls in both.
  • Use node: prefixes — node:fs rather than fs — which makes the intent unmistakable to both readers and tooling.

Questions people ask#

Why does it work in development and fail on build?

Development builds are more forgiving about module resolution, and code paths that are never executed may not be bundled. The production build analyses everything.

Can I use fs in a Server Action?

Yes. Server Actions run on the server, so Node built-ins are available.

Is the webpack fallback ever correct?

Yes, when a third-party library imports a Node module behind a run-time check that the browser never passes. It is wrong whenever your own code depends on it working.

How do I know what is in my client bundle?

Run the build with the bundle analyser enabled. It shows every module in the client output by size, which usually makes the offending import obvious immediately.

Where to go next#

Judging a JavaScript dependency before you add itRead next

Keep reading

JavaScript

Asynchronous JavaScript

The event loop, callbacks, promises and async/await — what actually happens when JavaScript waits, and the four mistakes that cause most async…

6 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *