Skip to content

Latest commit

 

History

History
1483 lines (1081 loc) · 21.6 KB

File metadata and controls

1483 lines (1081 loc) · 21.6 KB

Backend Development Journey

This README is a backend-only roadmap for becoming strong in Node.js, Express.js, REST APIs, databases, authentication, deployment, and real-world backend project structure.

Goal:

Learn backend fundamentals deeply, build APIs, connect databases, add authentication, deploy projects, and become capable of building production-style backend systems.


Table of Contents

  1. Backend Learning Path
  2. Phase 1: Node.js Basics
  3. Phase 2: npm and package.json
  4. Phase 3: Express.js Basics
  5. Phase 4: REST API Fundamentals
  6. Phase 5: Request Data
  7. Phase 6: Request Validation
  8. Phase 7: Middleware
  9. Phase 8: Routes and Controllers
  10. Phase 9: Error Handling
  11. Phase 10: Database
  12. Phase 11: MongoDB and Mongoose
  13. Phase 12: PostgreSQL and Prisma
  14. Phase 13: Authentication and Authorization
  15. Phase 14: Cookies, CORS, and Security
  16. Phase 15: File Upload
  17. Phase 16: Real-Time Backend
  18. Phase 17: Deployment
  19. Phase 18: Advanced Backend Concepts
  20. Backend Project Order
  21. 10-Day Backend Starter Plan
  22. Backend Checklist

Backend Learning Path

Recommended order:

Node.js basics
-> npm/package.json
-> Express.js
-> REST APIs
-> request/response
-> validation
-> middleware
-> routes/controllers
-> error handling
-> database
-> authentication
-> cookies/CORS/security
-> file upload
-> deployment
-> advanced backend concepts

Phase 1: Node.js Basics

Node.js lets you run JavaScript outside the browser.

Learn

  • What is Node.js?
  • Running JavaScript using Node
  • node command
  • CommonJS vs ES Modules
  • Built-in Node modules
  • Environment variables

Run JS with Node

Create index.js:

console.log("Hello from Node.js");

Run:

node index.js

Built-in Node Modules

You should know these at a basic level:

fs       -> file system
path     -> file/folder paths
http     -> create basic server
crypto   -> hashing/random values

Example: fs module

import fs from "fs";

fs.writeFileSync("notes.txt", "Learning backend development");

const data = fs.readFileSync("notes.txt", "utf-8");

console.log(data);

Example: Environment Variables

Install dotenv later:

npm install dotenv

Example:

import dotenv from "dotenv";

dotenv.config();

console.log(process.env.PORT);

Phase 2: npm and package.json

npm is used to install packages.

Commands

npm init -y
npm install express
npm install -D nodemon
npm uninstall package-name

package.json

Example:

{
  "name": "backend-project",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "nodemon src/index.js",
    "start": "node src/index.js"
  },
  "dependencies": {
    "express": "^4.18.0"
  },
  "devDependencies": {
    "nodemon": "^3.0.0"
  }
}

Important Fields

scripts       -> commands you can run
dependencies  -> packages needed in production
devDependencies -> packages needed only during development
type: module  -> allows import/export syntax

Phase 3: Express.js Basics

Express is a framework for building backend APIs.

Install Express

npm install express

Basic Server

import express from "express";

const app = express();

app.use(express.json());

app.get("/", (req, res) => {
  res.json({ message: "Backend is running" });
});

app.listen(3000, () => {
  console.log("Server running on port 3000");
});

Important Express Concepts

app.get()      -> handle GET request
app.post()     -> handle POST request
app.patch()    -> handle PATCH request
app.delete()   -> handle DELETE request
req            -> request object
res            -> response object
app.use()      -> use middleware

Phase 4: REST API Fundamentals

REST APIs use HTTP methods to perform CRUD operations.

HTTP Methods

GET     -> read data
POST    -> create data
PUT     -> replace full data
PATCH   -> update partial data
DELETE  -> delete data

Common API Structure

