Search code examples
next.jsvercel

process.cwd() Different paths in development and production environment


I'm using next js 14.

In each page folder I have a file (meta.md) that I read using fs. Let it be written accordingly to these files

const postsDirectoryPath = process.cwd();

In the development environment, everything works and the files are read, this is understandable, since process.cwd refers to the root directory of the project. But on the vercel, process.cwd refers to .next, where naturally the meta.md file no longer exists. I have some problems with debugging on Vercel and I can't keep track of everything.

But there is some confusion about how this works in production, since I call my function that reads the files in the top page.tsx (homepage) file and it surprisingly works. Doesn't work if the md file reading function is called at levels below (another pages in another folders)


Solution

  • If you use static rendering, you can read and process local files. If you run next dev, the dev server has access to these files and you can probably read them. Never tested.

    If you use dynamic rendering, the server does not have access to these files.

    I think, what you want to do is not the recommended way. Use static rendering and access metadata while generating the pages. If you use dynamic rendering, you should fetch metadata from an external store or API.

    Update after comment discussion below:

    If you use the new App Router (recommended), data fetching is different. You don't use getStaticProps anymore. The tutorial you refer to uses Page Router.

    You have to ensure that all pages accessing the file system are statically generated. Use generateStaticParams to do this.

    Tip: When done, run next build and look to the final statistics. You can see which pages are static. See legend:

    ○ (Static) prerendered as static content

    λ (Dynamic) server-rendered on demand using Node.js

    Valuable sources for your use case: