How to Easily Hide Your API Key In NodeJS ?

Nafis Ahmad
2 min readFeb 3, 2023

--

I received a warning from my API provider after I finished my Node.js project and pushed it to GitHub. The notification informed me of the potential risks associated with uploading my API key along with the project files to the online platform.

To address the issue, I conducted research on how to securely hide API keys while still ensuring that the project functions properly.

Here are the steps you need to follow :

  1. Create a new file in the directory and name it “.env”
  2. Inside of your “.env” file, put in your api-key with any variable in CAPS.
var API_KEY = apiapiapiapiapi;

3. Now go to your ‘app.js’ file or wherever you need the key, and require the ‘.env’ file

const dotenv = require('dotenv').config();

4. You can now use the key in this file by calling

process.env.API_KEY

5. To finally hide the key in the “.env” from gihub, you need to create another file and name “.gitignore” and inside the “.gitignore” file write the file name you don’t want to upload, in our case write “.env ” in the .gitignore file (without the quotes) and push the code to github.

6. This will work locally, and if your are going to host the app on a platform such as netlify, you need to give in the api key in the settings page.

Thanks for reading. : )

--

--

Nafis Ahmad

Exploring Data Science | Full Stack Development | Android Development | Kaggle Contributor | Content Writer at Medium | Computer Science Engineer | Learner