GET     /api/users        -> get all users
GET     /api/users/:id    -> get one user
POST    /api/users        -> create user
PATCH   /api/users/:id    -> update user
DELETE  /api/users/:id    -> delete user

Status Codes

200 OK
201 Created
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
500 Internal Server Error

Phase 5: Request Data

Backend receives data in different ways.

1. Route Params

Used for dynamic route values.

app.get("/api/users/:id", (req, res) => {
  const { id } = req.params;

  res.json({ id });
});

Example URL:

/api/users/123

2. Query Params

Used for filtering, searching, sorting, pagination.

app.get("/api/products", (req, res) => {
  const { category, sort } = req.query;

  res.json({ category, sort });
});

Example URL:

/api/products?category=shoes&sort=price

3. Request Body

Used when client sends data.

app.use(express.json());

app.post("/api/users", (req, res) => {
  const { name, email } = req.body;

  res.json({ name, email });
});

Phase 6: Request Validation

Always validate incoming data.

What to Validate

  • required fields
  • empty strings
  • email format
  • password length
  • invalid IDs
  • wrong data types
  • duplicate values

Manual Validation Example

app.post("/api/users", (req, res) => {
  const { name, email } = req.body;

  if (!name || name.trim() === "") {
    return res.status(400).json({ message: "Name is required" });
  }

  if (!email || !email.includes("@")) {
    return res.status(400).json({ message: "Valid email is required" });
  }

  res.status(201).json({ message: "User created" });
});

Validation Libraries to Learn Later

zod
joi
express-validator

Phase 7: Middleware

Middleware is a function that runs between request and response.

Middleware Structure

function middleware(req, res, next) {
  // do something
  next();
}

Logger Middleware

function logger(req, res, next) {
  console.log(`${req.method} ${req.url}`);
  next();
}

app.use(logger);

Route-Specific Middleware

function protectRoute(req, res, next) {
  const token = req.headers.authorization;

  if (!token) {
    return res.status(401).json({ message: "Unauthorized" });
  }

  next();
}

app.get("/api/profile", protectRoute, (req, res) => {
  res.json({ message: "Profile data" });
});

Types of Middleware

built-in middleware
custom middleware
third-party middleware
auth middleware
error middleware
logging middleware

Phase 8: Routes and Controllers

Do not keep everything in one file.

Recommended Folder Structure

src/
  index.js
  routes/
    user.routes.js
    todo.routes.js
  controllers/
    user.controller.js
    todo.controller.js
  middleware/
    auth.middleware.js
    error.middleware.js
  models/
    user.model.js
    todo.model.js
  lib/
    db.js
  utils/
    generateToken.js

Route File

routes/user.routes.js

import express from "express";
import { getUsers, createUser } from "../controllers/user.controller.js";

const router = express.Router();

router.get("/", getUsers);
router.post("/", createUser);

export default router;

Controller File

controllers/user.controller.js

export const getUsers = (req, res) => {
  res.json({ message: "Get users" });
};

export const createUser = (req, res) => {
  res.status(201).json({ message: "Create user" });
};

Main File

src/index.js

import express from "express";
import userRoutes from "./routes/user.routes.js";

const app = express();

app.use(express.json());

app.use("/api/users", userRoutes);

app.listen(3000, () => {
  console.log("Server running on port 3000");
});

Phase 9: Error Handling

Backend code can fail because of bad input, database errors, invalid IDs, network issues, etc.

Basic try/catch

app.get("/api/users/:id", async (req, res) => {
  try {
    const user = await findUser(req.params.id);

    if (!user) {
      return res.status(404).json({ message: "User not found" });
    }

    res.status(200).json(user);
  } catch (error) {
    res.status(500).json({ message: "Internal server error" });
  }
});

Global Error Middleware

function errorHandler(error, req, res, next) {
  console.log(error);

  res.status(500).json({
    message: "Internal server error",
  });
}

app.use(errorHandler);

Common Error Response Pattern

return res.status(400).json({
  success: false,
  message: "Invalid input",
});

