Environment Variables in MERN

Environment Variables are dynamic-named values that can affect the way running processes will behave on a computer. In a MERN stack, they are used to store sensitive information like MongoDB URIs, API Secret Keys, and Port numbers outside of the actual source code.

Environment Variables

1. Backend Setup (Node.js & Express)

On the backend, we use the dotenv package to load variables from a .env file into process.env.

// .env file
PORT=5000
MONGO_URI=mongodb+srv://user:pass@cluster.mongodb.net/

// server.js
require('dotenv').config();
const port = process.env.PORT || 5000;
mongoose.connect(process.env.MONGO_URI);
                

2. Frontend Setup (React)

If you are using Create React App, variables must start with REACT_APP_. If using Vite, they start with VITE_.

// .env file
REACT_APP_API_URL=http://localhost:5000/api

// App.js
const apiUrl = process.env.REACT_APP_API_URL;
                
Warning: Never store secret keys (like Stripe Secret Keys) in the frontend. Frontend variables are visible to anyone who inspects your website's code!

3. The .gitignore Rule

The most important step is to add your .env file to your .gitignore file. This ensures your secrets are never uploaded to GitHub.

# .gitignore
node_modules
.env
                

Knowledge Check

1. Which object is used to access variables in Node.js?
A) process.vars | B) process.env | C) system.env

2. In Create React App, what prefix is required for environment variables?
A) API_ | B) SECRET_ | C) REACT_APP_

3. Why do we add .env to .gitignore?
A) To make the app run faster | B) To prevent sensitive keys from leaking to GitHub | C) Because GitHub doesn't support .env files