How to run the server simultaneously with the client in a nodeJS application using concurently when the files are in different folders

Viewed 3130

My project is split into 2 folders client and server in the client folder the usual react-create-app package.json in sever folder package.json with trace script

scripts: {
 start: node app.js
server: nodemon app.js
}

how can I run the script through npm start to run both the backend and the frontend at the same time

client
  -app.js
  -package.json
server
  -app.js
  -package.json

I found a solution that you can start from the server folder as follows

dev: "concurently" npm run server "" npm run client "

but how to start if package.json is in different folders

1 Answers

If your client/front-end and server/back-end folders are separated in the root directory, you can run both the front-end and back-end servers together at the same time using concurrently. A few things need to be done before this is possible:

  1. CD into your root directory
  2. npm init -y (enter)
  3. touch .gitignore (enter)
  4. Add /node_modules to the .gitignore file
  5. npm install concurrently nodemon --save-dev (enter)
  6. Install all your backend server dependencies in the root directory
  7. Add the three scripts below to your root package.json:

"scripts": {
  "server": "nodemon --quiet server",
  "client": "npm start --prefix client",
  "dev": "concurrently \"npm run server\" \"npm run client\"",
},

Both the client and backend scripts are ran together by the dev script from the root directory when the npm run dev command is executed in the terminal. The dev script traverses both the client and server directories, locates the directories index.js file, and then runs each server.

Your server/back-end directory doesn't need scripts, a package.json or any node_modules as they will be available globally from the root directory.

client
  -index.js (index.js file in react is ran before app.js)
  -package.json
server
  -app.js <-- Rename to index.js
  -package.json <-- Remove package.json
  1. CD into your client/front-end directory
  2. Add this start script to your client package.json:

"scripts": {
   "start": "react-scripts start",
},

  1. Run your server/back-end and client/front-end at the same time by CD'ing into your root directory and executing npm run dev (enter)

This is what your directories will look like:

root
  client
    -index.js
    -package.json
    -/node_modules
  server
    -index.js
-package.json
-/node_modules

This directory setup is better for heroku deployment.

Related