nextjs app-router ai_generated true

Module not found: Can't resolve 'fs' in client component

ID: nextjs/module-not-found-client-component

Also available as: JSON · Markdown
95%Fix Rate
96%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
14 active

Root Cause

Client component (use client) tries to import a Node.js-only module like fs, path, or child_process.

generic

Workarounds

  1. 96% success Move the Node.js code to a Server Component or API route
    Remove 'use client' from the component that needs Node.js APIs

    Sources: https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns

  2. 85% success Split server-only imports behind dynamic import with ssr: false
    import dynamic from 'next/dynamic';
    
    // Dynamically import component that uses Node.js APIs:
    const ServerChart = dynamic(() => import('./ServerChart'), {
      ssr: false,
      loading: () => <p>Loading chart...</p>
    });

    Sources: https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading

  3. 88% success Use 'server-only' package to prevent accidental client imports
    npm install server-only
    
    // Add at top of any server-only module:
    import 'server-only';
    // Now if a client component imports this file,
    // you get a clear build error instead of a cryptic runtime error

    Sources: https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns#keeping-server-only-code-out-of-the-client-environment

Dead Ends

Common approaches that don't work:

  1. Polyfilling the Node.js module for the browser 80% fail

    fs and child_process cannot be meaningfully polyfilled in browsers

  2. Installing the module from npm 85% fail

    fs is a built-in Node module; npm install fs installs a shim that doesn't work

Error Chain

Frequently confused with: