How to use .env variables in Nuxt 2 or 3?
Asked Answered
T

8

35

I have .env file in the project root, and in my nuxt config I am using variables to configure ReCaptcha like this:

import dotenv from 'dotenv'
dotenv.config()

export default {
    modules: [
        ['@nuxtjs/recaptcha', {
          siteKey: process.env.RECAPTCHA_SITE_KEY,
          version: 3,
          size: 'compact'
        }],
    ]
}

and in .env like this:

RECAPTCHA_SITE_KEY=6L....

but the application always failed with console log error:

ReCaptcha error: No key provided

When I hard-code ReCaptcha key directly like that: siteKey: 6L.... app start working, so I guess the problem is with reading .env props in nuxt.config

do you have any idea how to fix it?

EDIT: I tried update my nuxt.config by @kissu recommendation and by example which I found here: https://www.npmjs.com/package/@nuxtjs/recaptcha

so there is new nuxt.config which also not working:

export default {
    modules: [
       '@nuxtjs/recaptcha',
    ],
    publicRuntimeConfig: {
       recaptcha: {
         siteKey: process.env.RECAPTCHA_SITE_KEY,
         version: 3,
         size: 'compact'
       }
  }
}
Till answered 26/5, 2021 at 10:29 Comment(9)
what's the nuxt version?Preemie
@BoussadjraBrahim 2.14Till
in this version you don't need dotenv modulePreemie
@BoussadjraBrahim I tried remove it but stilll didn't workTill
Have you tried using this instead? process.env.NUXT_ENV_RECAPTCHA_SITE_KEY nuxtjs.org/docs/2.x/configuration-glossary/…Sextuple
So, did you solved your issue?Costar
@Costar unfortunately no :/Till
In Nuxt 3, it works for me without having to add/change anything in nuxt.config.ts. However, it only works with the file .env and not .env.development or .env.local.Dworman
@Dworman yeah, there are even more defaults with Nuxt3.Costar
C
81

This video is a good explanation in a video format, with some up to date info that I didn't knew back in the time. Will soon update my answer accordingly to fix some mistakes.


If your Nuxt version is 2.13 or above, you don't need to use @nuxtjs/dotenv or anything alike because it is already backed into the framework.

To use some variables, you need to have an .env file at the root of your project. This one should be ignored by git. You can then input some keys there like

PUBLIC_VARIABLE="https://my-cool-website.com"
PRIVATE_TOKEN="1234qwer"

In your nuxt.config.js, you have to input those into 2 objects, depending of your use case, either publicRuntimeConfig or privateRuntimeConfig:

export default {
  publicRuntimeConfig: {
    myPublicVariable: process.env.PUBLIC_VARIABLE,
  },
  privateRuntimeConfig: {
    myPrivateToken: process.env.PRIVATE_TOKEN
  }
}

Differences: publicRuntimeConfig can basically be used anywhere, while privateRuntimeConfig can only be used during SSR (a key can only stay private if not shipped to the browser).

A popular use case for the privateRuntimeConfig is to use it for nuxtServerInit or during the build process (either yarn build or yarn generate) to populate the app with headless CMS' API calls.

More info can be found on this blog post: https://nuxtjs.org/blog/moving-from-nuxtjs-dotenv-to-runtime-config/


  • Then, you will be able to access it into any .vue file directly with
this.$config.myPublicVariable
  • You access it into Nuxt's /plugins too, with this syntax
export default ({ $axios, $config: { myPublicVariable } }) => {
  $axios.defaults.baseURL = myPublicVariable
}
  • If you need this variable for a Nuxt module or in any key in your nuxt.config.js file, write it directly with
process.env.PRIVATE_TOKEN

Sometimes, the syntax may differ a bit, in this case refer to your Nuxt module documentation.

// for @nuxtjs/gtm
publicRuntimeConfig: {
  gtm: {
    id: process.env.GOOGLE_TAG_MANAGER_ID
  }
},

PS: if you do use target: server (default value), you can yarn build and yarn start to deploy your app to production. Then, change any environment variables that you'd like and yarn start again. There will be no need for a rebuild. Hence the name RuntimeConfig!

Nuxt3 update

As mentioned in the docs, you can use the following for Nuxt3

nuxt.config.js

import { defineNuxtConfig } from 'nuxt3'

export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      secret: process.env.SECRET,
    }
  }
}

In any component

<script setup lang="ts">
  const config = useRuntimeConfig()
  config.secret
