Hide Your API Keys

Tosh
2 min readDec 27, 2020

--

How to secure you API keys

During my BootCamp, while working on a project with a third party API, I had to push my project on Github and I knew I should not leave my API key public so I put my repo private … Yes definitely not the best way specially when the project will but added on my resume to get a job but I was to afraid to get charged thousand of dollars cause of a thief.

Hide your Keys in the Frond End (React)

1-run dotven and Create a file called .env in the root of your project’s directory.

The .env has to be in the ROOT

npm install dotenv — save/ project
/.env <=== here
/public
/src
/.gitignore
/package-lock.json
/package.json

2. Inside the .env file


REACT_APP_KEY=secret-key

Keep in mind variable needs to start with REACT_APP_ for it to work.

3. Add the .env file to your .gitignore file.

// .gitignore

# keys
.env <=== here

# dependencies
/node_modules
/.pnp
.pnp.js

Save and run git status to make sure that .env is not on the list of changes to be committed.

4. Access the API key

in your app

// src/App.jsimport React, { Component } from 'react';
import'./App.css';
require('dotenv').config() '
console.log(process.env.REACT_APP_KEY)

Console.log to make sure you get your key back.

reference : https://create-react-app.dev/docs/adding-custom-environment-variables/

--

--

Tosh
Tosh

Written by Tosh

Software Engineering student @Flatiron

No responses yet