@heroku/env-as-html-data
v1.0.2
Published
Inject environment variables into HTML pages as data-* attributes.
Maintainers
Readme
Inject Environment Variables as HTML Data Attributes
Supports runtime config var changes and pipeline promotions on Heroku
This module will inject the current environment variables as HTML data-* global attributes into the app's HTML files. These variables can be updated everytime the app starts. Rebuild of the javascript app is not required to pick-up Heroku config var changes.
Using this Module
- install to the Javascript project:
npm install @heroku/env-as-html-data - set web process start-up to occur after this module:
npx env-as-html-data && bin/start-nginx-static
Configuration options (set as shell/environment variables):
ENV_AS_HTML_DATA_DIR(defaultpublic) the directory to search for HTML files to process.ENV_AS_HTML_DATA_FILE_EXT(default.html) the file extension to match for files to process.
Using Runtime Environment Variables
Do not set secret values into these environment variables. They will be injected into the website, where anyone on the internet can see the values. As a precaution, only environment variables prefixed with PUBLIC_ prefix will be exposed.
The variable names are case-insensitive, accessed as lowercase. Although enviroment variables are colloquially uppercased, the resulting HTML Data Attributes are set & accessed lowercased, because they are case-insensitive XML names.
For example, if this app is started:
export PUBLIC_API_URL=https://localhost:3001
export PUBLIC_RELEASE_VERSION=v42
export PORT=3000
npm startWhen the app is loaded in the web browser's javascript environment, these can be accessed using the HTML Data Attribtes:
const body = document.querySelector("body")
// These contain the env vars' values
body.dataset.public_api_url
body.dataset.public_release_version
// PORT is not set, because it isn't prefixed with PUBLIC_
body.dataset.port == nullUsing Build-time Variables
Environment variables used to configure the build, such as Webpack configuration, should be accessed using the normal Node.js process.env object.
How does the runtime variable injection work?
When this module runs during app start-up, it:
- reads all
PUBLIC_*environment variables - updates each
public/*.htmlfile, writing these env vars as<body data-*>attributes - serves the
public/directory as static files - the body data attributes are available within javascript & CSS running in the pages.
