Reputation: 4441
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.
Upvotes: 0
Views: 1750
Reputation: 1121
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
.
Upvotes: 1