Sébastien Belzile
Posted on July 14, 2021
Dotenv is wonderful. It allows you to use environment variables in your code, hence separating the code from its running environment.
The problem I have with it is that it is common to see people using it in the front-end of their web application (served static files, non-SSR applications).
What is wrong with this?
Your environment becomes hard-coded in your files at build time. If you proceed this way, you need to build your application every time you wish to deploy it.
Alternative
Load your configuration at runtime, either from a backend or from a configuration file (with an hash in the name). This way, your CI and your CD become 2 independent components. You build only once as opposed to once per deployment. Furthermore, the same artifact is being deployed everywhere, saving you a couple build minutes, and increasing your confidence in what you are deploying.
Implementation example (configuration file)
In your index.html
file, add a setting file that contains your environment variables:
<script src="./settings/settings.js"></script>
// must be placed before your js files
File content example:
var environment = {
"backendBaseUrl": "http://localhost:8000",
}
Using Typescript? Type it:
type Environment = {
backendBaseUrl: string
}
declare global {
const environment: Environment
}
Then use it:
const url = `${environment.backendBaseUrl}/potato`
Your deployment pipeline simply needs to ensure this file is being generated/deployed, which is way faster than building your whole codebase.
Posted on July 14, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.