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

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, you can use the following for Nuxt3

nuxt.config.js

import { defineNuxtConfig } from 'nuxt3'

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

In any component

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

Leave a Comment