</script>

In a composable like /composables/test.js like this

export default () => {
  const config = useRuntimeConfig()
  console.log(config.secret)
}

Here is the official doc for that part.

Costar answered 26/5, 2021 at 13:5 Comment(19)
Thank you for answer, I tried edit by your recommendation and I still have same error. I also update my question.Till
Do you have a populated .env in your project?Costar
Do you have a Github repo? Do you have a valid key in .env, no typo? How do you try this?Costar
Yes I checked site key and secret many times, there are correct, because when I write it in nuxt.config directly instead of using env variable everything works fine, so problem must be with reading env in nuxt configTill
Show us some screenshots I guess.Costar
what screenshot you mean?Till
Your setup is fine from what you tell. So, I don't know how but try to show us that this is 100% accurate because I'm sure that it works with the setup that I gave.Costar
I tried this solution, but stull I got same error :/Till
Please provide more debugging info or a minimal reproducible example.Costar
what if your env file is not at the root, in my case i have 4 env files .env.dev env.test .env.prod etc and want to load the right one depending on my buildFootloose
@Footloose this is how you could achieve this: https://mcmap.net/q/245596/-how-to-specify-another-directory-or-name-for-the-env-file-in-nuxtCostar
the problem is, when you change env at the runtime, then the config which loaded in nuxt.config.js by using process.env.xxx will not be changed. because it has been packed at the build time.Mordecai
publicRuntimeConfig is renamed to runtimeConfig in nuxt 3Paradiddle
@Paradiddle thanks for the notification. I've edited my answer accordingly.Costar
The main problem of new Nuxt 3 approach it requires app context, You need to be sure app is setup before invoke useRuntimeConfig, but what if I want to use env-variable in some lib.js file, and this file can be executed in different contexts: node cli or nuxt app context.Primavera
@LukasPierce if it's out of Nuxt's context, then it's not Nuxt's job to handle such task. In that case, you can always use dotenv or alike.Costar
@Costar yes, but just read my answer, combination of vite.define and useRuntimeConfig - is more elegant solution which gives full flexibilityPrimavera
@kissu, the first link (edit: for Nuxt3) is broken.Terrarium
@DanielDanielecki hm, I am not sure how to find a correspondence between the old repo and the new one (ID does not match). I just removed it so far, probably not that big of a deal anyway.Costar
B
6

You can also use the env property with Nuxt nuxt.config.js:

export default {
  // Environment variables
  env: {
    myVariable: process.env.NUXT_ENV_MY_VAR
  },
  ...
}

Then in your plugin:

const myVar = process.env.myVariable
Blomquist answered 6/11, 2021 at 5:54 Comment(0)
P
6

This is very strange because we can't access process.env in Nuxt 3

In the Nuxt 3, we are invited to use the runtime config, but this is not always convenient, because the Nuxt application context is required.

But in a situation where we have some plain library, and we don’t want to wrap it in plugins nor composables functions, declaring global variables through vite / webpack is best:

// nuxt.config.ts
export default defineNuxtConfig({
  vite: {
    define: {
      MY_API_URL: JSON.stringify(process.env.MY_API_URL)
    }
  }
})

And then you can use in any file without dancing with a tambourine:

// some-file.ts
console.log('global var:', MY_API_URL) // replaced by vite/webpack in real value

If you want to use some env variables as you used to doing it before, then define full qualified name:

// nuxt.config.ts
export default defineNuxtConfig({
  vite: {
    define: {
      // dont forgot about JSON.stringify, because it adds quotes
      'process.env.APP_URL': JSON.stringify(process.env.APP_URL)
      // for example
      'process.env.APP_URL': '"https://myawesomesite.com"'
    }
  }
})

and then use it in your code:

console.log(process.env.APP_URL)

check this code in browser sources and you will see:

console.log("https://myawesomesite.com")

It means any variable defined in vite.define section its just a pattern for replacement in compile time.

Primavera answered 23/10, 2022 at 11:21 Comment(2)
vite: in defineNuxtConfig just throws a 500 error. Am I missing something about your suggestion? You are quite right, Nuxt frustrates some things that should "just work", and the use of plain libraries becomes quite limited because of this lack of env var.Marola
I think you trying use proccess.env.SOME_VARIABLE in your client code, so in this case you need define full name like 'proccess.env.SOME_VARIABLE', because it is just a string pattern and will be replaced by vite in compile type. Try my update examplePrimavera
N
4

