DEV Community

Cover image for Learn .env in Express.js for Beginners (Effortless Setup)
Joodi
Joodi

Posted on

Learn .env in Express.js for Beginners (Effortless Setup)

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! πŸš€

Image description

Step 1: Install dotenv πŸ“¦

First, install the dotenv package to read environment variables from your .env file:

npm install dotenv
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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'));
Enter fullscreen mode Exit fullscreen mode

Ready to Go! πŸŽ‰

If you’ve followed these steps correctly, your project should now be securely connected to MongoDB using environment variables. Happy coding! 😊

Let's Connect 🌐

Top comments (0)