nuxt: Dynamic runtime public environment variables using publicRuntimeConfig are undefined

The issue:

I am trying to achieve this requirement:

  • The application is built using some environment variables that are defined on Build-time (like BasePath)
  • The application can access some envs that are Runtime, like API_URL

I am building my application for production nuxt build --production=true and running it on a docker container where I pass some environment variables e.g API_URL, ...etc

My nuxt.config.js has the definition of those env variables:

  publicRuntimeConfig: {
    TENANT: process.env.TENANT,
    API_URL: process.env.API_URL,
  },

I run my docker with the built-image:

   docker run -p 3000:3000 -e TENANT=GB -e API_URL=.... my_image_name

And I access those variables using the $config property in Vue:

mounted () {
   console.log(this.$config.TENANT) //undefined
   console.log(process.env.TENANT) //undefined
}

What is Expected?

The expected behaviour is whenever I run my_image_name with different by passing different env variables, I can see those values.

What is actually happening?

All the publicRuntimeConfig are undefined on run time!

Note:

Running it locally works fine, because the env variables are read from .env file, which doesn’t exist on production, but rather the env variables…

Versions

  • nuxt: v2.15.3
  • node: v12.14.0

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 21 (7 by maintainers)

Most upvoted comments

Same issue.

My problem was that i changed everything in my nuxt app to use es module instead of commonjs require.

So i used a workaround :

Instead of exporting to default the nuxt config i exported a function that uses process.env as parameter : //nuxt.config.js

export default function getNuxtConfig (envVariables) {
  return {
 //Nuxt config
    publicRuntimeConfig: {
      HOST: envVariables.HOST,
      PROTOCOL: envVariables.PROTOCOL,
      PORT: envVariables.PORT,
    etc...
    },
 }
}

And then in server/index.js :

import getNuxtConfig from '../nuxt.config.js' 
// Import and Set Nuxt.js options
const config = getNuxtConfig(process.env)
 const nuxt = new Nuxt(config)

Hope it helps

@StefanoTesla Looks like a typo? baseUrl vs baseURL

I’m having this very same issue reported at the beginning. I have a k8s pod which mounts a .env file, but the system is not able to read it. I was setting the API_URL, but I was not able to make it work. Locally works well. I’m gonna set the configuration on build time.

@bangrobe You can’t access this.$config within your nuxt.config. It’s for use within your app itself. In the case you have, @nuxtjs/apollo would also have to have support for publicRuntimeConfig (note: I’m not sure it does), and you would need to declare it like so:

apollo: {
  clientConfigs: {
    default: {
      httpEndpoint: process.env.GRAPHQL_HTTP
    }
  }
}