28

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'
       }
  }
}
kissu
  • 40,416
  • 14
  • 65
  • 133
Denis Stephanov
  • 4,563
  • 24
  • 78
  • 174

7 Answers7

69

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 here and 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 as shown in this comment

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

Here is the official doc for that part.

kissu
  • 40,416
  • 14
  • 65
  • 133
  • Thank you for answer, I tried edit by your recommendation and I still have same error. I also update my question. – Denis Stephanov May 26 '21 at 20:48
  • Do you have a populated `.env` in your project? – kissu May 26 '21 at 21:14
  • Do you have a Github repo? Do you have a valid key in `.env`, no typo? How do you try this? – kissu May 26 '21 at 21:30
  • 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 config – Denis Stephanov May 26 '21 at 21:36
  • Show us some screenshots I guess. – kissu May 26 '21 at 22:03
  • what screenshot you mean? – Denis Stephanov May 26 '21 at 22:20
  • 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. – kissu May 26 '21 at 22:26
  • I tried this solution, but stull I got same error :/ – Denis Stephanov May 31 '21 at 13:13
  • Please provide more debugging info or a [repro]. – kissu May 31 '21 at 13:14
  • 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 build – PirateApp Sep 23 '21 at 13:01
  • 1
    @PirateApp this is how you could achieve this: https://stackoverflow.com/a/68338032/8816585 – kissu Sep 23 '21 at 21:38
  • 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. – Bagaskara Jan 10 '22 at 04:32
  • 1
    publicRuntimeConfig is renamed to runtimeConfig in nuxt 3 – Lengo Jan 16 '23 at 15:40
  • @Lengo thanks for the notification. I've edited my answer accordingly. – kissu Jan 16 '23 at 16:56
  • 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. – Lukas Pierce Feb 28 '23 at 13:25
  • @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. – kissu Feb 28 '23 at 14:23
  • @kissu yes, but just read my answer, combination of vite.define and useRuntimeConfig - is more elegant solution which gives full flexibility – Lukas Pierce Feb 28 '23 at 14:52
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
ctwhome
  • 753
  • 1
  • 13
  • 24
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!

user2912903
  • 182
  • 2
  • 4
  • 1
    You should not use `process.env.baseUrl` but `myPublicVariable` as explained in my answer. – kissu Sep 17 '21 at 14:02
1

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
kissu
  • 40,416
  • 14
  • 65
  • 133
spe92
  • 23
  • 7
  • 1
    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. – Cesc Mar 15 '23 at 13:51
  • Do these need to be prefixed by NUXT_ ? – Miguel Stevens Jul 28 '23 at 12:33
  • @MiguelStevens Yes, afaik there is no way to do it without or another prefix.. – spe92 Jul 29 '23 at 15:15
1

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.

Lukas Pierce
  • 807
  • 3
  • 9
  • 15
  • 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. – dapug Feb 20 '23 at 21:39
  • 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 example – Lukas Pierce Feb 28 '23 at 13:11
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.

Alp Altunel
  • 3,324
  • 1
  • 26
  • 27
0

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>
miltonbhowmick
  • 324
  • 1
  • 5
  • 17
Mot
  • 48
  • 6