0

I have a folder called /api in the root of the application where I access an endpoint from the Frontend /src to send an email. I'd like to call an environment variable here but it is not working with process.env.VUE_APP_APIKEY. What is the right way to do this?

This is the endpoint I am calling the env variable from. This is using express:

let endpoint = function(app) {
  app.post('/send-mail', function(req, res) {
    sgMail.setApiKey(process.env.VUE_APP_APIKEY);
    sgMail
      .send(req.body)
      .then(() => {
        // do something
      })
      .catch(error => {
        // do something
      });

    return res.send(req.body);
  });
};

That sgMail is sendgrid, hence the API key I'm calling is for that service.

3
  • Are you getting any errors? Is VUE_APP_APIKEY defined as an environment variable? Commented Jun 18, 2018 at 13:31
  • No, the env variable works in the frontend correctly, but since /api is not inside /src then I think Vue env variables aren't available. Commented Jun 18, 2018 at 15:41
  • Yes that is correct. Your Vue app is running on an entirely different process than your Express application. So you need to define them in both places. Commented Jun 18, 2018 at 16:12

1 Answer 1

1

You have to define your env vars somewhere. process.env returns an object containing all the user environment.

You can define your env vars when you run node, by doing something like this:

MY_VAR=my_value node server.js

An easy way to manage your environment variables with Node.js is to use dotenv.

Create a .env file at the root of your repo or anywhere (depending on your needs) and add your env vars like this:

VUE_APP_APIKEY=[API KEY VALUE]

Then add the following line of code into your server.js or index.js (where your Express is instantiated):

require('dotenv').config()

Hence you should be able to use your env vars by using your existing code: process.env.VUE_APP_APIKEY.

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

5 Comments

Thanks, do you know of anyway to do this natively with Vue?
Based on the name of your env var, you're using Vue CLI, right? In that case, you can add your env vars within a .env file (without using dotenv) and prefix all of them by VUE_APP_.
Thanks but doesn't work, I think it needs to be inside /src folder for it to work.
Thanks, fyi just had to use env package and created a file and it's being read globaly. So I guess I'm stuck with Vue env variables for front end stuff, and a regular .env file for API stuff.
Yes, your .env file must be into the root folder of your frontend code, /src in your case. Cool if everything works ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.