Skip to content

Instantly share code, notes, and snippets.

@itsjavi
Last active November 25, 2023 03:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itsjavi/c4b36379cca977e3c75dab74a47cafea to your computer and use it in GitHub Desktop.
Save itsjavi/c4b36379cca977e3c75dab74a47cafea to your computer and use it in GitHub Desktop.
Open nextjs dev server URL after start
#!/bin/bash
set -e
# Load .env file
if [ -f .env ]; then
export $(cat .env | sed 's/#.*//g' | xargs)
else
echo "No .env file found"
exit 1
fi
# Check if env file is parsed correctly, by testing a required env var
if [ -z "$SOME_REQUIRED_VARIABLE" ]; then
echo ".env file vars could not be read correctly"
exit 1
fi
DEV_PORT=${DEV_PORT:-"${PORT:-3000}"}
startNextServer() {
PORT=$DEV_PORT node_modules/.bin/next dev
}
# execute startNextServer function in subshell
startNextServer &
# get pid of last executed command (startNextServer)
SERVER_PID=$!
# trap ctrl-c and call ctrl_c() function to kill all child processes if you press ctrl-c
trap ctrl_c INT
function ctrl_c() {
echo "** Trapped CTRL-C"
kill -9 $SERVER_PID
exit 1
}
# wait until server is up and then open it in the browser
echo "Waiting for server to start on port $DEV_PORT"
until $(curl --output /dev/null --silent --head --fail "http://localhost:$DEV_PORT"); do
printf '.'
sleep 1
done
echo ""
open "http://localhost:$DEV_PORT"
# call this script from your "dev" script in your package.json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment