Why is runtimeConfig doesn't see environment variables in Nuxt 3?

Viewed 231
  1. I do yarn build without the .env file
  2. Add the .env file to the project
  3. I do yarn start.
  4. Print the useRuntimeConfig().public.baseURL to the console and get undefined.

Why is runtime not tracking my environment variables?

.env

NUXT_PUBLIC_BASE_URL=https://example.com/api/v1

nuxt.config.js

export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      baseUrl: ''
    }
  },

plugins/app.js

export default defineNuxtPlugin(() => {
  console.log('baseURL', useRuntimeConfig().public.baseURL
})
3 Answers

From the documentation page:

However, after your server is built, you are responsible for setting environment variables when you run the server. Your .env file will not be read at this point. How you do this is different for every environment. On a Linux server, you could pass the environment variables as arguments using the terminal DATABASE_HOST=mydatabaseconnectionstring node .output/server/index.mjs. Or you could source your env file using source .env && node .output/server/index.mjs. Note that for a purely static site, it is not possible to set runtime configuration config after your project is prerendered.

So, source .env && yarn start should do it.

You might check the version of nuxt.

If it's the bridge version, runtimeConfig cannot work.

Cause I use @nuxt/bridge, not work.

and then it worked on the 3.0.0-rc.3 version. I've tried.

baseUrl: process.env.NUXT_PUBLIC_BASE_URL

try it that way. what you do is setting it explicitly to a empty string.

Related