Using environmental variables in Nuxt 2 or Nuxt 3 - a step-by-step guide

I have an .env file located in the root of my project. In my nuxt config, I am using variables to configure ReCaptcha as shown below:

import dotenv from 'dotenv'
dotenv.config()

export default {
    modules: [
        ['@nuxtjs/recaptcha', {
          siteKey: process.env.RECAPTCHA_SITE_KEY,
          version: 3,
          size: 'compact'
        }],
    ]
}

My .env file contains the following:

RECAPTCHA_SITE_KEY=6L....

However, the application consistently fails with a console log error:

ReCaptcha error: No key provided

Interestingly, when I directly hard-code the ReCaptcha key like this: siteKey: 6L...., the app starts working. This leads me to believe that the issue stems from reading the .env properties in the nuxt.config file.

Do you have any suggestions on how to resolve this?

EDIT: I attempted to update my nuxt.config based on recommendations from @kissu and examples I found here: https://www.npmjs.com/package/@nuxtjs/recaptcha

Here is the revised nuxt.config which unfortunately also did not work:

export default {
    modules: [
       '@nuxtjs/recaptcha',
    ],
    publicRuntimeConfig: {
       recaptcha: {
         siteKey: process.env.RECAPTCHA_SITE_KEY,
         version: 3,
         size: 'compact'
       }
  }
}

Answer №1

I found this informative video to be quite helpful and informative, providing some up-to-date information that I was previously unaware of. I plan on updating my answer with the correct information soon.


If you are using Nuxt version 2.13 or higher, there is no need for using @nuxtjs/dotenv or similar packages as it is already integrated into the framework.

To utilize variables, you must have an .env file at the root of your project which should be excluded from git. You can define keys in this file such as

PUBLIC_VARIABLE="https://my-cool-website.com"
PRIVATE_TOKEN="1234qwer"

In your nuxt.config.js, you need to assign these keys to either the publicRuntimeConfig or privateRuntimeConfig objects based on your requirements:

export default {
  publicRuntimeConfig: {
    myPublicVariable: process.env.PUBLIC_VARIABLE,
  },
  privateRuntimeConfig: {
    myPrivateToken: process.env.PRIVATE_TOKEN
  }
}

Note: The publicRuntimeConfig can be used anywhere, while the privateRuntimeConfig is limited to SSR (Server-Side Rendering) to keep sensitive data secure.

A common usage of privateRuntimeConfig is in methods like nuxtServerInit or during the build process to fetch data from headless CMS APIs.

For more details, refer to this blog post: https://nuxtjs.org/blog/moving-from-nuxtjs-dotenv-to-runtime-config/


  • You can directly access these variables in any .vue file by using
this.$config.myPublicVariable
  • In Nuxt's /plugins directory, you can access them like this
export default ({ $axios, $config: { myPublicVariable } }) => {
  $axios.defaults.baseURL = myPublicVariable
}
  • If you need to use a variable in a Nuxt module or in your nuxt.config.js file, you can reference it directly by
process.env.PRIVATE_TOKEN

Sometimes, the syntax might vary, so check your specific Nuxt module documentation for guidance.

// Example for @nuxtjs/gtm
publicRuntimeConfig: {
  gtm: {
    id: process.env.GOOGLE_TAG_MANAGER_ID
  }
},

If you are using target: server (default value), after running yarn build and yarn start, you can change environment variables without needing a rebuild. This is why it's called RuntimeConfig!

Nuxt3 update

According to the documentation, in Nuxt3 you can implement the following:

nuxt.config.js

import { defineNuxtConfig } from 'nuxt3'

export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      secret: process.env.SECRET,
    }
  }
}

In any component

<script setup lang="ts">
  const config = useRuntimeConfig()
  config.secret
</script>

In a composable like /composables/test.js as shown below

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

Refer to the official documentation for more details on this topic.

Answer №2

You have the option to utilize the env feature in Nuxt nuxt.config.js:

export default {
  // Environment variables
  env: {
    myVariable: process.env.NUXT_ENV_MY_VAR
  },
  ...
}

Subsequently, within your plugin:

const myVar = process.env.myVariable

Answer №3

It's quite peculiar that accessing process.env in Nuxt 3 is not possible.

In Nuxt 3, the suggestion is to utilize runtime config, but this approach isn't always practical as it requires the Nuxt application context.

In cases where we have a basic library and prefer not to wrap it in plugins or composable functions, declaring global variables through vite/webpack seems to be the optimal solution:

// nuxt.config.ts
export default defineNuxtConfig({
  vite: {
    define: {
      MY_API_URL: JSON.stringify(process.env.MY_API_URL)
    }
  }
})

This allows us to use the variable in any file without unnecessary complications:

