How to add two commands in the start inside package.json?

I have my package.json start like this

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

How to add also “json-server db.json” to start ?

Here are four different ways to do that.

Still I dont understand how to use it. I tried to write it like that

"scripts": {
    "start": "json-server db.json && react-scripts start",

but the main application at localhost:3000 does not load. How to I should write this ?

That command will wait for the json-server db.json command to finish before running the react-scripts start command, which is not what you want.

What happens when you use only one ampersand?

"scripts": {
    "start": "json-server db.json & react-scripts start",

If that doesn’t work, have a look at the Concurrently package, which allows you to run multiple commands concurrently.

1 Like

Yes I would definitely go with concurrently, most importantly for better process handling. If you just run a command in the background using a single &, and the foreground process (i.e. the last one in the line) dies, the background process will keep running which raises several problems:

  • Most apparently, the background process will keep occupying resources
  • It will still write to stdout and clutter your shell prompt (or wherever you redirected the output to)
  • If you try to run that script again, the background processes will either
    • Pile up and likely interfere with each other
    • Cause the script to fail entirely, e.g. when attempting to open a port that is still in use by an older process

To fix this, you’d have to find and kill the background processes manually then. Conversely, if a background process dies you might not even notice right away because the exit message got buried somewhere in the logs.

With concurrently OTOH you can clean up background processes automatically:

{
  "scripts": {
    "start": "concurrently --kill-others 'json-server db.json' 'react-scripts start'"
  },
  "devDependencies": {
    "concurrently": "^4.1.1"
  }
}

Also you’ll get a more organised console output so you can see where a certain message is actually coming from.

2 Likes

many thanks

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.