Good API Response Pattern

res.status(200).json({
  success: true,
  data: users,
});

Phase 10: Database

You should learn both:

MongoDB + Mongoose
PostgreSQL + Prisma

Suggested order:

MongoDB + Mongoose first
PostgreSQL + Prisma after that

Why?

MongoDB is easier to start with for CRUD APIs.
PostgreSQL + Prisma is very useful for serious full-stack apps.

Phase 11: MongoDB and Mongoose

Learn

  • MongoDB Atlas or local MongoDB
  • Mongoose connection
  • Schema
  • Model
  • CRUD operations
  • ObjectId
  • Relationships
  • Timestamps

Install

npm install mongoose

Connect Database

lib/db.js

import mongoose from "mongoose";

export const connectDB = async () => {
  try {
    await mongoose.connect(process.env.MONGO_URI);
    console.log("MongoDB connected");
  } catch (error) {
    console.log("MongoDB connection error:", error.message);
    process.exit(1);
  }
};

Model Example

models/user.model.js

import mongoose from "mongoose";

const userSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
    },

    email: {
      type: String,
      required: true,
      unique: true,
    },

    password: {
      type: String,
      required: true,
    },
  },
  { timestamps: true }
);

const User = mongoose.model("User", userSchema);

export default User;

CRUD Examples

Create

const user = await User.create({
  name,
  email,
  password,
});

Find All

const users = await User.find();

Find One

const user = await User.findById(id);

Update

const updatedUser = await User.findByIdAndUpdate(
  id,
  { name },
  { new: true }
);

Delete

await User.findByIdAndDelete(id);

Phase 12: PostgreSQL and Prisma

Learn

  • SQL basics
  • tables
  • rows
  • columns
  • primary key
  • foreign key
  • relations
  • Prisma schema
  • migrations
  • Prisma Client

Install Prisma

npm install prisma @prisma/client
npx prisma init

Example Prisma Schema

