32

I'm trying to add some environment variables into my vue app.

here is content of my .env file, which is placed on root(outside src):

VUE_APP_GOODREADS_KEY = my_key

and I added code for dot env on the top of my main.js

import Vue from 'vue'
import App from './App'
import VueResource from 'vue-resource'
import Vuetify from 'vuetify'

import dotenv from 'dotenv'

dotenv.config()

import { router } from './router'
import store from './store'

I want to use this variable within my store ./store/index.js

I tried to console.log environment variables within store but no luck:

console.log(process.env)

But all I'm getting is

NODE_ENV:"development"

Only related thread I found was Load environment variables into vue.js, but it only mentions how to use existing variables in the process.env. I want to add environment variables using dotenv. Why this code is not working?

Dani Vijay
  • 2,188
  • 2
  • 22
  • 37

3 Answers3

72

If your project was create by using Vue CLI 3, no need to use dotenv to get environment variables.

To get environment variables within .env file in your project:

  1. Placing the .env file in your project root.
  2. In the .env file, specifying environment variables with "VUE_APP_" prefix.

    VUE_APP_SOMEKEY=SOME_KEY_VALUE.

  3. Finally, you can access them with process.env.* in your application code.

    console.log(process.env.VUE_APP_SOMEKEY) // SOME_KEY_VALUE

Referance: Vue CLI 3 - Environment Variables and Modes

white
  • 808
  • 7
  • 4
7

When using Vue CLI 2, you have to use the dev.env.js and prod.env.js files located in the config folder.

Vue CLI 2 does not support the use of .env files, however Vue CLI 3 does.

// /config/prod.env.js
'use strict'
module.exports = {
  NODE_ENV: '"production"',
  SERVER_URI: "http://someremoteuri:3333/api/v1"
}
// /config/dev.env.js
'use strict'
module.exports = {
  NODE_ENV: '"development"',
  SERVER_URI: "http://localhost:3333/api/v1"
}
Nick Bolles
  • 439
  • 5
  • 14
PrestonDocks
  • 4,851
  • 9
  • 47
  • 82
  • 2
    Vue CLI 3 !== Vue Js 3, Vue CLI 3 generates Vue Js 2.x code, VueJS 3 is the next version of vue that's not out yet. – Nick Bolles Dec 09 '19 at 05:11
2

Try removing the spaces around the equal sign.

VUE_APP_GOODREADS_KEY=my_key

Also, try debugging like this:

const config = dotenv.config()
if(config.error){
  console.log('Could not load env file', config.error)
}

Reference: https://github.com/motdotla/dotenv#config

Tudor Ilisoi
  • 2,934
  • 23
  • 25
  • 2
    It seems I cant use it in the client side as it throws an error `fs not defined`. – Dani Vijay Jun 07 '18 at 12:04
  • 1
    Well, that is expected. How can a browser read an arbitrary file on your server? `fs` is a node builtin. However, you can setup a route which serves the config as a JSON string, so the browser can fetch and parse that – Tudor Ilisoi Jun 07 '18 at 13:16
  • Can you explain the set up a bit? I didn't get the method. – Dani Vijay Jun 08 '18 at 13:37