From Mistake to Best Practice: Securing API Keys in React Projects


I still remember the first time GitHub alerted me about a leaked secret.
I had just pushed a new React app update when I saw a bold warning in my GitHub repo:
🔴 "Secret scanning alert: Public leak — Google API Key"
At first, I was confused. Then nervous.
Then I saw the file GitHub flagged:src/Data.js:1
Yep , I had accidentally left my actual API key sitting right there in the code. And it was now live in a public repository.
🚨 What Is Secret Scanning?
GitHub automatically scans public repos for known patterns of sensitive data like API keys, tokens, and credentials.
It even shows you the exact file and line where the secret was found.
Honestly, I’m grateful it caught mine before someone else did.
🔐 The Fix — Using .env
Files in React
To prevent this from ever happening again, I took these steps:
Created a
.env
file in my project root:REACT_APP_API_KEY=your-real-key-here
Replaced the hardcoded string in my code:
const API_KEY = process.env.REACT_APP_API_KEY;
Added
.env
to.gitignore
so it never gets pushed:.env
Revoked the exposed API key and generated a fresh one
Rebuilt and redeployed the app securely this time.
💡 Key Takeaways
Never hardcode sensitive data.
Use
.env
files, and make sure they're in.gitignore
.Let GitHub’s secret scanning work for you, not against you.
Assume every line you write might one day be in public.
Have you ever had a similar moment where GitHub saved you from a mistake?
Let’s talk 👇
Subscribe to my newsletter
Read articles from Ganiyatu Sanuusi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Ganiyatu Sanuusi
Ganiyatu Sanuusi
Tech with Ghaniya is a space where I share real-world solutions to tech problems I’ve faced — and go further by offering practical tips, tutorials, and tools to help others learn, build, and grow. From software development to everyday tech challenges, if it helps someone level up, it’s worth writing about