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

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

Navigating PopUpWindows using SeleniumIn this guide, learn the best

I have attempted to manage a particular PopUp / new Window in Java using SeleniumServer, but unfortunately, it is not functioning as expected. Here is what I have tried: selenium.click("css=a[title=\"Some irrelevant title\"] > div.text"); Thr ...

Using Javascript to choose an option from a dropdown menu

const salesRepSelect = document.querySelector('select[name^="salesrep"]'); for (let option of salesRepSelect.options) { if (option.value === 'Bruce Jones') { option.selected = true; break; } } Can someone please ...

AngularJS - "Refrain from replicating items in a repeater"

I am facing an issue with creating HTML textarea elements for each member of an array. Despite consulting the AngularJS documentation and attempting different track by expressions, I am unable to render them. The problem arises when a user inputs the same ...

Utilizing Angular: Importing Scripts in index.html and Implementing Them in Components

Currently, I am attempting to integrate the Spotify SDK into an Angular application. While I have successfully imported the script from the CDN in index.html, I am encountering difficulties in utilizing it at the component level. It seems like there may be ...

Querying a map within a Mongo function results in an empty variable when accessed outside of the function, but

Currently, I am facing an issue while trying to create an array of objects using the map function in Mongo and node/express JS. Strangely, when I utilize console.log outside the map function, the array appears empty. However, within the map function, each ...

Discover the outcome of clicking on an object (mock tests)

I am just starting out with React and I'm unsure about when to use mocking. For instance, within the 'ListItem' component, there is a 'click me' button that reveals a dropdown for 'cameras'. Should I focus on testing what ...

Unusual behavior observed in AngularJs local variables

This code snippet is from the controller: cat1=[]; $.getJSON('categories/1/', function(data) { cat1 = data; //this returns a JSON object }); //cat2..4 are also JSONs $scope.pictures=[cat1,cat2,cat3,cat4,cat5]; The issue here seems to be th ...

Utilize Jasmine's AJAX spy to intercept and inspect the error request

I am encountering an issue while trying to monitor the ajax error request and receiving the following error message. Can someone assist me with this? TypeError: e.error is not a function Code snippet for JS testing : function postSettings() { $ ...

Revamp the Side Navigation Feature to Identify the Currently Viewed Section of the Page

My website currently features a side navigation bar that dynamically updates based on the user's scroll position. When the user reaches a specific height, a class is added to a div in the sidebar, turning it orange and indicating which part of the pag ...

Encountering an issue with top-level await in Angular 17 when utilizing pdfjs-dist module

While using the Pdfjs library, I encountered an error message that reads: Top-level await is not available in the configured target environment ("chrome119.0", "edge119.0", "firefox115.0", "ios16.0", "safari16.0" + 7 overrides) /****/ webpack_exports = g ...

streaming audio data from a MongoDB database to an HTML audio element

As part of my current project, I am delving into the realm of creating an audio player. The concept of database storage for files is relatively new to me, as my previous experience has mainly involved storing strings. Up to this point, here's what I ...

Tips for using MatTableDataSource in a custom Thingsboard widget

After creating multiple custom Thingsboard widgets, I've discovered that I can access a significant portion of @angular/material within my widget code. While I have successfully implemented mat-table, I now want to incorporate pagination, filtering, a ...

PHP may not be the only language that deals with website security concerns. This question on website security extends beyond just PHP and

Let's imagine we have files named "index.htm" and "routines.php". In the scenario, "index.htm" will eventually reach out to "routines.php" using JavaScript (AJAX). Now, here is the query: how can "routines.php" confirm that the request originated fr ...

Ionic ion-view missing title issue

I'm having trouble getting the Ionic title to display on my page: http://codepen.io/hawkphil/pen/oXqgrZ?editors=101 While my code isn't an exact match with the Ionic example, I don't want to complicate things by adding multiple layers of st ...

Angular project icons not displaying in the browser

My current project in Angular was functioning properly until recently. I am facing an issue where the images are not being displayed on the browser when I run ng serve, resulting in a 404 error. Interestingly, everything else seems to be working fine witho ...

Tips for showcasing API information with Nativescript Vue utilizing Axios

When running this code in a web browser, I am able to retrieve JSON data using v-for: export default { data() { return { orders: [] } }, created() { axios.get('https://development.octavs.com/testapi.json') .then(r ...

Enclose each set of objects, such as text, within a separate div, except for div elements

Is there a way to wrap each immediate group of objects that are not contained in a div with a wrap class? Input: var $code = 'Lorem Ipsum <p>Foo Bar</p> <div class="myclass"></div> <p>Foo Bar</p> <div clas ...

Applying style changes to the height on scroll event in Javascript for Chrome, Firefox, and Internet Explorer

I am working on triggering an event when scrolling to a specific height. I have code that successfully adds a style in Chrome, but it is not functioning properly in IE. Can anyone provide assistance? myID = document.getElementById("subnav"); var mySc ...

Launching a pre-built React application

I'm facing an issue while attempting to run a pre-existing React App on my Mac locally. I have all the source files and node.js installed on my machine. Upon running npm install, I encountered a massive list of deprecations and npm ERRors that surpas ...

Use leaflet.js in next js to conceal the remainder of the map surrounding the country

I'm currently facing an issue and would appreciate some assistance. My objective is to display only the map of Cameroon while hiding the other maps. I am utilizing Leaflet in conjunction with Next.js to showcase the map. I came across a helpful page R ...