Home > Web Front-end > JS Tutorial > How to Use .env Variables in Nuxt 2 and 3?

How to Use .env Variables in Nuxt 2 and 3?

Linda Hamilton
Release: 2024-11-13 08:28:02
Original
800 people have browsed it

How to Use .env Variables in Nuxt 2 and 3?

Using .env Variables in Nuxt 2 or 3

When incorporating external configurations into Nuxt, it's necessary to leverage the .env file, where sensitive data can be stored and referenced later in the Nuxt configuration. Here's a comprehensive guide on achieving this.

In Nuxt 2.13 and above, .env support is built-in. To utilize it, follow these steps:

  • Create an .env file in your project root.
  • Define your variables, such as:

    MY_VARIABLE="Hello World"
    Copy after login
  • In your nuxt.config.js, import the .env values into the publicRuntimeConfig or privateRuntimeConfig objects:

    export default {
    publicRuntimeConfig: {
      myPublicVariable: process.env.MY_VARIABLE,
    },
    privateRuntimeConfig: {
      myPrivateVariable: process.env.MY_PRIVATE_VARIABLE,
    },
    }
    Copy after login

In Nuxt 3, the process is slightly different:

  • In nuxt.config.js:

    import { defineNuxtConfig } from 'nuxt3'
    
    export default defineNuxtConfig({
    runtimeConfig: {
      public: {
        myPublicVariable: process.env.MY_VARIABLE,
      },
    },
    })
    Copy after login
  • In any component:

    <script setup lang="ts">
    const config = useRuntimeConfig()
    config.myPublicVariable
    </script>
    Copy after login
  • In composables:

    export default () => {
    const config = useRuntimeConfig()
    console.log(config.myPublicVariable)
    }
    Copy after login

When defining variables in your .env file, remember to avoid using spaces and special characters. For example:

API_URL=https://example.com/api
Copy after login

Now, you can effortlessly access these variables anywhere in your Nuxt application. If facing any issues, consult the official Nuxt documentation for further guidance.

The above is the detailed content of How to Use .env Variables in Nuxt 2 and 3?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template