Environment variables in Nuxt 3

A guide on how to use environment variables on Nuxt 3

Jose Garcia
2 min readFeb 22, 2023
Purple forest
Photo by Stable Diffusion

I recently upgraded my portfolio to Nuxt 3. And surprise surprise the environment variables don’t work anymore. So, after finishing a small ordeal to get them working, this article was born.

This article goes over how to set up environment variables on Nuxt 3.

There are several ways to use environment variables. The configuration I develop here protects your sensitive information.

This tutorial has three steps:

Steps

  1. Define variables inside the .env file.
  2. Inject variables thru the runtimeConfig configuration.
  3. Use variables.

Let’s begin.

Define variables inside the .env file

At the root of your project, set up a .env file.

NUXT_GOOGLE_TOKEN=asdf
NUXT_GITHUB_TOKEN=token
NUXT_TARGET_EMAIL=email
NUXT_SERVICE_MAILER_URL=url

You can set here your sensitive information. Notice that you don’t have to prepend NUXT to your variables.

This file should be added to .gitignore.

Inject variables

On your nuxt.config.js file, inside defineNuxtConfig add the following:

export default defineNuxtConfig({
...
runtimeConfig: {
googleToken: process.env.NUXT_GOOGLE_TOKEN,
public: {
githubToken: process.env.NUXT_GITHUB_TOKEN,
targetEmail: process.env.NUXT_TARGET_EMAIL,
mailerUrl: process.env.NUXT_SERVICE_MAILER_URL,
},
},
...
});

That will inject your variables. The variables under runtimeConfig will be available only server side. Yet, the variables under the public object are accessible on the browser.

Use variables

To use the variables we injected, we need to get them from the runtimeConfig function. Something like this:

const { githubToken, targetEmail, mailerUrl } = useRuntimeConfig();

These variables are accessible from all your components.

Conclusions

You can use environment variables in Nuxt 3 by:

  1. Defining the variables inside a .env file.
  2. Injecting variables thru the runtimeConfig configuration.

After that, access your variables thru the runtimeConfig function.

I hope this was helpful to you, until next time.

--

--

Jose Garcia

Hello There! I am a fullstack developer, a fan of open source and crypto and an obssesive fella. Well met.