// some-file.ts
console.log('global var:', MY_API_URL) // will be replaced by vite/webpack with actual value

If you wish to incorporate environment variables as before, specify the fully qualified name:

// nuxt.config.ts
export default defineNuxtConfig({
  vite: {
    define: {
      // remember to use JSON.stringify to add quotes
      'process.env.APP_URL': JSON.stringify(process.env.APP_URL)
      // for example
      'process.env.APP_URL': '"https://myawesomesite.com"'
    }
  }
})

You can then access these variables in your code:

console.log(process.env.APP_URL)

If you inspect the browser sources, you'll notice:

console.log("https://myawesomesite.com")

Essentially, any variable defined in the vite.define section serves as a placeholder for substitution during compile time.

Answer №4

In the official documentation for v3 here, there is a detailed explanation.

To set up runtimeConfig in your nuxt.config.[ts,js] file, you can define it as follows:

export default defineNuxtConfig({
  runtimeConfig: {
    recaptchaSiteKey: 'default value' // This key is considered "private" and only accessible server-side
  }
}

You can initialize runtimeConfig using environment variables, but they are statically written after the build process. To dynamically override the value at runtime, use this env var:

NUXT_RECAPTCHA_SITE_KEY=SOMETHING DYNAMIC

If you want to access the configuration on the client-side, use the public property instead:

export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      recaptchaSiteKey: 'default value' // This will also be available on the client-side
    }
  }
}

Take note of the PUBLIC part in the following env var:

NUXT_PUBLIC_RECAPTCHA_SITE_KEY=SOMETHING DYNAMIC

Answer №5

Here is a straightforward method. I will present you with an example using axios/nuxt.

  1. Firstly, define your variable in the .env file:

    baseUrl=http://localhost:1337

  2. Next, add the variable to the nuxt.config.js within an env-object (and utilize it in the axios configuration):

    export default {env: {baseUrl: process.env.baseUrl},axios: {baseURL: process.env.baseUrl},}

  3. You can now use the environment variable in any file like this:

    console.log(process.env.baseUrl)

Note: Keep in mind that while console.log(process.env) will display {}, console.log(process.env.baseUrl) will still reveal your specified value!

Answer №6

To start with Nuxt 3, begin by creating a new file called .env.

# .env
HELLO="World"

Next, place your HELLO environment variable within the runtimeConfig.public section of your nuxt.config.ts file.

// nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      HELLO: process.env.HELLO
    }
  },
  devtools: { enabled: true }
})

After setting up the configuration, you can access the value in your .vue files using the useRuntimeConfig() method.

<!-- In your [app/componentName].vue -->

<template>
  Hello {{useRuntimeConfig().public.HELLO}}.
</template>

<!-- Or -->

<template>
  Hello {{helloValue}}.
</template>

<script>
const config = useRuntimeConfig();
const helloValue = config.public.HELLO;
</script>

Answer №7

In the nuxt3 rc11 release, make sure to include the following configuration in the nuxt.conf.ts file:

export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      locale: {
        defaultLocale: process.env.NUXT_I18N_LOCALE,
        fallbackLocale: process.env.NUXT_I18N_FALLBACK_LOCALE,
      }
    }
  },
...

Additionally, update the .env file with the necessary variables:

NUXT_I18N_LOCALE=tr
NUXT_I18N_FALLBACK_LOCALE=en

It is crucial to include 'public:' in the configuration to avoid any undefined errors.

Answer №8

It seems like I might be the only one experiencing this issue, but the config.myVar does not appear to exist anymore. Specifically for a public (client) case. I can confirm this as when I console.log the config, console.log({ config }) displays an empty result https://i.sstatic.net/ZVQmC.png

However, it seems to work fine when accessed through config.public.myVar.

To provide a full explanation, here is my current setup:

nuxt.config.ts

export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      recaptchaSiteKey: process.env.RECAPTCHA_SITE_KEY,
    },
  },
})

.env (located in root folder)

RECAPTCHA_SITE_KEY=123

composable/component

import { VueReCaptcha } from 'vue-recaptcha-v3'
import { RuntimeConfig } from 'nuxt/schema'
import { useNuxtApp } from '#app'

const config: RuntimeConfig = useRuntimeConfig()

