How to Remove Accidentally Pushed .env File in Git History

ยท

2 min read

Cover Image for How to Remove Accidentally Pushed .env File in Git History

Recently I was implementing Google Analytics to my Next.js portfolio website. I saved my Google measurement ID in a .env file. After all the work, I pushed my .env file directly to the online repository without adding it to .gitignore.

It was a whole nightmare when I received a mail something like this below from the GitGuardian.

a mail receive from gitguardian by informing that you pushed .env file.

However, it's not necessary to hide the Google Analytics ID because anyone can see it by inspecting the webpage.

I felt so frustrated when I accidentally pushed .env to Github.

But don't worry in this article I've shared a great git feature that will help us to remove specific files from the commit history.

Environment variables play a crucial role in any software application. The .env files are designed to store environmental variables in key-value pairs that hold various sensitive configuration settings for an application.

Accidentally pushing a .env file can lead to a serious security threat to our application. It can lead to unauthorized API uses, access to databases, and more. So it's very necessary to keep the .env file confidential.

Solution

I'm assuming that you have already pushed the .env file to the remote repository without saving it to the .gitignore file.

Save The .env File To .gitignore File First

.env

To Remove .env File From Git History Run This Command

git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch .env" HEAD

Push The Filtered Changes

git push --force

Conclusion

In this way, you can completely remove the .env file from the git history. Although It's removed I will highly recommend you to check .gitignore even before making any git commit to ensure that the .env file is added to it. Thanks for reading this article till the end. Subscribe to my newsletter & Let's Connect!