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.


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",
3 "start:development": "npm run copy:env && vite --host",
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
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()
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])
20# Create the TS file
21tsFile = "/**\n ** This file is generated by scripts/envToConsts.py\n **/\n"
22tsFile += "export const ENV_VARIABLES = {\n"
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 += "}"
33# Write the file on disk
34f = open(os.path.join(__location__,
35 '../app/src/generated/constants_env.ts'), "w")

The input file can look like this:

1# Which environment is running? It should be "development" or "production".
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
10SERVER_PORT=80 # Internal port for the Node server
11DOCKER_SERVER_PORT_FORWARD=3500 # Port opened by the Docker to communicate to the server
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

and the produced TypeScript file looks like:

2 ** This file is generated by scripts/envToConsts.py
3 **/
4export const ENV_VARIABLES = {
5 NODE_ENV: "development",
6 CLIENT_IP: "",
7 CLIENT_PORT: 3000,
10 SERVER_IP: "",

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.


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.