๐Ÿš€ Node.js Backend : Pro Beginner Notes

Want to build a clean, maintainable, and secure backend with Node.js, Express, MongoDB, and best practices? This guide takes you step-by-step โ€” from setup to real-world essentials like CORS, .env configs, routes, and password resets.


๐Ÿ“š Table of Contents

  1. Getting Started
  2. require vs import โ€” Which One?
  3. Managing Config with dotenv
  4. Express Setup
  5. Auto Reload with Nodemon
  6. Handling CORS the Right Way
  7. Handling JSON and Form Data
  8. MongoDB Setup with Mongoose
  9. Secure Password Reset Flow
  10. Creating a User Model
  11. API Structure: Routes, Controllers, Layers
  12. Beginner Doubts Answered
  13. Mini Project Ideas
  14. Final Thoughts

1. Getting Started

Initialize Your Project

npm init -y

Install Dependencies

npm i express dotenv cors mongoose
npm i -D nodemon

Enable ES Modules

In your package.json, add:

"type": "module"

2. require vs import

SyntaxTypeWhen to Use
require()CommonJSOlder Node.js projects
importES ModulesModern ES6+ projects

๐Ÿง  Best Practice: Stick to one module system per project for consistency.


3. Managing Config with dotenv

Create a .env file:

PORT=4000
MONGO_URL=mongodb+srv://username:password@cluster.mongodb.net/myDB

๐Ÿ”’ Add .env to .gitignore โ€” never expose secrets in version control.

Enable environment variables:

import dotenv from 'dotenv';
dotenv.config();

Based on The Twelve-Factor App methodology โ€” config should live outside code.


4. Express Setup

import express from 'express';

const app = express();
const port = process.env.PORT || 4000;

app.get('/', (req, res) => {
  res.send('Hello from backend!');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

5. Auto Reload with Nodemon

Install Nodemon

npm i -D nodemon

Add to package.json

"scripts": {
  "dev": "nodemon index.js"
}

Run the App

npm run dev

6. Handling CORS the Right Way

CORS (Cross-Origin Resource Sharing) lets your frontend talk securely to your backend.

Install and Configure

npm i cors
import cors from 'cors';

app.use(cors({
  origin: 'http://localhost:3000',
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE']
}));

โœ… Allow only trusted domains.


7. Handling JSON and Form Data

Add middlewares:

app.use(express.json()); // JSON data
app.use(express.urlencoded({ extended: true })); // Form data

8. MongoDB Setup with Mongoose

Install

npm i mongoose

Create DB Utility โ€” utils/db.js

import mongoose from 'mongoose';
import dotenv from 'dotenv';

dotenv.config();

const connectDB = () => {
  mongoose.connect(process.env.MONGO_URL)
    .then(() => console.log("โœ… MongoDB connected"))
    .catch(() => console.error("โŒ DB connection failed"));
};

export default connectDB;

Use in index.js

import connectDB from './utils/db.js';
connectDB();

โš ๏ธ Encode special characters in MongoDB URI (e.g., @ โ†’ %40)


9. Secure Password Reset Flow

Step-by-Step

  1. Request Token

    • User submits email
    • Backend creates token and expiry
    • Send via email
  2. Verify Token

    • Check existence & expiry
  3. Submit New Password

    • Validate token
    • Hash password using bcrypt
    • Save to DB

๐Ÿ›ก๏ธ Security Tips

  • Hash the token before storing in DB
  • Expire tokens in 15โ€“60 min
  • Rate-limit reset requests
  • Never reveal if email exists

10. Creating a User Model

// models/User.model.js
import mongoose from 'mongoose';

const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  password: String,
  role: { type: String, enum: ['user', 'admin'], default: 'user' },
  isVerified: { type: Boolean, default: false },
  verificationToken: String,
  resetPasswordToken: String,
  resetPasswordExpires: Date
}, { timestamps: true });

const User = mongoose.model('User', userSchema);
export default User;

๐Ÿ’ก Financial data? Store in lowest denomination (e.g., paise, not rupees)


11. API Structure: Routes, Controllers, Layers

// controllers/user.controller.js
const registerUser = async (req, res) => {
  res.send("User registered successfully");
};

export { registerUser };

Routes

// routes/user.routes.js
import express from 'express';
import { registerUser } from '../controllers/user.controller.js';

const router = express.Router();
router.get('/register', registerUser);

export default router;

Use in Entry File

import userRoutes from './routes/user.routes.js';

app.use('/api/v1/users', userRoutes);

Now visiting /api/v1/users/register hits your controller!


12. Beginner Doubts Answered

Q: app.json() vs express.json()?\ A: express.json() is the correct middleware โ€” app.json() doesn't exist.

Q: What if I have double slashes in a route?\ A: /api//register = /api/register. But avoid them.

Q: Do I need to return res.send()?\ A: Not necessarily โ€” it's sufficient to just call res.send().

Q: How to share .env securely?\ A:

  • Share via WhatsApp or password managers
  • Add a .env.sample
  • Use Infisical for secrets management

13. Mini Project Ideas

Controller

Pick one and go deep!

  • LMS โ€” Learning Management System
  • CMS โ€” Content Management System
  • HMS โ€” Hospital Management System
  • BMS โ€” Billing Management System

Build one full-stack app well instead of five half-done ones.


14. Final Thoughts

โœ… Keep code layered: routes โ†’ controllers โ†’ services\ โœ… Use .env for secrets\ โœ… Use nodemon for development\ โœ… Understand why middleware, CORS, .env, and tokens matter\ โœ… Write secure, scalable backend code

๐Ÿ’ช "Zimmedariyon wale kandho ko thakna allow nahi hota."\ Keep shipping. Refine later. You're growing every day ๐Ÿš€


๐Ÿ’ฌ Like this guide?

Follow me for more dev tutorials on:

  • Node.js
  • MongoDB
  • REST APIs
  • Authentication
  • Developer Career Tips
10
Subscribe to my newsletter

Read articles from shaikh sirajuddin directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

shaikh sirajuddin
shaikh sirajuddin