Home > Article > Web Front-end > How to Access .env Variables in Nuxt 2 or 3: A Comprehensive Solution
Nuxt.js allows you to seamlessly manage environment variables through .env files, but encountering issues is not uncommon. This guide provides a step-by-step solution to the recurring problem of accessing .env variables in Nuxt's configuration.
You are facing a failure in your Nuxt application while attempting to read environment variables from .env within nuxt.config.js or another module. Console errors indicate that a key is missing, despite being specified in the .env file.
In earlier versions of Nuxt, .env variables were not automatically loaded into the application. Additional packages, such as @nuxtjs/dotenv, were required to facilitate the loading process. However, with the introduction of Nuxt 2.13,dotenv handling is now built into the framework, eliminating the need for external packages.
For Nuxt 2.13 or above:
export default { publicRuntimeConfig: { myPublicVariable: process.env.PUBLIC_VARIABLE, }, privateRuntimeConfig: { myPrivateToken: process.env.PRIVATE_TOKEN, } }
For Nuxt 3:
import { defineNuxtConfig } from 'nuxt3' export default defineNuxtConfig({ runtimeConfig: { public: { secret: process.env.SECRET, } } }
By following these steps, you can effectively use .env variables in Nuxt 2 or 3. Remember, .env files are valuable for storing sensitive information and configuration values, ensuring they are not exposed to the public.
The above is the detailed content of How to Access .env Variables in Nuxt 2 or 3: A Comprehensive Solution. For more information, please follow other related articles on the PHP Chinese website!