Skip to content
Go back

Injecting Environment Variables in HTML Using EJS

Edit page

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:

Sample workflow:

  1. Create .env files for each environment (e.g., .env.development, .env.production).
  2. Use a build tool or script to render your EJS templates, passing the appropriate environment variables.
  3. 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:

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.


Edit page
Share this post on:

Previous Post
Hosting a Static Website on GitHub Pages
Next Post
Running Vite Preview and Using Bun for Background Processes