const { vueApp } = useNuxtApp()
vueApp.use(VueReCaptcha, {
  siteKey: config.public.recaptchaSiteKey,
  loaderOptions: {
    autoHideBadge: true,
    renderParameters: {
      hl: 'en',
    },
  },
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for acquiring a comprehensive catalog of Node.js modules?

Currently, I am working on integrating NPM functionality into my Node.js applications. My goal is to be able to analyze the node modules available on my system. When referring to a "module" in this context, it could either be an identifier like "fd" or a f ...

Changing URI to File Object using JavaScript

I have successfully retrieved the URI of a selected file in my Ionic app using the cordova-fileChooser plugin. https://i.sstatic.net/NxXti.jpg Next, I used the cordova-plugin-filepath to obtain the absolute path of the file from the nativeURL on the phon ...

What could be causing my AJAX code to malfunction?

This issue should be a simple fix, but I'm completely stumped. I'm working on a test involving an AJAX request and trying to display a variable from a drop-down menu. Unfortunately, the code isn't running at all. Can someone please point ou ...

Eliminate event listener using unique identifier

Is there a way to retrieve information about all event handlers for an element in JavaScript? $._data($('#element_id')[0], "events"); This will provide a detailed record of every event handler attached to the element. 0: {type: "c ...

mention a Vue.js component computed property that points to a specific DOM element

Is there a way to access the DOM element that initiated a method inside a Vue component computed property? For example: <template> <img :src="getUrl" class="image1"/> <img :src="getUrl" class="image2"/> </template> <scri ...

Animated div or fieldset featuring a multi-step form

I have recently put together a detailed step-by-step guide. Each step is wrapped in its own "fieldset" within a single .html file. To navigate back and forth, I have incorporated javascript into the process. However, as time goes on, I am noticing that th ...

Issue with utilizing addEventListener("load") in Firefox in conjunction with <iframe>

I've encountered an issue with my iframe when it is used as the target for a form. In all major browsers, except for Firefox, the iframe successfully removes the main element upon pressing the submit button. However, in Firefox, the main element is re ...

Choosing an automatically generated choice from a C# web browser control

Using a c# web browser control, I am navigating a commercial website to access a list of potential jobs. However, I encountered an issue while trying to bid on these jobs through some links. The problem arises when dealing with forms that contain two sele ...

Analyzing a text file against a string to identify discrepancies using Node.js

Recently, I came across a dilemma involving a text file containing information on all Wifi connections (such as ssid, mac no, strength, etc.) that were within my laptop's range just 2 minutes ago. Now, I've rerun the code and obtained the current ...

How to implement the Ionic ToastController without being confined to a Vue instance

I am currently facing a challenge while trying to utilize the ToastController of Ionic outside a vue instance. I have created a separate actions file which will be loaded within the vue instance, handling a request. Within this request, certain validations ...

Running on Node.js, the Promise is activated, yet there remains an issue with the function

I've encountered a strange issue that I can't seem to diagnose. It's showing a TypeError: My code is returning 'function is undefined', which causes the API call to fail. But oddly enough, when I check the logs and breakpoints, it ...

What could be causing the header of the datatable to be out of alignment with the rest of

I'm facing an issue with my datatable where the header is misaligned with the content. Can someone please assist me in adjusting the header and content so that they are parallel? It doesn't look right at the moment. <div style="margin-top:1 ...

Utilizing Google Places Autocomplete to tailor search outcomes

I'm currently working on customizing the output of my Google Places autocomplete code. Specifically, I want to change the displayed result when a user selects an address from the list. For example, one of the results is: '45 Alexandra Road Holi ...

Is there a way for me to show "No data" when the json response in vue js is empty?

Is it possible to display a message like "No search results" when there is no data available? I am new to this and only have basic understanding. Can someone guide me on how to achieve this? Example of my JSON data when it's empty: { "status": true ...

Guide to pinpointing a location with Google Maps

I am currently working on setting up a contact page that includes Google Maps to show the location of a meeting place. Here is the code I am using: JavaScript (function(){ document.getElementById('map_canvas').style.display="block"; var ...

Automatically navigate to a specific selection within the Autocomplete feature

Imagine having a dropdown or Autocomplete list in Material-UI with a long list of items. How can you make the list automatically scroll to a specific item when you open the dropdown? For instance, if we take the list of top100Films, the initial displayed i ...

What is the best way to develop a card stack swiper similar to Tinder using React?

After experimenting with various packages, I found that none were satisfactory for creating a customizable card swiper. As a result, I am now considering developing my own solution. What would be the best approach for adding animations, enabling draggable ...

Module '../../third_party/github.com/chalk/supports-color' not found in the directory

Within my tutoring-frontend-main project folder There is a file named package.json { "name": "app-frontend", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build --prod", "test": "n ...

Combining GET and POST requests in ExpressJS on a single route

As I work on setting up a questionnaire in Express JS with EJS as the renderer, I have already created individual pages for each question. These pages are accessible through static links using the app.get('/question/:number?', routes.questions) f ...

Tips for importing all global Vue components in a single file

I currently have a large Vuejs application where I imported all my components globally in the app.js file. While it's functioning well, I believe reorganizing the component imports into a separate file would improve the overall structure of the projec ...