model User {
  id        String   @id @default(uuid())
  name      String
  email     String   @unique
  password  String
  posts     Post[]
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

model Post {
  id        String   @id @default(uuid())
  title     String
  content   String
  authorId  String
  author    User     @relation(fields: [authorId], references: [id])
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

Prisma Commands

npx prisma migrate dev
npx prisma generate
npx prisma studio

Prisma Client Example

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

const users = await prisma.user.findMany();

CRUD Examples

await prisma.user.create({
  data: {
    name,
    email,
    password,
  },
});

await prisma.user.findMany();

await prisma.user.findUnique({
  where: { id },
});

await prisma.user.update({
  where: { id },
  data: { name },
});

await prisma.user.delete({
  where: { id },
});

Phase 13: Authentication and Authorization

Authentication means:

Who are you?

Authorization means:

What are you allowed to access?

Learn

  • signup
  • login
  • password hashing
  • JWT
  • cookies
  • protected routes
  • logout
  • auth middleware
  • role-based access

Install Packages

npm install bcryptjs jsonwebtoken cookie-parser cors

Signup Flow

Receive name/email/password
-> validate input
-> check if user already exists
-> hash password
-> save user
-> generate token
-> send response

Login Flow

Receive email/password
-> validate input
-> find user by email
-> compare password
-> generate token
-> send token in cookie/header

Password Hashing

import bcrypt from "bcryptjs";

const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);

Compare Password

const isPasswordCorrect = await bcrypt.compare(password, user.password);

if (!isPasswordCorrect) {
  return res.status(400).json({ message: "Invalid credentials" });
}

Generate JWT

import jwt from "jsonwebtoken";

const token = jwt.sign(
  { userId: user._id },
  process.env.JWT_SECRET,
  { expiresIn: "7d" }
);

Send Cookie

res.cookie("jwt", token, {
  httpOnly: true,
  secure: process.env.NODE_ENV === "production",
  sameSite: "strict",
  maxAge: 7 * 24 * 60 * 60 * 1000,
});

Auth Middleware

import jwt from "jsonwebtoken";
import User from "../models/user.model.js";

export const protectRoute = async (req, res, next) => {
  try {
    const token = req.cookies.jwt;

    if (!token) {
      return res.status(401).json({ message: "Unauthorized" });
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET);

    const user = await User.findById(decoded.userId).select("-password");

    if (!user) {
      return res.status(401).json({ message: "Unauthorized" });
    }

    req.user = user;

    next();
  } catch (error) {
    res.status(401).json({ message: "Unauthorized" });
  }
};

Phase 14: Cookies, CORS, and Security

CORS

CORS controls which frontend can call your backend.

npm install cors
import cors from "cors";

app.use(
  cors({
    origin: "http://localhost:5173",
    credentials: true,
  })
);

cookie-parser

npm install cookie-parser
import cookieParser from "cookie-parser";

app.use(cookieParser());

Security Basics

Learn:

  • httpOnly cookies
  • secure cookies
  • sameSite
  • CORS origin
  • rate limiting
  • helmet
  • input validation
  • password hashing
  • environment variables

Useful Packages

helmet
express-rate-limit
cors
cookie-parser
bcryptjs
jsonwebtoken
zod

Phase 15: File Upload

File upload is used for profile pictures, product images, chat images, and blog covers.

Learn

  • frontend file input
  • multipart/form-data
  • multer
  • Cloudinary
  • storing image URL in database

Packages

npm install multer cloudinary

Common Flow

User selects image
-> frontend sends file/base64
-> backend receives image
-> upload to Cloudinary
-> get secure_url
-> save secure_url in database

Cloudinary Config

import { v2 as cloudinary } from "cloudinary";

cloudinary.config({
  cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
  api_key: process.env.CLOUDINARY_API_KEY,
  api_secret: process.env.CLOUDINARY_API_SECRET,
});

export default cloudinary;

Phase 16: Real-Time Backend

Real-time backend is used for chat, notifications, live comments, online status, etc.

Learn

  • WebSockets
  • Socket.IO
  • connection
  • disconnect
  • emit
  • listen
  • rooms
  • online users
  • typing indicators

Install

npm install socket.io

Socket.IO Example

import { Server } from "socket.io";
import http from "http";
import express from "express";

const app = express();
const server = http.createServer(app);

const io = new Server(server, {
  cors: {
    origin: "http://localhost:5173",
    credentials: true,
  },
});

io.on("connection", (socket) => {
  console.log("User connected:", socket.id);

  socket.on("sendMessage", (message) => {
    io.emit("newMessage", message);
  });

  socket.on("disconnect", () => {
    console.log("User disconnected:", socket.id);
  });
});

server.listen(3000, () => {
  console.log("Server running on port 3000");
});

Real-Time Projects

  • chat app
  • notification system
  • live comments
  • collaborative todo app
  • online status system

Phase 17: Deployment

Learn

  • environment variables
  • production scripts
  • database hosting
  • backend hosting
  • frontend-backend connection
  • CORS in production
  • logs
  • debugging deployed backend

Common Platforms

Render
Railway
Fly.io
Vercel
Neon
Supabase
MongoDB Atlas
Docker

Production Checklist

  • .env variables added on hosting platform
  • database URL is correct
  • CORS origin is frontend deployed URL
  • cookies configured correctly
  • backend logs checked
  • frontend API URL updated
  • no secrets pushed to GitHub

Phase 18: Advanced Backend Concepts

Learn these after building 2-3 backend projects.

Topics

  • pagination
  • filtering
  • sorting
  • search
  • indexing
  • caching
  • queues
  • cron jobs
  • rate limiting
  • refresh tokens
  • RBAC
  • webhooks
  • background jobs
  • transactions
  • database relationships
  • logging
  • testing APIs
  • Docker
  • CI/CD basics

Pagination Example

GET /api/products?page=1&limit=10

Filtering Example

GET /api/products?category=electronics

Sorting Example

GET /api/products?sort=price

Search Example

GET /api/products?search=laptop

Backend Project Order

Build projects in this order.

1. Basic Express Server

Features:

  • health route
  • JSON response
  • environment variable for port

2. Users API with In-Memory Array

Features:

  • get all users
  • get user by id
  • create user
  • update user
  • delete user

3. Todo API with In-Memory Array

Features:

  • CRUD todos
  • validation
  • status codes
  • filter completed todos

4. Notes API with MongoDB

Features:

  • create note
  • get all notes
  • get one note
  • update note
  • delete note
  • MongoDB/Mongoose

5. Auth API

Features:

  • signup
  • login
  • logout
  • JWT
  • cookies
  • protected route
  • get current user

6. Blog API

Features:

  • auth required for create/update/delete
  • public posts
  • comments
  • categories/tags
  • search
  • pagination

7. E-Commerce API

Features:

  • products
  • categories
  • cart
  • orders
  • auth
  • admin role
  • image upload

8. Chat Backend

Features:

  • auth
  • users
  • messages
  • Socket.IO
  • online users
  • image messages

9. Job Board API

Features:

  • companies
  • jobs
  • applications
  • auth
  • role-based access
  • search/filter/sort

10. SaaS Backend

Features:

  • teams
  • roles
  • workspaces
  • invites
  • billing mock
  • activity logs

10-Day Backend Starter Plan

Days 1-2

Learn:

  • Node.js
  • npm
  • package.json
  • Express server
  • GET/POST routes

Build:

  • basic server
  • users API with array

Days 3-4

Learn:

  • route params
  • query params
  • request body
  • PUT/PATCH/DELETE
  • status codes
  • validation

Build:

  • Todo API with array

Days 5-6

Learn:

  • routes/controllers folder structure
  • middleware
  • error handling

Build:

  • refactor Todo API properly

Days 7-8

Learn:

  • MongoDB
  • Mongoose
  • schema/model
  • CRUD with database

Build:

  • Notes API with MongoDB

Days 9-10

Learn:

  • signup/login
  • bcrypt
  • JWT
  • cookies
  • protected routes

Build:

  • Auth API

Backend Checklist

Node.js

  • Understand Node.js
  • Run JS using Node
  • Use npm
  • Understand package.json
  • Use ES Modules
  • Use environment variables

Express

  • Create Express server
  • Use express.json()
  • Create GET route
  • Create POST route
  • Create PATCH route
  • Create DELETE route
  • Understand req
  • Understand res

REST API

  • Understand HTTP methods
  • Use route params
  • Use query params
  • Use request body
  • Use status codes
  • Validate input

Middleware

  • Use app.use()
  • Create logger middleware
  • Create auth middleware
  • Use error middleware

Project Structure

  • Create routes folder
  • Create controllers folder
  • Create models folder
  • Create middleware folder
  • Create lib folder

Database

  • Connect MongoDB
  • Create Mongoose schema
  • Create Mongoose model
  • Perform CRUD operations
  • Understand relationships
  • Learn PostgreSQL basics
  • Learn Prisma basics

Authentication

  • Signup
  • Login
  • Hash password
  • Compare password
  • Generate JWT
  • Send cookie
  • Protect route
  • Logout
  • Get current user

Security

  • CORS
  • Cookies
  • httpOnly
  • secure
  • sameSite
  • rate limiting
  • helmet
  • env variables

Deployment

  • Use production env variables
  • Deploy backend
  • Connect database
  • Fix CORS in production
  • Check logs
  • Test deployed API

Final Backend Learning Order

Node.js
-> npm
-> Express
-> REST APIs
-> request data
-> validation
-> middleware
-> routes/controllers
-> error handling
-> MongoDB/Mongoose
-> auth
-> cookies/CORS/security
-> file upload
-> real-time backend
-> deployment
-> advanced backend concepts

Rule

Do not just watch tutorials.

Use this cycle:

learn one backend topic
-> build one small API
-> test with Postman/Thunder Client
-> debug errors
-> push to GitHub
-> write README notes
-> move to next topic