1.0.1-rc1 • Published 3 years ago

@neat-tech/bundle-web v1.0.1-rc1

Weekly downloads
-
License
MIT
Repository
-
Last release
3 years ago

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