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

Unknown's avatar

Published by Shane O'Sullivan

I am a software engineer and manager from Ireland. I spent 7 years working in Ireland from 2003 – 2010, then ten years in Silicon Valley from 2010 to 2020. In California I spent about 6.5 years at Facebook Engineering, the last three of which I was an engineering manager in the Ads organisation focusing on customer facing products for creating and managing ads. At Stripe I built the Developer Productivity organisation, with teams that were responsible for the use of the Ruby language, testing infrastructure, documentation, developer tooling (e.g. IDE integrations) and more. At Promise, I was Head of Engineering from 2018 – 2020, responsible for building the first few iterations of our products, hiring for all product roles, meeting with clients and investors, and anything else needed to get a tiny startup bootstrapped and successful. Now I’m back in Ireland, working various projects while advising the great people at Stainless (stainless.com). This blog contains my various musings on all things technical/interesting on the interweb and beyond.

Published