3

[SOLVED]

I have created a dynamic API route in NextJS that, if given a filename, the server will read the file (.md or .txt file) under the content directory, convert it into string and returns it. The API works as intended in local environment, however, the deployed website in Vercel doesn't work properly for this API route.

That API route, for a file that exists in the content directory, returns 500 internal server error.

The console error is:

Failed to load resource: the server responded with a status of 500 ()

Checking the vercel logs for the route, showed this:

ERROR Error: ENOENT: no such file or directory, open 'content/phase1_section1.md'

I think the path.join() is not working for me. It is not adding the actual domain name of the app in front of the content part. How can I resolve this?

And, here's the code

import { readFileSync } from 'fs';
import path from "path";

export default function courseHandler({ query: { slug } }, res) {
    const fullPath = path.join('./content/', slug);
    const content = readFileSync(fullPath, 'utf8');
    if (content) {
        res.status(200).json({
            content: content
        });
    } else {
        res.status(404).json({ message: `Course with slug: ${slug} not found.` })
    }
}
5
  • 1
    A 500 error can be anything. Can you check out the logs in Vercel? Commented Dec 14, 2021 at 9:06
  • Yes, just checked. I think the path is not working for me. ERROR Error: ENOENT: no such file or directory, open 'content/phase1_section1.md' It is not adding the actual domain name of the app in front of the content part. How can I resolve this? Commented Dec 14, 2021 at 9:13
  • Can you locate content/phase1_section1.md on the environment where your API is running? Commented Dec 14, 2021 at 9:15
  • Thanks for your comment. I solved the issue. The issue was with file path. Commented Dec 14, 2021 at 9:27
  • Faced Same problem and find solution Commented Oct 20, 2022 at 11:54

2 Answers 2

4

The problem is actually solved.

I just replaced this

path.join('./content/', slug);

with this

path.join(process.cwd(), 'content', slug);
Sign up to request clarification or add additional context in comments.

Comments

3
  1. Check logs on Vercel
  2. Configure yours .env variables on Vercel for each environment
  3. Check your local .env files. if you hardcoded your .env variables - this will cause a negative impact.

1 Comment

Thanks for your comment. I set the variables right. But the issue was with file path.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.