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!

1

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You can only the environment variables after you close the dev server and restart, or do a new build~
I just restarted like @mintedsky suggested and it worked. npm run serve - thanks
Because of Vue CLI 3, future viewers might benefit from this post instead: stackoverflow.com/questions/50828904/…
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

2 Comments

when I do this, the value getting printed in console is 'SECRET' and not the value of SECRET set from express node.js
PLEASE, do not put actual secrests into the .env file, it will get exposed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.