Skip to content
G. D. Hardy Development

Auto Restart Gatsby Development Server

gatsby1 min read

Ocassionally you'll want to make changes to your Gatsby configuration files (i.e. gatsby-config.js, gatsby-browser.js). However, those changes won't take effect until after you restart the Gatsby development server. If you don't want to do this manually every time, you can set up an npm script that will do it for you. We'll use two npm packages to handle this.

First, install nodemon and kill-port as dev dependencies.

npm install nodemon kill-port --save-dev

Nodemon is typically used to auto restart a node.js server running from a javascript file. However, we can also use it to execute terminal commands with the --exec option.

nodemon --exec "your command here"

We can also choose files to watch with the --watch option. This will re-run the --exec command whenever changes are saved.

nodemon --exec "your command here" --watch "filename 1" --watch "filename n" --watch "directory name"

Unfortunately, you have to use a separate watch flag for each file or directory you want to monitor.

Now, for the command we want to run, we will use kill-port. Kill-port will close any processes running on the port you specify.

kill-port --port 8000

Gatsby dev server runs on port 8000 by default. If you have a different set up, you'll want to change the port number. After killing the port, run the gatsby develop command to restart the server again. The final npm script will look something like this.

package.json
"scripts": {
"dev": "nodemon --exec 'kill-port --port 8000 && gatsby develop' --watch gatsby-node.js --watch package.json --watch gatsby-config.js"
}

Now when you wan't to launch the development server for the first time, you just run the npm script.

npm run dev

That's all there is to it!

© 2021 by G. D. Hardy Development. All rights reserved.
Theme by LekoArts