Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load environment variables into vue.js

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!

like image 927
Trung Tran Avatar asked Sep 10 '16 12:09

Trung Tran


2 Answers

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.

like image 115
Paul Wenzel Avatar answered Oct 21 '22 16:10

Paul Wenzel


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

like image 31
Ayotunde Olubiyo Avatar answered Oct 21 '22 14:10

Ayotunde Olubiyo