Static GitHub Issues

[2689] Enhancement: allow Nuxt to use runtime environment variables

prev: Proposal: Allow fallback to SPA in universal mode's generate
next: How to integrate HotJar?

We currently use this plugin to hydrate/dehydrate runtime environment variables. This is handy for 12-factor apps where you might want to reconfigure a running app without rebuilding.

// This plugin copies runtime environment variables from the server process
// to the client via the Nuxt state serialized on window.__NUXT__.
// Normally, environment variables in Nuxt are captured at build time.
//
// To prevent leakage of sensitive information from the server to the client,
// this plugin will ONLY copy variables named in the env section of nuxt.config.js.
//
// To use runtime environment variables, just use the Nuxt context env or
// explicitly look at window.__NUXT__.env.
export default ({ beforeNuxtRender, nuxtState, env }) => {
  if (process.server) {
    beforeNuxtRender(({ nuxtState }) => {
      nuxtState.env = nuxtState.env || {}
      Object.keys(env).forEach(key => {
        if (process.env[key]) {
          nuxtState.env[key] = process.env[key]
        }
      })
    })
  } else {
    Object.keys(nuxtState.env).forEach(key => {
      env[key] = nuxtState.env[key]
    })
  }
}
<!--cmty--><!--cmty_prevent_hook--><div align="right"><sub><em>This question is available on <a href="https://nuxtjs.cmty.io">Nuxt.js</a> community (<a href="https://nuxtjs.cmty.io/nuxt/nuxt.js/issues/c2337">#c2337</a>)</em></sub></div>