Search code examples
reactjsverceljson-server

Launch mock server on vercel


I have a React project and installed mock server with json-server node module.
(For your note: Here is the json-server documentation for better understanding. [link]1)
I can start mock server with npm script [npm run mock].
After run the script, mock server start working with this link: localhost:3000.
This react project is working well on local environment.
Now I am going to deploy react project on vercel.
But I have no idea for start mock server on vercel.
How can I start mock server on vercel?

Here is the scripts of package.json file for the application.

{
...
"scripts": {
    "start": "PORT=3001 react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "mock": "json-server --watch src/mock/db.json",
    "preinstall": "npm install --package-lock-only --ignore-scripts && npx npm-force-resolutions"
  }
...
}

Please ask me more information what you want to check.


Solution

  • I had a similar issue and this article save my life.

    https://shadowsmith.com/how-to-deploy-an-express-api-to-vercel

    Instead of deploying together with my React project, I deploy JSON Server as a separate mock server.

    First of all, you need to create a server.js to run JSON Server as a module. Reference: https://github.com/typicode/json-server#module

    At the end of the file, export server in order for Vercel to turn Express into a serverless function

    // Export the Express API
    module.exports = server;
    

    Last but not least, create a vercel.json in order to deploy to Vercel.

    Here are my scripts for your reference purpose: https://github.com/kitloong/json-server-vercel