9

I am building an app using node.js + vue.js and was wondering if anyone knows how I can load environment variables into my vue.js components? Right now I'm loading environment variables in my server side code using the dotenv package but it doesn't seem to work for vue.js..

Thanks in advance!

Trung Tran
  • 13,141
  • 42
  • 113
  • 200
  • 1
    You can use [DefinePlugin](https://webpack.js.org/plugins/define-plugin/), check this [answer](http://stackoverflow.com/a/43508655/4305494). You can also use DefinePlugin along with [Configuration types](https://webpack.js.org/configuration/configuration-types/) like in this other [answer](http://stackoverflow.com/a/41900834/4305494). – Ricky Ruiz Apr 20 '17 at 15:12

2 Answers2

6

You can expose environment variables from NodeJS like this:

console.log(process.env.EXAMPLE_VARIABLE);

More details on process.env: https://nodejs.org/api/process.html#process_process_env

To expose your environment variables to the client-side in Vue (or any Javascript framework for that matter), you could render a JSON response from NodeJS that is ingested via an AJAX call.

Paul Wenzel
  • 1,886
  • 2
  • 15
  • 15
  • 1
    You can only the environment variables after you close the dev server and restart, or do a new build~ – mintedsky Nov 21 '17 at 15:56
  • I just restarted like @mintedsky suggested and it worked. `npm run serve` - thanks – Gel Feb 15 '21 at 06:39
  • Because of Vue CLI 3, future viewers might benefit from this post instead: https://stackoverflow.com/questions/50828904/using-environment-variables-with-vue-js – Dan der Mensch Jul 28 '21 at 14:26
3

Using Vue Cli 3, You can load your environment variables like this

  1. Create a .env file in the root directory of your application.
  2. In the .env file, prefix your environment variables with VUE_APP_.

    Example: VUE_APP_SECRET=SECRET.

  3. Now you can access them with process.env.THE_NAME_OF_THE_VARIABLE in your application code.

    Example: console.log(process.env.VUE_APP_SECRET) // SECRET

You can read more here

Prasad N
  • 543
  • 4
  • 10
  • 22
  • when I do this, the value getting printed in console is 'SECRET' and not the value of SECRET set from express node.js – VVictor Dec 01 '20 at 18:07
  • 1
    PLEASE, do not put actual secrests into the .env file, it will get exposed. – Marcel Nov 27 '21 at 21:29