Module not found: Can't resolve 'fs'
Next.js · updated 2026-11-05
Printed by next build or the dev server while bundling for the browser, followed by an import trace from a client file to the module that needs fs. Node built-ins such as fs, net, tls and child_process do not exist in browser bundles.
Failed to compile.
./lib/posts.ts:2:1
Module not found: Can't resolve 'fs'
1 | import matter from 'gray-matter';
> 2 | import fs from 'fs';
| ^
3 | import path from 'path';
https://nextjs.org/docs/messages/module-not-found
Import trace for requested module:
./components/post-list.tsx
./app/blog/page.tsxQuick fix
Follow the import trace under the error to the first file marked 'use client' (or a Pages Router component) and cut the chain there. Keep fs usage in Server Components, route handlers, server actions or getServerSideProps, and add import 'server-only' to that module so a future client import fails clearly.
- Read the import trace printed below the error.
- Find the first file in the trace that is a client component.
- Move the fs call into a server-side module and pass the result down as props.
- Split barrel files (index.ts) that export both server and client helpers.
- Add import 'server-only' at the top of modules that touch the filesystem.
// lib/posts.ts: server only
import 'server-only';
import { readFile } from 'node:fs/promises';
export async function getPost(slug: string) {
if (!/^[a-z0-9-]+$/.test(slug)) throw new Error('invalid slug');
return readFile(`content/${slug}.md`, 'utf8');
}
// app/blog/[slug]/page.tsx: Server Component (no 'use client')
import { getPost } from '@/lib/posts';
import { PostBody } from './post-body'; // client component gets plain text
export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
return <PostBody markdown={await getPost(slug)} />;
}Paste this into Claude Code, Cursor or Codex in the project that throws it. The agent reads this guide in plain text and applies the fix that matches your stack.
Read https://runheed.com/errors/module-not-found-fs.md and fix this error in this project.Why it happens
A client component imports server code
A file marked 'use client' imports a helper that reads files: a config loader, a markdown reader, a logger with a file transport. Everything a client file imports is bundled for the browser, fs included.
Barrel files mix server and client exports
lib/index.ts re-exports a pure formatting helper and a function that uses fs. Importing only the harmless helper through the barrel still makes the bundler resolve the whole file, and module resolution happens before tree shaking can drop anything.
Node-only package used from the browser
Packages written for Node (dotenv, database drivers, many server SDKs, file-based loggers) get pulled into a client component. Check whether the package ships a browser build; if not, call it from the server.
Pages Router: fs outside data functions
In pages/, Next strips fs from the client bundle only when it is used inside getServerSideProps or getStaticProps. Using it in the component body, or in a helper the component also calls, keeps it in the browser bundle.
A library guards fs at runtime
Some packages require('fs') behind a check that never runs in the browser. The bundler still has to resolve the import, so these need a resolve fallback or alias rather than moving your code.
Other fixes
- For a library that only touches fs behind a server check, set resolve.fallback = { fs: false } for client builds in the webpack config.
- Under Turbopack, alias the module for browser builds with turbopack.resolveAlias, for example fs: { browser: './empty.ts' }.
- Swap the Node-only package for one with a browser build, or call it through a route handler.
Same error, other wording
- Module not found: Error: Can't resolve 'fs' in '/app/node_modules/x/lib'
- Module not found: Can't resolve 'child_process'
- Module not found: Can't resolve 'net'
- UnhandledSchemeError: Reading from "node:fs" is not handled by plugins (Unhandled scheme).
Let your coding agent catch the next one
This error stops the build, before your app runs, so Runheed doesn't record it. What it does record is the exceptions your running server code throws (route handlers, server rendering, API errors and background jobs) with the stack trace and the breadcrumbs before them, and serves those errors to Claude Code, Cursor or any MCP client.
Setup for Next.js or Vercel Functions, then have your agent fix and resolve it.
Related errors
- Error [ERR_REQUIRE_ESM]: require() of ES Module ... not supported.
- An error occurred in the Server Components render. The specific message is omitted in...
- Hydration failed because the server rendered HTML didn't match the client. As a result...
- Dynamic server usage: Route /x couldn't be rendered statically because it used `headers`.
More in Imports and modules
- TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /app/src/index.tsNode.js
- Error: Cannot find module 'x'Node.js
- SyntaxError: Cannot use import statement outside a moduleNode.js
- Module not found: Can't resolve '@/components/OrderTable'Next.js
- ModuleNotFoundError: No module named 'x'Python
- ImportError: cannot import name 'x' from partially initialized module 'y' (most likely...Python
- ImportError: attempted relative import with no known parent packagePython
- AttributeError: module 'requests' has no attribute 'get'Python
- TypeError: 'module' object is not callablePython
- ImportError: libGL.so.1: cannot open shared object file: No such file or directoryPython
- Error: Could not load the "sharp" module using the linux-x64 runtimeNode.js
Other error topics
- Error: 429 You exceeded your current quota, please check your plan and billing details.Network and HTTP
- Error: write EPIPENetwork and HTTP
- BrokenPipeError: [Errno 32] Broken pipeNetwork and HTTP
- error: invalid input syntax for type uuid: "undefined"Databases
- MongoServerError: E11000 duplicate key error collection: app.users index: email_1 dup...Databases
- psycopg.errors.UndefinedColumn: column "titel" does not existDatabases
- Objects are not valid as a React child (found: object with keys {id, name, total}). If...React and Next.js rendering
- Error: Event handlers cannot be passed to Client Component props.React and Next.js rendering
- TypeError: Failed to parse URL from /api/ordersReact and Next.js rendering
- ERR_INVALID_ARG_TYPE: The "path" argument must be of type string. Received undefinedUndefined, None and type errors
- TypeError: __init__() got an unexpected keyword argument 'proxies'Undefined, None and type errors
- java.lang.NullPointerException: Cannot invoke "String.toLowerCase()" because the return...Undefined, None and type errors
- SyntaxError: Unexpected end of JSON inputJSON, parsing and validation
- RangeError: Invalid time valueJSON, parsing and validation
- pydantic_core._pydantic_core.ValidationError: 1 validation error for User email Field...JSON, parsing and validation
- MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error...Memory, async and the process
- botocore.exceptions.NoCredentialsError: Unable to locate credentialsMemory, async and the process
- RuntimeError: Event loop is closedMemory, async and the process
- Bad Request: No valid session ID providedMCP servers and clients
- Error executing tool get_orderMCP servers and clients
- McpError: MCP error -32001: Request timed outMCP servers and clients
Free tools: Source map stack trace decoder · Uptime and SLA downtime calculator · Error budget calculator · Stack trace formatter · JSON log viewer · HTTP status code reference.
References: Next.js: Module Not Found, Next.js: Server and Client Components
Spotted a mistake? Email hello@greatwork.company. About Runheed.