For v3 there is a precise description in the official docs

You define a runtimeConfig entry in your nuxt.config.[ts,js] which works as initial / default value:

export default defineNuxtConfig({
  runtimeConfig: {
    recaptchaSiteKey: 'default value' // This key is "private" and will only be available within server-side
  }
}

You can also use env vars to init the runtimeConfig but its written static after build. But you can override the value at runtime by using the following env var:

NUXT_RECAPTCHA_SITE_KEY=SOMETHING DYNAMIC

If you need to use the config on client-side, you need to use the public property.

export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      recaptchaSiteKey: 'default value' // will be also exposed to the client-side
    }
  }
}

Notice the PUBLIC part in the env var:

NUXT_PUBLIC_RECAPTCHA_SITE_KEY=SOMETHING DYNAMIC
Nitrification answered 20/10, 2022 at 9:14 Comment(3)
let me use this answer to maybe help people struggling with the same thing I struggled. This answer to me is the correct one, just stressing in a detail, the default value must be there!, if you put recaptchaSiteKey: process.env.RECAPTHA_SITE_KEY but this Env variable is not there at build time, there will be no human way to later try to overwrite this on run time. It's not that the runtimeconfig.public.recaptchaSiteKey is null, but that it doesn't even exist. So don't forget a default value.Cityscape
Do these need to be prefixed by NUXT_ ?Vullo
@MiguelStevens Yes, afaik there is no way to do it without or another prefix..Nitrification
L
2

For Nuxt 3, first create your .env file.

# .env
HELLO="World"

Then put your HELLO env under runtimeConfig.public in nuxt.config.ts.

// nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      HELLO: process.env.HELLO
    }
  },
  devtools: { enabled: true }
})

Then in your .vue files access it with the useRuntimeConfig() method.

<!-- In your [app/componentName].vue -->

<template>
  Hello {{useRuntimeConfig().public.HELLO}}.
</template>

<!-- Or -->

<template>
  Hello {{helloValue}}.
</template>

<script>
const config = useRuntimeConfig();
const helloValue = config.public.HELLO;
</script>
Liberal answered 5/8, 2023 at 2:1 Comment(0)
P
1

It's very easy. Providing you an example with axios/nuxt

  1. Define your variable in the .env file:

    baseUrl=http://localhost:1337

  2. Add the variable in the nuxt.config.js in an env-object (and use it in the axios config):

    export default {env: {baseUrl: process.env.baseUrl},axios: {baseURL: process.env.baseUrl},}

  3. Use the env variable in any file like so:

    console.log(process.env.baseUrl)

Note that console.log(process.env) will output {} but console.log(process.env.baseUrl) will still output your value!

Penetration answered 17/9, 2021 at 13:43 Comment(1)
You should not use process.env.baseUrl but myPublicVariable as explained in my answer.Costar
H
0

For nuxt3 rc11, in nuxt.conf.ts file:

export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      locale: {
        defaultLocale: process.env.NUXT_I18N_LOCALE,
        fallbackLocale: process.env.NUXT_I18N_FALLBACK_LOCALE,
      }
    }
  },
...

and in .env file:

NUXT_I18N_LOCALE=tr
NUXT_I18N_FALLBACK_LOCALE=en

public: is very important otherwise it cannot read it and gives undefined error.

Heading answered 2/10, 2022 at 15:33 Comment(0)
T
0

I'm not sure if that's only me, but the config.myVar doesn't really exists (anymore?). For a public (client) case. I can clearly see it when console.logging the config, console.log({ config }) gives me enter image description here

Having said that, it only works when trying to access it via config.public.myVar.

For a completeness of this answer, I'm sending my remaining setup.

nuxt.config.ts

export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      recaptchaSiteKey: process.env.RECAPTCHA_SITE_KEY,
    },
  },
})

.env (in root folder location)

RECAPTCHA_SITE_KEY=123

composable/component

import { VueReCaptcha } from 'vue-recaptcha-v3'
import { RuntimeConfig } from 'nuxt/schema'
import { useNuxtApp } from '#app'

const config: RuntimeConfig = useRuntimeConfig()

const { vueApp } = useNuxtApp()
vueApp.use(VueReCaptcha, {
  siteKey: config.public.recaptchaSiteKey,
  loaderOptions: {
    autoHideBadge: true,
    renderParameters: {
      hl: 'en',
    },
  },
})
Terrarium answered 7/10, 2023 at 12:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.