How to clean up after your NextJS dev server

Sometimes you need to modify files when building a web application that must be reverted before committing. In my case I’m building a Chrome extension that reads from a NextJS based web service, and when I’m working on the browser extension it reads from http://localhost:3005, so I have to modify its manifest.json file to allow this. Of course, I cannot leave that change in the file as it would be a privacy issue and Google would rightly reject it.

Rather than leaving this up to me remembering to manually revert the manifest.json change, here’s how you can do it in bash. The idea is that, when starting up the NextJS process, you run your setup script, and then you listen to the termination signal for the server and execute the cleanup script

Modify package.json

We’re going to use the standard npm run dev command to do all the setup and cleanup work, so make a new script command in the package.json file that runs the standard `next dev` command, e.g.

"scripts": {
  "dev": "./scripts/dev.sh",
  "nextdev": "next dev"
}

Create a dev.sh script

Now create the dev.sh script mentioned above, assuming it is the scripts folder and your setup and cleanup scripts are in the same folder and named run_setup_script.sh and run_cleanup_script.sh respectively

# Get the directory of the script
script_dir="$(dirname "$0")"

"$script_dir/run_setup_script.sh"

on_termination() {
    # Add your cleanup script or command here
    echo "cleaning up dev environment"
    "$script_dir/run_cleanup_script.sh"  
}

# Set up the trap to call on_termination() 
# when a signal is received that shuts it down

# SIGINT is sent when you kill it with Ctrl+C
trap on_termination SIGINT
trap on_termination SIGTERM

# EXIT is sent when the node process calls process.exit()
trap on_termination EXIT

# Now run your NextJS server
npm run nextdev

Leave a comment