Tutorial

How To Use Environment Variables in Vue.js

Updated on March 17, 2021
author

Daniel Schmitz

How To Use Environment Variables in Vue.js

Introduction

In a web app, you will most likely have to access a backend API server through a URL. In a development environment - when you are working locally, this URL can be something like: http://localhost:8080/api. In a production environment - when the project has been deployed, this URL can be something like: https://example.com/api. Environment variables allow you to change this URL automatically, according to the current state of the project.

With Vue.js, it is possible to use environment variables through files with the .env file extension. These files are responsible for storing information that is specific to the environment (“development”, “testing”, “production”, etc.).

In this article, you will learn how to work with distinct configurations between development and production mode for Vue.js projects using Vue CLI 3+ and 2.

Prerequisites

To follow along with this article, you will need:

This tutorial was verified with Node v15.1.0, npm v6.14.8, Vue.js v2.6.12, TypeScript v3.9.3, @vue/cli v4.5.8, and vue-cli v2.9.6.

Step 1 — Using .env Files with Vue CLI 3+

Vue CLI 4 is the current version of @vue/cli. Once you create a Vue.js project, you can add .env and .env.production files.

With your terminal, create a new Vue.js project with @vue/cli:

  1. npx @vue/cli create vue-cli-env-example

Navigate to the project directory;

  1. cd vue-cli-env-example

With a code editor, create a .env file and add values like the following:

.env
VUE_APP_ROOT_API=http://localhost/api

Then, with a code editor, create a .env.production file and add values like the following:

.env.production
VUE_APP_ROOT_API=http://www.example.com/api

Note: The VUE_APP_ prefix is important here, and variables without that prefix will not be available in your app.

After creating the VUE_APP_ROOT_API variable, you can use it anywhere in Vue through the global process.env object:

process.env.VUE_APP_ROOT_API

For example, open the HelloWorld.vue file and in the <script> tag add the following:

src/components/HelloWorld.vue
<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  mounted() {
    console.log(process.env.VUE_APP_ROOT_API)
  },
}
</script>

If you compile the application with development values:

  1. npm run serve

This command will use the .env value and the console log will display: http://localhost/api.

If you compile the application with production values:

  1. npm run serve -- --mode=production

Note: It is important to use double hyphens here to pass the flags from npm to vue-cli-service.

You can also use this alternative command:

  1. vue-cli-service serve --mode=production

This command will use the .env.production value and the console log will display: http://www.example.com/api.

By default, Vue CLI will support three modes: “development”, "test’, and “production”. For more information on using environment variables with Vue CLI 3, consult the official documentation.

Step 2 — Using .env Files with Vue CLI 2

Vue CLI 2 is the previous version of vue-cli. Once you create a Vue.js project, you can use dev.env.js, test.env.js, and prod.env.js.

With your terminal, create a new Vue.js project with vue-cli:

  1. npx vue-cli init webpack vue-cli-two-env-example

There are two files in the config directory: dev.env.js and prod.env.js.

These files are used in development and production mode. When you are running the application through the npm run dev command, the dev.env.js file is used. When you compile the project for production with the npm run build command, the prod.env.js file is used instead.

Open dev.env.js in a code editor and add the ROOT_API value:

config/dev.env.js
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  ROOT_API: '"http://localhost/api"'
})

Next, open prod.env.js in a code editor and add the ROOT_API value:

config/prod.env.js
'use strict'
module.exports = {
  NODE_ENV: '"production"',
  ROOT_API: '"http://www.example.com/api"'
}

After creating the ROOT_API variable, you can use it anywhere in Vue through the global process.env object:

process.env.ROOT_API

For example, open the HelloWorld.vue file and in the <script> tag add the following:

src/components/HelloWorld.vue
<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  mounted() {
    console.log(process.env.ROOT_API)
  },
}
</script>

If you compile the application with:

  1. npm run dev

This command will use the dev.env.js value and the console log will display: http://localhost/api.

If you compile the application with:

  1. npm run build

This command will use the prod.env.js value and generate the application in the dist directory. Navigate into this directory and verify that the process.env.ROOT_API value uses http://www.example.com/api instead of http://localhost/api.

You can work with different variables for each different environment, using the ready-made configuration that the webpack template provides. If you use another template, make sure you find an equivalent feature or use a library like dotenv to manage your environment variables.

Conclusion

In this article, you learned how to use environment variables in projects built with Vue CLI 3+ and 2.

For current and future projects, it is recommended that you use @vue/cli moving forward as vue-cli has been deprecated.

If you’d like to learn more about Vue.js, check out our Vue.js topic page for exercises and programming projects.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Daniel Schmitz

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.