Setting up Nuxt.js env

Back-End Dev Note August 16, 2022

Hello, I’m Eric, a back-end engineer for two years now. To be frank, I haven’t been a big fan of Nuxt the first time I started using it, but as time moves on, I started to appreciate Nuxt bit by bit.

When creating applications, .env or dotenv files is a really big help when it comes to app development. It’s a simple text configuration file for controlling your applications’ environment constants. I.e., your API keys and services’ configurations.

This is how you can use your .env variables on your Nuxt application.

1) Create a variable on your project’s .env file.

Go to your project’s root directory and open your .env file. Once opened, declare your variable on a new line.


VARIABLE_NAME=VALUE                                          I.e.: API_URL=http://localhost:8000


2) Set your Nuxt config file.

On your project’s root directory as well. Open the file nuxt.config.js. Now there are two ways, that I know of, to implement your environment variable. First is through using the env property and second is through using publicRuntimeConfig / privateRuntimeConfig. The difference of these two is that env property is required at build time while the publicRuntimeConfig / privateRuntimeConfig is required at run time. Note: this is only for Nuxt versions > 2.12+.


Using our example API_URL above…

import { resolve } from 'path'
 *  @type { import("@nuxt/types").NuxtConfig }

export default {
	env: {
		apiUrl: process.env.API_URL
	publicRuntimeConfig: {
		apiUrl: process.env.API_URL
	privateRuntimeConfig: {
		// For private/sensitive information such as API secret tokens


For the Runtime Config Property, the difference between publicRuntimeConfig and privateRuntimeConfig is that, as the name suggests, public should hold all env variables that are public as these will be exposed on the frontend. This could include a reference to your public URL for example. Like our example API_URL. For private, these are variables that should not be exposed on the frontend. This could include a reference to your API secret tokens for example.

3) Call your env variables on any of your pages/components.

mounted () {