Blog Post
Environment Variables and the Importance of .gitignore 🛡
When working with a full-stack application, it’s critical to protect your sensitive information! A key method to prevent malicious actors or bots from accessing private details—either via GitHub or browser inspection tools—is by using the .env file alongside the .gitignore file.
How Do These Files Work Together?
Environment Variables act as protective keys that store sensitive data, such as API keys or database credentials. A common package used to manage these is dotenv.
- Environment Variables:
Installing dotenv: npm install dotenv
If you’re using a framework like Next.js, it likely has built-in support for dotenv. But, if you’re using a more simple setup, you may need to install it manually. These variables allow you to protect confidential information by placing them in a .env file, away from the public eye.
Example: If you were using a MongoDB Atlas key that contains sensitive credentials, you can define it in your .env file like so:
MONGO_URI=your_secret_mongo_connection_stringAnd then, reference it in your code by using process.env.MONGO_URI.
To ensure your .env file isn’t accidentally pushed to a public repo, you can use a .gitignore file to omit it from being tracked by Git. This is a security measure to keep sensitive data safe from external exposure.
- Protect Your Code with .gitignore:
Setting Up .gitignore:
- Add a
.gitignorefile in the root of your project - Inside the
.gitignorefile, add the following line to prevent your.envfile from being pushed to GitHub:
.envWhen deploying to production, you may still need these sensitive variables. GitHub offers a feature called Secrets and variables under the repository’s Settings to securely store environment variables, ensuring your application functions properly without exposing sensitive data.
- GitHub Secrets for Production: