Route handler unable to read json file
Answered
Masai Lion posted this in #help-forum
Masai LionOP
In my app, I have a function where I am reading data from a stored json file.
I call it like this
When I use this file in a server component, it works perfectly fine and displays the data I want. However when I try to do the same in a route handler, it works locally but not when deployed. I have a vercel cron job that is supposed to hit this endpoint on a schedule but I just get this error
Are route handlers not supposed to be able to interact with the file system while deployed or am I doing this wrong? Should it be stored in a different folder? is the way I am referencing the path incorrect?
export async function readJson(filePath: string): Promise<Pokemon[]> {
try {
const segments = filePath.split("/");
const fullPath = path.join(process.cwd(), "src", ...segments);
const data = await fs.readFile(fullPath, "utf8");
return JSON.parse(data);
} catch (error) {
console.error(error);
return [];
}
}I call it like this
const pokedex = await readJson("/data/pokedex.json");When I use this file in a server component, it works perfectly fine and displays the data I want. However when I try to do the same in a route handler, it works locally but not when deployed. I have a vercel cron job that is supposed to hit this endpoint on a schedule but I just get this error
[Error: ENOENT: no such file or directory, open '/var/task/src/data/pokedex.json'] {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: '/var/task/src/data/pokedex.json'
}Are route handlers not supposed to be able to interact with the file system while deployed or am I doing this wrong? Should it be stored in a different folder? is the way I am referencing the path incorrect?
Answered by Masai Lion
hi thank you for the response. I was able to solve the error by completing doing away with my fs approach and instead just importing the json file directly. That seemed to work
5 Replies
next doesn't output a
src folder when built. you can verify this on vercel with Deployment > Source > Output@josh next doesn't output a `src` folder when built. you can verify this on vercel with Deployment > Source > Output
Masai LionOP
hi thank you for the response. I was able to solve the error by completing doing away with my fs approach and instead just importing the json file directly. That seemed to work
Answer
Masai LionOP
Also I had no idea I could see what the uilt files on vercel looked like. I'm sure ill need that in the future
Did you copy the
.json file to your build files?JSON import is the way to go here, webpack will handle the bundling part so no need to worry about copying files and finding file paths