Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run client and server code at the same time

I have client code which is in the client folder. I have done yarn build to create the production build.

I also have a server which holds the API end points how do I run them concurrently using the production of the client code.

Server Package.json:

  "scripts": {
    "client-install": "npm install --prefix client",
    "start": "node server.js",
    "server": "nodemon server.js",
    "client": "npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\"",
    "prod": "NODE_ENV=production concurrently \"npm run server\" \"npm run client\""
  },

server.js:

// Routes
app.use("/api/users", users);

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log(`Server up and running on port ${PORT} !`));

client package.json:

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:5000",
like image 256
Ayush Parikh Avatar asked Mar 06 '26 12:03

Ayush Parikh


2 Answers

When you do yarn build for client prod, you generate some index.html with js, let's say in client/build folder (you can adjust path for your needs). Therefore you don't need npm run client, you just have to serve html files. It's possible to add handler in server.js after all routes defined, like this

if (['production'].includes(process.env.NODE_ENV)) {
  app.use(express.static('client/build'));

  const path = require('path');
  app.get('*', (req, res) => {
    res.sendFile(path.resolve('client', 'build', 'index.html'));
  });
}

One last step is to update script in package.json file the following way

"prod": "NODE_ENV=production node server.js"

That's it

like image 63
Rashad Ibrahimov Avatar answered Mar 08 '26 04:03

Rashad Ibrahimov


you can add default fallback for your front end like

   if(process.env.NODE_ENV === 'production'){
        const path  =  require('path');
        app.use(express.static('client/build'));
        app.get('/*',(req,res)=>{ 
            res.sendfile(path.resolve(__dirname,'../client','build','index.html')); // change as per your index.html 
        })
    }
like image 45
Prakash Karena Avatar answered Mar 08 '26 05:03

Prakash Karena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!