Typescript Web Project and Environment Variables<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Typescript Web Project and Environment Variables

Posted on: January 26, 2022

Many projects require to have configurations. These configurations change depending on the environment. For example, you can have a different service DNS address and port to connect depending if you are developing locally or in a testing environment, or in production. A typical pattern is to set variables in a .env file. Many systems like NodeJS or Docker can easily read the file. However, web projects created with a web framework struggle to read the .env file. ReactJS and SolidJS are two popular frameworks that have a workaround. They inject the value of specific prefixed variables from the .env file into the code. The constraint of the prefix allows having at build time values from the file into the generated JavaScript to bypass the limitation that the browser does not have access to the .env file on the server. The issue with this workaround is that it forces the usage of variables prefixed (React Doc, SolidJS Doc). What if we want to use a .env file in a mono repository that shares a variable between projects or do not wish to use a prefixed variable between projects?

A small solution is to create your custom script that opens the .env file and generates a variable that can be referenced directly in your codebase. It means that Docker and other systems can rely on the .env file, using all the variable names you desired and at the same time having the web project, React framework or else to also use the same variable names -- no duplication or name constraint.

Package.json

The first modification is to ensure that the script is running when you start your application. You want to ensure the script generate the TypeScript (or JavaScript) file that contains all the value. With the generated file in place, you can import the variable and use the values in your web project.

Here is an example of a SolidJS project that relies on Vite.

1"scripts": {
2 "start:production": "npm run copy:env && vite --host 0.0.0.0",
3 "start:development": "npm run copy:env && vite --host 0.0.0.0",
4 "build": "npm run copy:env && vite build",
5 "serve": "npm run copy:env && vite preview",
6 "copy:env": "python ../scripts/envToConsts.py"
7 },

As you can see, all commands start with npm run copy:env

Python Script

I decided to rely on Python for the script. It is a shortcode that relies on opening a file, reading the lines, and saving the created variable into a TypeScript file.

Here is the complete script that works even if there are comments inside the .env file.

1import os
2
3# Read the environment variables from the .env file
4__location__ = os.path.realpath(os.path.join(
5 os.getcwd(), os.path.dirname(__file__)))
6f = open(os.path.join(__location__, '../.env'))
7lines = f.read().splitlines()
8
9# Extract all the key-value of each line
10keyValues = []
11for line in lines:
12 if line.find("=") >= 0 and line.strip().find("#") != 0:
13 lineSplit = line.split("=")
14 left = lineSplit[0].strip()
15 right = lineSplit[1].strip()
16 if right.find("#") > 0:
17 right = right[:right.find("#")-1]
18 keyValues.append([left, right])
19
20# Create the TS file
21tsFile = "/**\n ** This file is generated by scripts/envToConsts.py\n **/\n"
22tsFile += "export const ENV_VARIABLES = {\n"
23
24for pair in keyValues:
25 if unicode(pair[1], "utf-8").isnumeric():
26 tsFile += " " + pair[0] + ": " + pair[1] + ",\n"
27 elif pair[1] == "true" or pair[1] == "false" or pair[1] == "TRUE" or pair[1] == "FALSE":
28 tsFile += " " + pair[0] + ": " + pair[1].lower() + ",\n"
29 else:
30 tsFile += " " + pair[0] + ": \"" + pair[1].lower() + "\",\n"
31tsFile += "}"
32
33# Write the file on disk
34f = open(os.path.join(__location__,
35 '../app/src/generated/constants_env.ts'), "w")
36f.write(tsFile)
37f.close()

The input file can look like this:

1# Which environment is running? It should be "development" or "production".
2NODE_ENV=development
3
4CLIENT_IP=127.0.0.1
5CLIENT_PORT=3000 # Need to be the same as the value set in vite.config.ts and nginx.conf
6DOCKER_CLIENT_PORT_FORWARD=3501 # Port opened by the Docker to communicate to the client
7DOCKER_CLIENT_HEALTHCHECK_TEST=/bin/true
8
9SERVER_IP=127.0.0.1
10SERVER_PORT=80 # Internal port for the Node server
11DOCKER_SERVER_PORT_FORWARD=3500 # Port opened by the Docker to communicate to the server
12
13# What health check test command do you want to run? In development, having it
14# curl your web server will result in a lot of log spam, so setting it to
15# /bin/true is an easy way to make the health check do basically nothing.
16#export DOCKER_SERVER_HEALTHCHECK_TEST=curl localhost:8700/health
17DOCKER_SERVER_HEALTHCHECK_TEST=/bin/true

and the produced TypeScript file looks like:

1/**
2 ** This file is generated by scripts/envToConsts.py
3 **/
4export const ENV_VARIABLES = {
5 NODE_ENV: "development",
6 CLIENT_IP: "127.0.0.1",
7 CLIENT_PORT: 3000,
8 DOCKER_CLIENT_PORT_FORWARD: 3501,
9 DOCKER_CLIENT_HEALTHCHECK_TEST: "/bin/true",
10 SERVER_IP: "127.0.0.1",
11 SERVER_PORT: 80,
12 DOCKER_SERVER_PORT_FORWARD: 3500,
13 DOCKER_SERVER_HEALTHCHECK_TEST: "/bin/true",
14}

The script might require some modification for your need. For example, the source path and the output path. In my case, I had to work around Docker and adjust the paths for the Docker's folders structure.

Conclusion

I found the scripting solution to be quite convenient. It allows a central configuration file with clean names. Furthermore, it provides for potential customization like marking configuration to be opt-out for the web project if needed (e.g., using a particular comment to opt-out). In the end, this simple script removed the need to duplicate variables. For example, Docker uses the IP and port for the server in this file and the web project to know where to connect. Without this solution, we would need to have duplicated data (prefixed and non-prefixed) or to have the Docker system uses the prefixed variables.