Next.js Discord

Discord Forum

Next.js: "Module not found: Can't resolve 'fs'" in page router when using fs only in getStaticProps

Unanswered
Western paper wasp posted this in #help-forum
Open in Discord
Western paper waspOP
I'm working on a Next.js project using the page router. I want to use a function (buildSidebar) that uses fs inside getStaticProps for my docs section. My expectation is that this function should only run on the server side. However, when I run npm run dev (in development), I still get the following error:

Module not found: Can't resolve 'fs'


Here's a simplified version of my code:

// pages/[collection]/[[...slug]].tsx
export const getStaticProps: GetStaticProps = async ({ params }) => {
    const collection = String(params?.collection);
    // ...other code omitted...
    return {
        props: {
            // ...other props...
            extra: COLLECTIONS[collection as keyof typeof COLLECTIONS].extra(),
        },
    };
};

export const COLLECTIONS = {
    docs: {
        // buildSidebar uses fs internally
        extra: () => ({ sidebar: buildSidebar() }),
    },
    // ...other collections...
} satisfies Record<string, CollectionConfig>;

// ...other unrelated component code omitted...

const DynamicPage: NextPage<PageProps> = ({
    // props omitted
    extra
}) => {
    const router = useRouter();
    const cfg = COLLECTIONS[router.query.collection as keyof typeof COLLECTIONS];
    const Layout = cfg.layout;
    // ...
};


I thought getStaticProps only runs on the server, so using fs here should be fine.
Why does Next.js (with the page router) still try to bundle fs and fail to resolve it, even though it's only used in getStaticProps?
How should I structure my code so that anything using fs is strictly server-side and never included in the client bundle?


* buildSidebar is a function that uses fs to generate the sidebar config for the docs section.
* The error happens when running npm run dev (development mode), not during build or runtime in production.
* I'm using Next.js 13 (page router, not app router).

What I've tried:
* Making sure buildSidebar is only called inside getStaticProps.
* Searching for related issues, but most answers just say “don’t use fs on the client,” which I already understand.

What's the recommended way to organize this in Next.js with the page router?

0 Replies