Serving a static json file as an API endpoint

Often when prototyping an app we need to fetch data from an API endpoint that is not implemented yet. Developers usually mock the data in a json file and then fetch that data by sending a request to an endpoint. There is an npm package called json-server which exactly does this job, however that server runs on localhost, so when you push your prototype to a remote server, the json server will stop working. To avoid this problem we can run a Node.js function on a serverless platform like Vercel which would return json data from our static json file:

// /api/json-server.js
const fs = require('fs');
const path = require('path');

module.exports = async (req, res) => {
  const jsonPath = path.join(process.cwd(), 'src', 'app', 'db.json');
  const jsonFile = fs.readFileSync(jsonPath, 'utf8');
  const json = JSON.parse(jsonFile);
  res.setHeader('Content-Type', 'application/json');
  return res.json(json);
}

In this case db.json is our static json file located at /src/app/ and we can now fetch the json in our app using fetch('/api/json-server'). Note that in Node.js process.cwd() returns the path where node process is invoked which is usually root of your project.

https://vercel.com/guides/how-can-i-use-files-in-serverless-functions