'Change Environmet Variables at runtime (React, vite) with docker and nginx
at work I need to make it possible to change the environmet variables at runtime, from an Azure web service, through docker and nginx. I tried this, this and some similar solutions, but I couln't get any of them to work.
I also couldn't find any solution online or any article/thread/post that explained if this is even possible, I only always find the text that vite statically replaces the env variables at build time.
During our CI/CD pipeline vite gets the env variables but our Azure admins want to be able to configure them from Azure, just for the case of it.
Does anyone know if this is possible and or maybe has a solution or some help, please ? :)
Solution 1:[1]
My Solution is that it schould work with the links from my question. I use this approach and it works, the only thing that needs to be thought of is to use a different variable name/prefix (e.g. "APP_...") so vite doesn't change them at build time. I created a config file wich resolves the variable, for example if the app is in production than it uses the new Variable "APP_.."(which comes injected from nginx/ docker) or use "VITE_..."-variable if "APP_.." is undefined.
Solution 2:[2]
It is not possible to dynamically inject Vite env variables. But what is possible, is to change the window object variables (assign them on runtime).
WARNNING!!! DO NOT EXPOSE ANY SENSITIVE VARIABLES THROUGH THE WINDOW OBJECT. YOUR FRONT-END APPLICATION SOURCE IS VISIBLE TO ANYONE USING IT
Steps:
Create your desired env files and place them in
<rootDir>/public. Let's call themenv.jsandenv-prod.js.Inside your
env.jsandenv-prod.jsYou want to assign your desired variables usingvarkeyword. Also, you will have to reference these values in your source likewindow.MY_VARto be able to use them.Create a script tag inside your
<rootDir>/index.htmllike this:<script type="text/javascript" src="./env.js"></script>.
IMPORTANT!!!type="text/javascript"is important, because if You specify module,Vitewill include yourenv.jssource inside your minifiedindex.jsfile.Vite config (optional):
plugins: [react(), tsConfigPath()],
build: {
emptyOutDir: true, // deletes the dist folder before building
},
});
How to serve the env files on runtime. Create anodeserver which will serve your frontend application. But before serving theenv.jsfile, depending on ourprocess.env.ENVIRONMENTyou can now choose which env.js to serve. Let's say my node server file is stored at<rootDir>/server/server.js:
const express = require("express");
const path = require("path");
const app = express();
const env = process.env.ENVIRONMENT || "";
console.log("ENVIRONMENT:", env);
const envFile = path.resolve("public", env ? `env-${env}.js` : "env.js");
const indexFile = path.resolve("dist", "index.html");
app.use((req, res, next) => {
const url = req.originalUrl;
if (url.includes("env.js")) {
console.log("sending", envFile);
// instead of env.js we send our desired env file
res.sendFile(envFile);
return;
}
next();
});
app.use(express.static(path.resolve("dist")));
app.get("*", (req, res) => {
res.sendFile(indexFile);
});
app.listen(8000);
Solution 3:[3]
I came up with a solution and published it as packages to the npm registry.
With this solution, you don't need to change any code:
// src/index.js
console.log(`API base URL is: ${import.meta.env.API_BASE_URL}.`);
It separate the build step out into two build step:
During production it will be statically replaced import.meta.env with a placeholder:
// dist/index.js
console.log(
`API base URL is: ${"__import_meta_env_placeholder__".API_BASE_URL}.`
);
You can then run the package's CLI anywhere to replace the placeholders with your environment variables:
// dist/index.js
console.log(
`API base URL is: ${{ API_BASE_URL: "https://httpbin.org" }.API_BASE_URL}.`
);
// > API base URL is: https://httpbin.org.
Here is the documentation site: https://iendeavor.github.io/import-meta-env/.
Feel free to provide any feedback.
Solution 4:[4]
You can set the variables in YAML format and update them accordingly as per your requirement.
Below is the sample YAML format which we use as a template:
#Set variables once
variables:
configuration: debug
platform: x64
steps:
#Use them once
- task: MSBuild@1
inputs:
solution: solution1.sln
configuration: $(configuration) # Use the variable
platform: $(platform)
#Use them again
- task: MSBuild@1
inputs:
solution: solution2.sln
configuration: $(configuration) # Use the variable
platform: $(platform)
Check this SO for more insights to understand environment variables hosted in azure web app
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Max |
| Solution 2 | |
| Solution 3 | Ernest |
| Solution 4 | SaiKarri-MT |

