Node - Hide API Key


2 min read

Hiding An API Key

  • Add .env to .gitignore

  • Install dotenv module: npm install dotenv --save-dev

  • Install dotenv webpack: npm install dotenv-webpack --save-dev

  • Add require(‘dotenv').config() before declaring the class

  • Add the following to webpack.config.js:

1// add to the top
2const Dotenv = require('dotenv-webpack');
3
4// ---
5
6node: {
7 fs: 'empty'
8},
9plugins: [
10 new Dotenv()
11]

Adding An API Key

  • Create .env and add the following in it: API_KEY=_insert api key here_

  • Where needed, replace API key with process.env.API_KEY

  • Restart npm run watch


If The .env File Is Already Committed:

  • Commit any code changes

  • Run git rm --cached .env

  • Run git add . and git commit -m "_insert message here_"

Previous post:
Webpack - Cannot Resolve ‘Fs’ In [Path]
Next post:
Node - Fetch Is Not Defined

Discussion