Back to Courses

World's Best MERN Stack Course

#8: Securing Your Private Data with Dotenv in our Backend App | MERN Tutorial in Hindi

Welcome, 🌟 Elevate the security of your Node.js app with our latest tutorial! πŸ›‘οΈ Join us as we guide you through the seamless integration of Dotenv, a powerful package that safeguards your sensitive data.

server.js

Add require("dotenv").config() at the top of server.js

require("dotenv").config();

const express = require("express");
const app = express();
const router = require("./routes/auth-route");
const connectDb = require("./utils/db");

// Mount the Router: To use the router in your main Express app, you can "mount" it at a specific URL prefix
app.use("/api/auth", router);

const PORT = 5000;

connectDb().then(() => {
  app.listen(PORT, () => {
    console.log(`server is running at port: ${PORT}`);
  });
});

create .env file

MONGODB_URI=<your-mongodb-uri-here>

db.js

const mongoose = require("mongoose");

// const URI = "mongodb://127.0.0.1:27017/mern_admin_panel";
const URI = process.env.MONGODB_URI;
console.log(URI);

const connectDb = async () => {
  try {
    await mongoose.connect(URI);
    console.log("connection successful to DB");
  } catch (error) {
    console.error("database connection fail");
    process.exit(0);
  }
};

module.exports = connectDb;