How to auth the API with API key and API token storing in .env

800 Views Asked by At

I write a nodejs program to call data form API, it is working if I hard code the API key and token.

Hard code the API key and token is working:

let username = "userid"; //--API_USERNAME
let token = "hfdhdfgfdhgs24" //API TOKEN;
let auth = btoa(`${username}:${token}`);

I store the key and token into .env file , however cannot get the data when calling the API.

It seems cannot read the value from the .env file, would anyone can help?

//.env file
API_USERNAME=userid


//.js code
import dotenv from "dotenv"
dotenv.config();
`var myHeaders = new Headers();
let token = "hfdhdfgfdhgs24" //API TOKEN;

let auth = btoa(`${process.env.API_USERNAME}:${token}`);
1

There are 1 best solutions below

2
ghybs On

process.env gives you access to environment variables, i.e. what is exposed to the currently running process.

On Unix-like OS, you can do for example:

export API_USERNAME=myUserName && node ./myScript.js

The .env file is not automatically read by Node. You can use dotenv library to do so: it will look for such file, and inject it into process.env for you:

require('dotenv').config();

let username = process.env.API_USERNAME