Home >Web Front-end >JS Tutorial >Why is My .env Variable Not Working in My Nuxt Application?

Why is My .env Variable Not Working in My Nuxt Application?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-15 05:44:03346browse

Why is My .env Variable Not Working in My Nuxt Application?

Troubleshooting .env Variables in Nuxt 2 and 3

Problem Statement

Nuxt applications may encounter an error when using .env variables to configure modules, such as ReCaptcha. The console may display "ReCaptcha error: No key provided," despite the presence of an .env file with the required key.

Explanation

In Nuxt 2.13 and above, the @nuxtjs/dotenv module is no longer necessary as runtime configuration is built into the framework. To utilize .env variables, follow these steps:

Nuxt 2.13

  • Create an .env file at the project root.
  • Import the necessary variables into nuxt.config.js:

    export default {
    publicRuntimeConfig: {
      recaptcha: {
        siteKey: process.env.RECAPTCHA_SITE_KEY,
        version: 3,
        size: 'compact'
      }
    }
    }
  • Use the variables in your components using this.$config.

Nuxt 3

  • Import the following:

    import { defineNuxtConfig } from 'nuxt3'
  • Use the following in nuxt.config.js:

    export default defineNuxtConfig({
    runtimeConfig: {
      public: {
        secret: process.env.SECRET,
      }
    }
    }
  • Use the variables in your components using useRuntimeConfig():

    <script setup lang="ts">
    const config = useRuntimeConfig()
    config.secret
    </script>
  • Use the variables in composables:

    export default () => {
    const config = useRuntimeConfig()
    console.log(config.secret)
    }

Nuxt 2 Pre-2.13

If using Nuxt 2 pre-2.13, the @nuxtjs/dotenv module is required. You can add this method to your nuxt.config.js file:

import dotenv from 'dotenv'
dotenv.config()

The above is the detailed content of Why is My .env Variable Not Working in My Nuxt Application?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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