javascriptnext.jsserver-side-renderingvercelproduction-environment

Error: ENOENT: no such file or directory, open '/var/task/src/content/hello.mdx' - Next.js blog Vercel production deployment error


I am building a blog section for my personal website. I am not able to open a blog post due to the following error:

(Vercel logs)

Error: ENOENT: no such file or directory, open '/var/task/src/content/hello.mdx'
    at Object.openSync (node:fs:601:3)
    at Object.readFileSync (node:fs:469:35)
    at PostPage (/var/task/.next/server/app/posts/[slug]/page.js:381:45)
    at S (/var/task/.next/server/chunks/789.js:6503:13)
    at eb (/var/task/.next/server/chunks/789.js:6618:21)
    at Array.toJSON (/var/task/.next/server/chunks/789.js:6422:20)
    at stringify (<anonymous>)
    at pb (/var/task/.next/server/chunks/789.js:6829:9)
    at mb (/var/task/.next/server/chunks/789.js:6728:29)
    at Timeout._onTimeout (/var/task/.next/server/chunks/789.js:6553:16) {
  errno: -2,
  syscall: 'open',
  code: 'ENOENT',
  path: '/var/task/src/content/hello.mdx'
}

I get the following error message when i visit a blog post on my portfolio:

Application error: a server-side exception has occurred (see the server logs for more information). Digest: 2113801254

Project directory structure:

my-app/
└── src/
    ├── app/
    │   ├── posts/
    │   │   ├── page.js
    │   │   └── [slug]/
    │   │       └── page.js or PostPage
    │   └── page.js
    ├── layout.js
    ├── page.js
    ├── components
    ├── content/
    │   └── hello.mdx
    └── fonts

Error shows that PostPage file has error in the code. I have written the following code:

export default function PostPage({ params }) {
  const post = fs.readFileSync(
    path.join(__dirname, "../../../../../src/content/" + params.slug + ".mdx"),
    "utf-8"
  );
  const { data: frontmatter, content } = matter(post);
  const blog = DOMPurify.sanitize(
    marked.parse(content, { mangle: false, headerIds: false })
  );
.....
//returns jsx with markdown content
}

I have tried changing path in readFileSync() but nothing works in production. It is working in local dev mode. Kindly Help.

Please note that i am a beginner in programming and nextjs or vercel. Thanks


Solution

  • You are using wrong path here -> path.join(__dirname, "../../../../../src/content/" + params.slug + ".mdx"), '__dirname' is your root folder. Try logging __dirname or you should use process.cwd()