Environment Variables in MERN Projects
Environment variables are a crucial part of MERN (MongoDB, Express, React, Node.js) projects. They help manage sensitive information and configuration settings without hardcoding them into your application. Here's a breakdown of how to work with environment variables in a MERN stack project:
๐ What Are Environment Variables?
Environment variables store values outside your source code—like database URLs, API keys, or secret tokens—making your app more secure and easier to configure.
๐ Folder Structure Overview
bash
Copy
Edit
/client # React frontend
/server # Node.js backend (Express)
.env # Root environment file (optional, mainly for shared vars)
.env.local # Git-ignored local env file (optional)
๐ฅ️ Backend (Node.js + Express)
✅ Setup
Install dotenv:
bash
Copy
Edit
npm install dotenv
Create a .env file in the /server folder:
env
Copy
Edit
PORT=5000
MONGO_URI=mongodb+srv://user:password@cluster.mongodb.net/dbname
JWT_SECRET=your_jwt_secret
Load environment variables in your app:
js
Copy
Edit
// server/index.js or server/app.js
require('dotenv').config();
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
const mongoURI = process.env.MONGO_URI;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
๐ Frontend (React)
✅ Setup
Create a .env file in the /client folder:
env
Copy
Edit
REACT_APP_API_URL=http://localhost:5000
Access it in React code:
js
Copy
Edit
const apiUrl = process.env.REACT_APP_API_URL;
fetch(`${apiUrl}/api/data`)
.then(res => res.json())
.then(data => console.log(data));
⚠️ Note: React environment variable names must start with REACT_APP_
Restart the React server after changing .env files.
๐ Best Practices
Do not commit .env files to version control:
Add them to .gitignore:
bash
Copy
Edit
# Ignore env files
*.env
Use .env.example to share the required variables (without actual values).
✅ Example .env.example
env
Copy
Edit
PORT=
MONGO_URI=
JWT_SECRET=
REACT_APP_API_URL=
Would you like a full working example or help integrating environment variables into your specific MERN project?
Learn MERN Stack Course in Hyderabad
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment