Skip to content

Instantly share code, notes, and snippets.

@regmicmahesh
Last active November 1, 2023 05:46
Show Gist options
  • Save regmicmahesh/b7c1daf23d6fdc20bba0c61f0663f73c to your computer and use it in GitHub Desktop.
Save regmicmahesh/b7c1daf23d6fdc20bba0c61f0663f73c to your computer and use it in GitHub Desktop.
NextJS+ReactJS Environment Variables Replacer - Runtime
#!/bin/bash
set -e
# This is for NextJS, modify accordingly for react.
ENV_VARS=$(printenv | grep NEXT_ | cut -d= -f1)
for var in $ENV_VARS
do
TEMP_VAR_NAME="REPLACE_ME_${var}"
echo "Replacing ${TEMP_VAR_NAME} with ${!var}"
ESCAPED_ENV_VAR=$(echo ${!var} | sed 's/#/\\#/g')
# This path can be of nginx, if you're using static builds.
find /app/.next -type f -exec sed -i "s#$TEMP_VAR_NAME#${ESCAPED_ENV_VAR}#g" {} +
done
exec "$@"
@regmicmahesh
Copy link
Author

The dockerfile would be something like this:

ARG NEXT_APP_API_URL=REPLACE_ME_NEXT_APP_API_URL

...

ENV NEXT_APP_API_URL=$NEXT_APP_API_URL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment