Next.js Discord

Discord Forum

Unable to reference file in public directory

Unanswered
Giant panda posted this in #help-forum
Open in Discord
Giant pandaOP
Hey 👋 ,

I'm currently referencing a .mdx file in one of my pages:

    const mdxText: string = readFileSync('./public/posts/microservice-discord-bots.mdx').toString();


However, I realise that when I deploy to vercel, this will not work as my project will be compiled, and thus I have changed this too:

const mdxText: string = readFileSync('/posts/microservice-discord-bots.mdx').toString();

As instructed here:

However, when I attempt to access this page in my deployment, I encounter the following message:
Application error: a server-side exception has occurred (see the server logs for more information).
Digest: 4185446599


With the following error:

Error: ENOENT: no such file or directory, open '/posts/microservice-discord-bots.mdx'
    at Object.openSync (node:fs:603:3)
    at readFileSync (node:fs:471:35)


This is despite my project's compiled directory looking like: (see attached image)

Any ideas why I may have this error?

1 Reply

Asian black bear
this not going to work. instead you can do this

const fileBuffer = await readFile(__dirname + "/posts" + "/microservice-discord-bots.mdx")

const post = fileBuffer.toString()

console.log(post)


please, note it that __dirname returns the current directory path of script file. So make sure adjust paths with your needs.