Home

Issue: 2689

Enhancement: allow Nuxt to use runtime environment variables

[issue link]

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]
    })
  }
}
This question is available on Nuxt.js community (#c2337)