Injecting Environment Variables in HTML Using EJS
Question: I have a vite app with an index.html it has ejs tags i have another ejs template as well i would like to inject environment variables into html dev from .env prod from config files
Explanation:
To inject environment variables into your HTML using EJS in a Vite app, you can use the following approach:
-
Development:
- Vite exposes environment variables that start with
VITE_
from your.env
files. In your EJS template, you can reference these variables by passing them from your Vite config or build script. - Example: In your
vite.config.js
, you can useimport.meta.env
to access variables and pass them to your EJS template during build.
- Vite exposes environment variables that start with
-
Production:
- For production, you can generate a config file (like
config.prod.json
) with the required values and inject them into your EJS template during the build process. - You can use a build script or a plugin to replace EJS tags with the correct values for each environment.
- For production, you can generate a config file (like
Sample workflow:
- Create
.env
files for each environment (e.g.,.env.development
,.env.production
). - Use a build tool or script to render your EJS templates, passing the appropriate environment variables.
- For multiple environments or regions, generate the config files or set environment variables before running the build.
Question: Now i need to generate multiple index.html per region and stage in prod
Explanation:
To generate multiple index.html
files for different regions and stages in production:
- Prepare a separate config (JSON or env) for each region and stage (e.g.,
config.us.prod.json
,config.eu.staging.json
). - Write a build script (Node.js or similar) that loops through each region/stage, renders the EJS template with the corresponding config, and outputs the result to the appropriate directory (e.g.,
dist/us/index.html
,dist/eu/index.html
). - This allows you to serve region- and stage-specific HTML files, each with their own injected variables.
Example Node.js script:
const ejs = require("ejs");
const fs = require("fs");
const configs = [
{ region: "us", stage: "prod", config: require("./config.us.prod.json") },
{
region: "eu",
stage: "staging",
config: require("./config.eu.staging.json"),
},
// ...add more configs
];
configs.forEach(({ region, stage, config }) => {
ejs.renderFile("index.ejs", config, (err, str) => {
if (err) throw err;
fs.writeFileSync(`dist/${region}/${stage}/index.html`, str);
});
});
This approach gives you a flexible way to generate multiple HTML files tailored to each deployment scenario.