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?
1. Environment Variables:
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`.
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_string
```
And then, reference it in your code by using `process.env.MONGO_URI`.
2. Protect Your Code with .gitignore:
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.
Setting Up .gitignore:
- Add a `.gitignore` file in the root of your project
- Inside the `.gitignore` file, add the following line to prevent your `.env` file from being pushed to GitHub:
```
.env
```
3. GitHub Secrets for Production:
When 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.