I found this informative video to be quite helpful and informative, providing some up-to-date information that I was previously unaware of. I plan on updating my answer with the correct information soon.
If you are using Nuxt version 2.13 or higher, there is no need for using @nuxtjs/dotenv
or similar packages as it is already integrated into the framework.
To utilize variables, you must have an .env
file at the root of your project which should be excluded from git. You can define keys in this file such as
PUBLIC_VARIABLE="https://my-cool-website.com"
PRIVATE_TOKEN="1234qwer"
In your nuxt.config.js
, you need to assign these keys to either the publicRuntimeConfig
or privateRuntimeConfig
objects based on your requirements:
export default {
publicRuntimeConfig: {
myPublicVariable: process.env.PUBLIC_VARIABLE,
},
privateRuntimeConfig: {
myPrivateToken: process.env.PRIVATE_TOKEN
}
}
Note: The publicRuntimeConfig
can be used anywhere, while the privateRuntimeConfig
is limited to SSR (Server-Side Rendering) to keep sensitive data secure.
A common usage of privateRuntimeConfig
is in methods like nuxtServerInit
or during the build process to fetch data from headless CMS APIs.
For more details, refer to this blog post: https://nuxtjs.org/blog/moving-from-nuxtjs-dotenv-to-runtime-config/
- You can directly access these variables in any
.vue
file by using
this.$config.myPublicVariable
- In Nuxt's
/plugins
directory, you can access them like this
export default ({ $axios, $config: { myPublicVariable } }) => {
$axios.defaults.baseURL = myPublicVariable
}
- If you need to use a variable in a Nuxt module or in your
nuxt.config.js
file, you can reference it directly by
process.env.PRIVATE_TOKEN
Sometimes, the syntax might vary, so check your specific Nuxt module documentation for guidance.
// Example for @nuxtjs/gtm
publicRuntimeConfig: {
gtm: {
id: process.env.GOOGLE_TAG_MANAGER_ID
}
},
If you are using target: server
(default value), after running yarn build
and yarn start
, you can change environment variables without needing a rebuild. This is why it's called RuntimeConfig!
Nuxt3 update
According to the documentation, in Nuxt3 you can implement the following:
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 below
export default () => {
const config = useRuntimeConfig()
console.log(config.secret)
}
Refer to the official documentation for more details on this topic.