Single Page App Runtime Environment Variables
Tags: javascript, devops, singlepageapp
Published: 2021-12-17 16:12:58

## Introduction 

Any single page application (SPA) runs as static page inside a browser runtime environment, and inside a browser, there is nothing like a runtime variables that could be used by SPA. However, there are few hacks through which we can implement dynamic environment variable in a SPA.

**But the question is why we need a runtime variable for static page?** Well, in my experience there are few cases which compel us to look for runtime or dynamic variable for a SPA. For example, different API endpoints for local, pre-prod, and production, different API keys for pre-prod and prod, and likewise.

## Getting Started 

We need a few configurations to get started for local development:
1. An environment file
2. A Bash script
3. A NPM script 
4. Include script tag in public/index.html
5. Script where runtime variable is needed

### 1. An environment file
Create an env.preprod file, create this file at _/public/env/_ location e.g. _/public/env/env.preprod_
This is the file where the runtime environment variable will be stored, there could more than one variable in the file. **Why under public directory? as it will be bundled during the build process into tarball**

```JS
//Filename: env.preprod
APP_RUNTIME_PREPROD_KEY=xyz
```

### 2. A Bash script
Bash script that will be executed during `npm start` for local, that will create the env-config.js with content from env.preprod file and same for pre-prod during deployment. For prod, we'll have the default env-config.js file.

Filename: env.sh
```BASH
#!/bin/bash

# look for runtime env file
if [ ! -z "${2}" ]; then
  envFile="${1}"/env."${2}"
fi

#If can't find it then exit
if [[ ! -f "$envFile" ]]; then
echo "Env file doesn't exist!"
exit 1;
fi

  
# create runtime env JS file
if [[ ! -z "${1}" ]]; then
  envJs="${1}/env-config.js"
fi

#Recreate config file
rm -rf ${envJs}
touch ${envJs}

# Add assignment 
echo "window._env_ = {" >> ${envJs}

# Read each line in .env file
# Each line represents key=value pairs
while read -r line || [[ -n "$line" ]];
do
  # Split env variables by character `=`
  if printf '%s\n' "$line" | grep -q -e '='; then
    varname=$(printf '%s\n' "$line" | sed -e 's/=.*//')
    varvalue=$(printf '%s\n' "$line" | sed -e 's/^[^=]*=//')
  fi

  # Read value of current variable if exists as Environment variable
  value=$(printf '%s\n' "${!varname}")
  # Otherwise use value from .env file
  [[ -z $value ]] && value=${varvalue}
  
  # Append configuration property to JS file
  echo "  $varname: \"$value\"," >> ${envJs}
done < ${envFile}

echo "};" >> "${envJs}"

echo "generated ${envJs} with content"
cat ${envJs}
```

### 3. A NPM script
This will wire up as the `prestart npm script` and execute the bash script.

```JS
//Change in package.json file
"prestart" : "chmod +x ./public/env/env.sh && ./public/env/env.sh ./public/env preprod"
```

### 4. Include script tag in the public/index.html
The env-config.js created so far needs to be loaded in the index.html, else we can't use it. When env-config.js is created, the browser's window object is assigned a runtime variable.

```HTML
<!--Change in index.html-->
<head>
  <script src="%PUBLIC_URL%/env/env-config.js?d=20210529"></script>
</head>
```

### 5. Script where runtime variable is actually used
And now for all the hard work done so far, it's time to ripe/use the runtime variable. Since the variable is assigned as a window object, now we can use the way we want. It can also be used in the vanilla JS file file. Checkout [Sample Code](https://github.com/an1meshk/tutorials/tree/main/spa-runtime-variable)

```JS
//Filename: some-important.js
const RUNTIME_ENV_KEY = window?._env_?.APP_RUNTIME_PROD_KEY ? window._env_.APP_RUNTIME_PROD_KEY : window?._env_?.APP_RUNTIME_PREPROD_KEY;

```
Also, include some-important.js in the index.html head tag:

```HTML
<!--Change in index.html-->
<head>
  <script src="%PUBLIC_URL%/some-important.js?d=20210529"></script>
</head>
```

## For Preprod
1. Execute script during deployment
2. location.conf (when using NGINX)

### 1. Execute script during deployment
Include a script to execute the `env.sh` in the deployment process. For docker image details, checkout the reference section at the end.

Filename: preprod-deployment.sh
```BASH
bash ./public/env/env.sh ./public/env preprod
```

### 2. location.conf (when using NGINX)
When the Nginx server is used as a web server, allow access to env-config.js file.

Filename: location.conf
```
location ~ /env/(.+\.(?:js))$ {
  expires -1;
  add_header Cache-Control "public"
}
```

## For Production

### 1. Create default env-config.js
Creating a default reduces the effort to configure any steps needed during the production deployment. But if we want, we can create another env file like env.prod and run the same during production deployment. However, this is totally up to you!

Filename: env-config.js
```JS
window._env_ = {
  APP_RUNTIME_PROD_KEY=runtime-env-value
};
```

## Sample Code
The code snippet presented in this blog is available in Github, [Sample Code](https://github.com/an1meshk/tutorials/tree/main/spa-runtime-variable).

_If you have reached here, then I did a satisfactory effort to keep you reading. Please be kind to leave any comments or ask for any corrections. **Happy Coding!**_

## References:

- https://www.freecodecamp.org/news/how-to-implement-runtime-environment-variables-with-create-react-app-docker-and-nginx-7f9d42a91d70/

## My other blogs:

- [Avoid Spring RestTemplate Default Implementation to Prevent Performance Impact](https://dev.to/akdevcraft/never-use-spring-resttemplate-default-implementation-2ghj)
- [Private Cloud Vs Public Cloud Computing](https://dev.to/akdevcraft/private-vs-public-cloud-computing-5b74)
- [Containers Vs Virtual Machines, which is better and why?](https://dev.to/akdevcraft/containers-vs-virtual-machines-45m1)
- [Why we need multiple code analysis tools?](https://dev.to/akdevcraft/why-we-need-multiple-code-analysis-tools-3d9o)