In this guide, you'll learn how to securely manage your MongoDB connection string using the .env
file in an Express.js backend project. Let's dive in! π
Step 1: Install dotenv
π¦
First, install the dotenv
package to read environment variables from your .env
file:
npm install dotenv
Step 2: Create a .env
File π οΈ
Create a .env
file in the root of your project and store your MongoDB URI in it. For example:
MONGO_URI=mongodb+srv://<username>:<password>@cluster0.mongodb.net/<database>?retryWrites=true&w=majority
Replace <username>
, <password>
, and <database>
with your actual database credentials.
Step 3: Load Environment Variables π
In your main project file (e.g., index.js
or app.js
), import and configure dotenv
at the very top:
import dotenv from 'dotenv';
dotenv.config();
This ensures that all variables in your .env
file are loaded into process.env
.
Step 4: Use the Environment Variable π‘οΈ
Now, use the environment variable MONGO_URI
in your MongoDB connection:
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Error connecting to MongoDB:', err));
Step 5: Add .env
to .gitignore
π«
To prevent exposing sensitive data (like your MongoDB URI) in version control, add .env
to your .gitignore
file:
.env
Security Tip π
Never hardcode sensitive information like usernames, passwords, or database URLs directly in your code. Always use environment variables for a secure and clean setup.
Full Example: index.js
π
Hereβs a complete example of an Express.js app connected to MongoDB using the .env
file:
import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import UserRoute from './routes/UserRoute.js';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on('error', (error) => console.log(error));
db.once('open', () => console.log('Database Connected'));
app.use(cors());
app.use(express.json());
// Routes
app.use(UserRoute);
app.listen(5080, () => console.log('Server is running'));
Ready to Go! π
If youβve followed these steps correctly, your project should now be securely connected to MongoDB using environment variables. Happy coding! π
Top comments (0)