Accessing Environment Variables in Nuxt 2 or 3: .env Made Easy
When using environment variables in your Nuxt projects, whether Nuxt 2 or 3, it's essential to understand the correct approach. In this article, we'll explore how to read environment variables from your .env file in Nuxt's configuration.
In Nuxt 2.13 or above, the use of @nuxtjs/dotenv is no longer necessary as the framework natively supports environment variables. To define your variables, create an .env file at the root of your project and populate it with key-value pairs.
Nuxt 2.13 or Above
In your nuxt.config.js, define your environment variables using publicRuntimeConfig or privateRuntimeConfig, depending on their intended usage.
export default { publicRuntimeConfig: { myPublicVariable: process.env.PUBLIC_VARIABLE, }, privateRuntimeConfig: { myPrivateToken: process.env.PRIVATE_TOKEN, }, };
Nuxt 3
Nuxt 3 introduces the runtimeConfig object in nuxt.config.js. Define your environment variables here:
import { defineNuxtConfig } from 'nuxt3'; export default defineNuxtConfig({ runtimeConfig: { public: { secret: process.env.SECRET, }, }, });
To access these variables in your components, use this.$config in Nuxt 2 and useRuntimeConfig() in Nuxt 3.
Accessing Environment Variables in Nuxt.config
For Nuxt.config, you can directly access environment variables using process.env.VARIABLE_NAME.
export default { modules: [ ['@nuxtjs/recaptcha', { siteKey: process.env.RECAPTCHA_SITE_KEY, version: 3, size: 'compact', }], ], };
By following these steps, you can seamlessly utilize environment variables in your Nuxt projects. Please note that the syntax may vary slightly depending on the Nuxt package you're using. Refer to the official documentation for specific guidance.
The above is the detailed content of How to Access Environment Variables in Your Nuxt 2 or 3 Project?. For more information, please follow other related articles on the PHP Chinese website!