Search code examples
next.jspathnode.js-fsnext-api

next js api returns no response after deployment


while working on the local host, api and the posts.jaon file also works fine. was able to perform CRUD.But after I deploy it to vercel, the api does not loads. error in the log is something like this: [GET] /api/insta 11:39:32:83 [Error: ENOENT: no such file or directory, open './posts.json'] { errno: -2, code: 'ENOENT', syscall: 'open', path: './posts.json' }

expecting a json response in the browser when I hit the api.

the json file is in the pages/api folder of next app. I tried moving the json file outside pages at the top level of the folder strecture, and changing the path inside the fs("file.json",....). but nothing worked


Solution

  • This article from Vercel might help you:

    How to Load Data from a File in Next.js

    Here is an excerpt:

    import path from 'path';
    import { promises as fs } from 'fs';
    
    export default async function handler(req, res) {
      
      const jsonDirectory = path.join(process.cwd(), 'json');
      
      const fileContents = await fs.readFile(jsonDirectory + '/data.json', 'utf8');
      
      res.status(200).json(fileContents);
    }
    

    You would then have a folder named json where all the data is saved. That is declared in line 4. If you want to rename it, it is of course possible.

    enter image description here