Home > Web Front-end > JS Tutorial > How to Access Environment Variables in Your Nuxt 2 or 3 Project?

How to Access Environment Variables in Your Nuxt 2 or 3 Project?

DDD
Release: 2024-11-11 17:58:02
Original
266 people have browsed it

How to Access Environment Variables in Your Nuxt 2 or 3 Project?

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,
  },
};
Copy after login

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,
    },
  },
});
Copy after login

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',
    }],
  ],
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template