node.jsreactjsvercelprerender

How can I run my build through node on Vercel without using '/api' in my URL?


I am trying to deploy my react application on vercel .But i want to run my build using node server. Because I have to use prerender.io in my node app. Such that preview can come with dynamic value when someone share the link.

For that i am adding server.js in my root folder and this is the code :

const express = require('express');
const prerender = require('prerender-node');

const app = express();

// Serve the static React build files
app.use(express.static('build'));

// Use prerender.io for prerendering
app.use(prerender.set('prerenderToken', 'MY TOKEN'));

// Serve the React app for all routes
app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, 'build', 'index.html'));
});

// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

and this is my vercel.json :

{
    "rewrites": [
      { "source": "/(.*)", "destination": "/server.js" }
    ]
  }
  

But my build is not getting read through node , vercel is just serving build directly i think.

But when i added api folder in my app and added same server.js code there , afterwards it started running through node app. And i dont want to use '/api' in my url for it to work. So what can i walk around such that my build runs through node app .

These are scripts in my package.json

 "scripts": {
    "start": "node server.js",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },```




Solution

  • Your vercel config file is malformed

    Rewrites change the path from source with the destination, but keep in mind that the vercel internal routes are different.

    In this example, your api is under "/api/server" then you need to point to that path

    in your vercel.json need to change to this

    {
      "version": 2,
      "rewrites": [{ "source": "/(.*)", "destination": "/api/server" }]
    }