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 ๐ŸŒ

Image of Timescale

๐Ÿš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsโ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post โ†’

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series ๐Ÿ“บ

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series ๐Ÿ‘€

Watch the Youtube series