@neat-tech/bundle-web
TypeScript icon, indicating that this package has built-in type declarations

1.0.1-rc1 • Public • Published

Runtime env variables for frontend

From the infrastructure point of view it's better to set some env variables during the runtime, and to set others during the build time to enable bundle optimizations. Examples:

  • NODE_ENV should always be set during build time, because it enables dead code elimination
  • Feature flags can be enabled during build time as well, because is also enables dead code elimination
  • Things like backend url, sentry key etc should be set during runtime, because these envs don't allow for extra optimizations. Setting them on container startup allows for more flexible infra management

This is how we enable runtime variables for static frontend:

  1. We pass current env to HtmlWebpackPlugin as templateParameters:
const { parsed: env } = dotenv.config();
addPlugin(
  config,
  new HtmlWebpackPlugin({
    filename,
    templateParameters: { env },
    template,
    favicon,
    chunks,
  })
);
  1. Later in the index.ejs, we create a script that sets env variables as window properties:
<script>
  <%= Object.keys(env).map(key => `window.${key} = '${env[key]}';`).join('') %>
</script>

(turns into)

<script>
  window.BACKEND_URL = 'https://google.com';
</script>
  1. When building the app, pass $VARIABL_NAME instead of actual variable value.
addPlugin(
  config,
  new HtmlWebpackPlugin({
    filename,
    templateParameters: { BACKEND_URL: '$BACKEND_URL' },
    template,
    favicon,
    chunks,
  })
);
  1. On container startup, run envsubst on html files

Readme

Keywords

none

Package Sidebar

Install

npm i @neat-tech/bundle-web

Weekly Downloads

1

Version

1.0.1-rc1

License

MIT

Unpacked Size

339 kB

Total Files

52

Last publish

Collaborators

  • ruslana_x
  • vmajsuk