How put API key on env files in a Node.js app?

Viewed 1421

this is my first time im trying to handle " Web api ", so i took this project to get many call but after it running well, when i try to click to "search" it dosent work, I guess the problem arises from api call because chrome inspector show me that : enter image description here I was able to understand on the different forums, for handling apis call with Node.js that must be encapsulated API calls behind "Environment variable".

That the config.js file enter image description here

When i try to put on the terminal export env.API_KEY='000000000000000' it made me :

export: not valid in this context: env.API_KEY

I hope you can point me in the right direction, I very tried everything, to run it that.

1 Answers

I personally like to use a npm package called dotenv:

You can install it by running npm i dotenv within your api directory.

Have a file called .env within your api directory which contains all of your environment variables:

APP_ID="000000000000000"
API_KEY="000000000000000"

Then change config.js to load all environment variable files when it is executed by including require('dotenv').config():

require('dotenv').config()
module.exports = {
  APP_ID: process.env.APP_ID,
  API_KEY: process.env.API_KEY,
  BASE_URL: 'https://api.adzuna.com/v1/api/jobs',
  BASE_PARAMS: 'search/1?&results_per_page=20&content-type=application/json',
};

Note: you will also want to add .env to your .gitingore so that your sensitive API keys aren't included in your git repository

Related