How to Set & Use .env Environment Variables in Nuxt.js

Published on August 22, 2020 34 sec read

.env or dotenv file is a configuration file of an application. It loads environment variables from a .env file into process.env. In this article, I’m going to show how to set & use it in Nuxt.js.

Table of Contents

  1. Install dotenv Package
  2. Set & Use Variable
  3. Recommendation

Install dotenv Package

To use .env files in Nuxt, we need to install @nuxtjs/dotenv modules. Let’s do this:

npm install @nuxtjs/dotenv

Then register the dotenv module to nuxt.config.js file like:

buildModules: [
    '@nuxtjs/dotenv'
],

Set & Use Variable

Create a .env file at the root of your project directory. Then let’s create a simple variable:

TEST_VARIABLE=Hello MyNotePaper

Now we’re able to get the variable in our app like:

console.log(process.env.TEST_VARIABLE);

Amazing, it works! 🙂

Recommendation

In Nuxt v2.13, they introduced runtime config feature. Please try to use environment variables like new method. Have a look at their blog post.

That’s it. Thanks for reading. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *