Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I start my node server and react app at the same time?

I created an API using express and I want to use it in my front-end server, the issue is that in order for my api to work I have to constantly run it on a server. However I can't do that simultaneously running my react application. So my question is how can I start my react server and api at the same time?

P.S. I tried out concurrently but I'm confused on how to get it working, heres some sample code from my package.json

{
    "name": "app",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
    "@material-ui/core": "^4.1.1",
    "@material-ui/icons": "^4.2.0",
    "axios": "^0.19.0",
    "concurrently": "^4.1.0",
    "express": "^4.17.1",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-scripts": "3.0.1"
  },
     "scripts": {
     "start": "node src/connection",
     "build": "react-scripts build",
     "test": "react-scripts test",
     "eject": "react-scripts eject",
     "react": "react-scripts start",
     "dev": "concurrently \"npm start\" \"npm react\""
     },
     "proxy": "http://localhost:3000",
    "eslintConfig": {
    "extends": "react-app"
    },
    "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": []
 }
}
like image 749
martha1352 Avatar asked Jun 23 '19 12:06

martha1352


2 Answers

In 5 steps:

  1. Install npm i --s concurrently package
  2. Add below script inside Node/server/backend's package.json
    "client": "npm start --prefix client",
    "clientinstall": "npm install --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client" 
  1. Make sure you provided the correct path for client and server
  2. Run 'npm run dev'
  3. Smile
like image 165
Aamer Avatar answered Oct 13 '22 00:10

Aamer


Install package npm-run-all, which helps you to execute multiple scripts. You can refer the below link:

https://www.npmjs.com/package/npm-run-all

After installing this package, In your package.json, add the script like this:

"scripts": {    
  "start-js": "react-scripts start",
  "backend-start": "NODE_ENV=production node node_api/server.js",
  "start": "concurrently \"npm-run-all -p backend-start start-js\"",
  "build": "npm-run-all build-css && react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject"
}

Here, when you run the command "npm start", it first run the "backend-start" script which starts your backend server and then it starts react.

Just change the path in "backend-start" script. replace "node_api/server.js" with your path node startup file

like image 40
Dhvani Avatar answered Oct 12 '22 23:10

Dhvani