DEV Community

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

Posted on

3 1 1 1 1

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 🌐

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay