In this lab lesson, students will learn how to securely manage sensitive information, such as passwords and API keys, using environment variables in a Node.js application.
You will understand the importance of not hardcoding sensitive information in the source code and how to use `.env` files to manage these variables securely.
#### Prerequisites
- Basic understanding of Node.js and Express.
- Basic understanding of Git and GitHub.
#### Table of Contents
1. Introduction to Environment Variables
2. Setting Up the Project
3. Installing `dotenv` Package
4. Creating and Configuring `.env` File
5. Using Environment Variables in Code
6. Adding `.env` to `.gitignore`
7. Practical Exercise
8. Summary
---
### 1. Introduction to Environment Variables
Environment variables are used to store configuration settings and other data that your application needs to function. They are especially useful for sensitive information such as database passwords, API keys, and other secrets.
**Why use environment variables?**
- **Security**: Sensitive information is not hardcoded in the source code.
- **Flexibility**: Configuration can be easily changed without modifying the code.
- **Environment-specific settings**: Different settings for development, testing, and production environments.
### 2. Setting Up the Project
Create a new Node.js project.
1. **Initialize the project**:
```bash
mkdir secureEnvApp
cd secureEnvApp
npm init -y
```
2. **Install Express**:
```bash
npm install express
```
### 3. Installing `dotenv` Package
The `dotenv` package is used to load environment variables from a `.env` file into `process.env`.
1. **Install `dotenv`**:
```bash
npm install dotenv
```
### 4. Creating and Configuring `.env` File
1. **Create a `.env` file in the root directory**:
```bash
touch .env
```
2. **Add your environment variables to the `.env` file**:
```plaintext
PORT=3000
DB_URI=mongodb://localhost:27017/secureEnvApp
SECRET_KEY=mysecretkey
```
### 5. Using Environment Variables in Code
1. **Create `app.js`**:
```javascript
const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
// Load environment variables from .env file
dotenv.config();
const app = express();
const port = process.env.PORT || 3000;
const dbUri = process.env.DB_URI;
const secretKey = process.env.SECRET_KEY;
// Connect to MongoDB
mongoose.connect(dbUri, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Could not connect to MongoDB...', err));
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
```
### 6. Adding `.env` to `.gitignore`
To ensure that your `.env` file is not pushed to GitHub, add it to `.gitignore`.
1. **Create a `.gitignore` file in the root directory**:
```bash
touch .gitignore
```
2. **Add `.env` to `.gitignore`**:
```plaintext
node_modules/
.env
```
### 7. Practical Exercise
#### Task
1. **Set up the project**:
- Follow the steps above to create a new Node.js project.
- Install the necessary packages.
2. **Create and configure `.env` file**:
- Add environment variables to the `.env` file.
- Use these variables in your `app.js` file.
3. **Secure the `.env` file**:
- Add `.env` to `.gitignore`.
4. **Push the project to GitHub**:
- Initialize a new Git repository.
- Push the project to a GitHub repository.
- Verify that the `.env` file is not included in the repository.
#### Solution
1. **Initialize Git**:
```bash
git init
git add .
git commit -m "Initial commit"
```
2. **Create a new repository on GitHub**:
- Follow GitHub instructions to create a new repository.
3. **Push to GitHub**:
```bash
git remote add origin <repository-url>
git push -u origin master
```
4. **Verify `.env` file is not included**:
- Go to your GitHub repository and verify that the `.env` file is not present.
### 8. Summary
In this lab lesson, students learned how to use environment variables to securely manage sensitive information in a Node.js application. They created a `.env` file to store these variables and used the `dotenv` package to load them into their application. They also added the `.env` file to `.gitignore` to ensure it is not pushed to GitHub, preventing the exposure of sensitive information.
By following these practices, students can improve the security and flexibility of their Node.js applications.