Express.js Documentation
The minimal Node.js framework for REST APIs — routing, middleware, validation, auth and error handling.
Express is the most popular web framework for Node.js — a small, flexible layer on top of Node's http module for building REST APIs and web servers. It is the E in the MERN stack. Its core idea is simple: a request flows through a chain of middleware functions until one of them sends a response.
1. Introduction & Setup
mkdir notes-api && cd notes-api
npm init -y
npm install express
npm install --save-dev nodemon
Add "type": "module" to package.json to use import, and scripts:
{
"type": "module",
"scripts": { "dev": "nodemon src/index.js", "start": "node src/index.js" }
}
// src/index.js
import express from 'express';
const app = express();
app.use(express.json()); // parse JSON bodies
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`API running on http://localhost:${PORT}`));
npm run dev
Output:
API running on http://localhost:5000
⚠️ Common error:
Error: listen EADDRINUSE: address already in use :::5000— another process uses the port. Stop it or changePORT.
2. Routing
app.get('/notes', handler); // read all
app.get('/notes/:id', handler); // read one
app.post('/notes', handler); // create
app.put('/notes/:id', handler); // replace
app.patch('/notes/:id', handler); // update part
app.delete('/notes/:id', handler); // delete
app.all('/health', handler); // any method
Route parameters, query strings and the body:
// GET /users/42/posts?page=2&sort=new
app.get('/users/:userId/posts', (req, res) => {
const { userId } = req.params; // "42" (always strings)
const page = Number(req.query.page) || 1; // 2
const sort = req.query.sort || 'new';
res.json({ userId, page, sort });
});
// POST /notes with JSON {"title": "Graphs"}
app.post('/notes', (req, res) => {
const { title } = req.body; // needs app.use(express.json())
res.status(201).json({ id: 1, title });
});
Group routes with express.Router():
// src/routes/notes.js
import { Router } from 'express';
const router = Router();
router.get('/', listNotes);
router.get('/:id', getNote);
router.post('/', createNote);
export default router;
// src/index.js
import notesRouter from './routes/notes.js';
app.use('/api/notes', notesRouter); // GET /api/notes, GET /api/notes/:id …
3. Request & Response
req |
Meaning |
|---|---|
req.params |
URL parameters (/notes/:id) |
req.query |
query string (?q=graph) |
req.body |
parsed body (needs a body parser) |
req.headers / req.get('Authorization') |
request headers |
req.cookies |
cookies (needs cookie-parser) |
req.ip, req.method, req.path |
client IP, method, path |
res |
Meaning |
|---|---|
res.json(obj) |
send JSON (sets Content-Type) |
res.send(text) |
send text/HTML/buffer |
res.status(404).json({...}) |
set status then send |
res.sendStatus(204) |
status only |
res.redirect('/login') |
redirect (302) |
res.set('Cache-Control', 'no-store') |
set a header |
res.cookie('token', t, { httpOnly: true }) |
set a cookie |
res.sendFile(path) / res.download(path) |
send a file |
⚠️ Common error:
Cannot set headers after they are sent to the client— you responded twice. Usereturn res.json(...)so the function stops.
4. Middleware
A middleware is (req, res, next) => { … }. It can read/change req and res, end the request, or call next() to pass control on. Order matters — they run in the order you app.use() them.
// logger
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${Date.now() - start}ms`));
next();
});
Built-in and popular middleware:
import cors from 'cors';
import helmet from 'helmet';
import cookieParser from 'cookie-parser';
import morgan from 'morgan';
app.use(helmet()); // security headers
app.use(cors({ origin: process.env.CLIENT_URL, credentials: true }));
app.use(express.json({ limit: '1mb' })); // JSON body
app.use(express.urlencoded({ extended: true })); // HTML form body
app.use(cookieParser());
app.use(morgan('dev')); // request logs
app.use(express.static('public')); // serve files from ./public
Middleware for one route only:
app.get('/admin/stats', requireAuth, requireAdmin, getStats);
5. Validation & Error Handling
Never trust input. Validate and send 400 with a clear message:
app.post('/api/notes', (req, res) => {
const title = String(req.body.title || '').trim();
if (title.length < 3) return res.status(400).json({ message: 'Title must be at least 3 characters' });
// …
});
With a schema library (zod):
import { z } from 'zod';
const NoteSchema = z.object({ title: z.string().min(3).max(120), tags: z.array(z.string()).default([]) });
const validate = (schema) => (req, res, next) => {
const r = schema.safeParse(req.body);
if (!r.success) return res.status(400).json({ message: r.error.issues[0].message });
req.body = r.data;
next();
};
app.post('/api/notes', validate(NoteSchema), createNote);
Error-handling middleware has four arguments and goes last:
// 404 for unknown routes
app.use((req, res) => res.status(404).json({ message: `Not found: ${req.originalUrl}` }));
// central error handler
app.use((err, req, res, next) => {
console.error(err);
const status = err.status || 500;
res.status(status).json({ message: status === 500 ? 'Something went wrong' : err.message });
});
Async errors: in Express 5 a rejected promise in a handler goes to the error handler automatically. In Express 4 wrap handlers:
const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
router.get('/', asyncHandler(async (req, res) => res.json(await Note.find())));
6. Connecting a Database (MongoDB + Mongoose)
npm install mongoose dotenv
// src/db.js
import mongoose from 'mongoose';
export async function connectDB() {
await mongoose.connect(process.env.MONGO_URI);
console.log('MongoDB connected');
}
// src/models/Note.js
import mongoose from 'mongoose';
const noteSchema = new mongoose.Schema(
{ title: { type: String, required: true, trim: true }, body: String, tags: [String] },
{ timestamps: true }
);
export default mongoose.model('Note', noteSchema);
// src/index.js
import 'dotenv/config';
import { connectDB } from './db.js';
await connectDB();
app.listen(PORT, () => console.log(`API on ${PORT}`));
Full CRUD controller:
import Note from '../models/Note.js';
export const listNotes = async (req, res) => {
const q = req.query.q ? { title: new RegExp(escapeRegex(req.query.q), 'i') } : {};
const notes = await Note.find(q).sort({ createdAt: -1 }).limit(50).lean();
res.json(notes);
};
export const getNote = async (req, res) => {
const note = await Note.findById(req.params.id).lean();
if (!note) return res.status(404).json({ message: 'Note not found' });
res.json(note);
};
export const createNote = async (req, res) => {
const note = await Note.create({ title: req.body.title, body: req.body.body, tags: req.body.tags });
res.status(201).json(note);
};
export const updateNote = async (req, res) => {
const note = await Note.findByIdAndUpdate(req.params.id, { $set: req.body }, { new: true, runValidators: true });
if (!note) return res.status(404).json({ message: 'Note not found' });
res.json(note);
};
export const deleteNote = async (req, res) => {
await Note.findByIdAndDelete(req.params.id);
res.sendStatus(204);
};
const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
⚠️ An invalid id like
/notes/abcthrows aCastError— checkmongoose.isValidObjectId(id)and return 400/404.
7. Authentication with JWT
npm install bcryptjs jsonwebtoken
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
router.post('/register', async (req, res) => {
const { name, email, password } = req.body;
if (await User.exists({ email })) return res.status(409).json({ message: 'Email already registered' });
const user = await User.create({ name, email, password: await bcrypt.hash(password, 10) });
res.status(201).json({ token: sign(user) });
});
router.post('/login', async (req, res) => {
const user = await User.findOne({ email: req.body.email });
if (!user || !(await bcrypt.compare(req.body.password, user.password)))
return res.status(401).json({ message: 'Wrong email or password' });
res.json({ token: sign(user) });
});
const sign = (u) => jwt.sign({ id: u._id, role: u.role }, process.env.JWT_SECRET, { expiresIn: '7d' });
export function requireAuth(req, res, next) {
const token = (req.get('Authorization') || '').replace(/^Bearer /, '');
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch {
res.status(401).json({ message: 'Please log in' });
}
}
export const requireAdmin = (req, res, next) =>
req.user.role === 'admin' ? next() : res.status(403).json({ message: 'Admins only' });
8. File Uploads, Rate Limiting & Security
File uploads with multer:
import multer from 'multer';
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 2 * 1024 * 1024 }, // 2 MB
fileFilter: (req, file, cb) => cb(null, /^image\/(png|jpe?g|webp)$/.test(file.mimetype)),
});
router.post('/avatar', requireAuth, upload.single('avatar'), async (req, res) => {
if (!req.file) return res.status(400).json({ message: 'Upload a PNG, JPG or WebP image' });
// req.file.buffer → upload to Cloudinary / S3
res.json({ ok: true });
});
Rate limiting:
import rateLimit from 'express-rate-limit';
app.use('/api/auth', rateLimit({ windowMs: 15 * 60 * 1000, limit: 20 })); // 20 requests / 15 min per IP
Security checklist:
| Risk | Defence |
|---|---|
| Missing security headers | helmet() |
| Open CORS | cors({ origin: allowedOrigin }) |
| Brute force | rate limits on login / OTP |
NoSQL injection ({ "$gt": "" } in body) |
validate types; express-mongo-sanitize |
| Huge bodies | express.json({ limit }) |
| Leaking stack traces | generic 500 message in production |
| Secrets in code | .env + environment variables |
| Real IP behind a proxy | app.set('trust proxy', 1) |
9. Project Structure
src/
├── index.js ← create app, middleware, routes, start server
├── db.js
├── config/ ← env parsing
├── models/ ← Mongoose schemas
├── routes/ ← express.Router() per resource
├── controllers/ ← request handlers
├── middleware/ ← auth, validate, errors, rate limits
├── utils/ ← helpers (email, tokens)
└── tests/
Keep app (setup) separate from listen (start) so tests can import the app:
// src/app.js → export default app; src/index.js → app.listen(...)
10. Advanced Concepts
- Express 5 (stable since 2024): async error handling,
req.queryis read-only, path syntax changes (/*splatinstead of*), removed deprecated methods. - Pagination:
?page=2&limit=20→.skip((page-1)*limit).limit(limit), or cursor-based (?after=<id>) for large data. - Caching: set
Cache-Control/ETag; cache hot queries in Redis. - Compression:
app.use(compression()). - Graceful shutdown: on
SIGTERM,server.close()then close the DB connection. - Testing:
supertest+ Jest/Vitest:
import request from 'supertest';
import app from '../app.js';
test('GET /health', async () => {
const res = await request(app).get('/health');
expect(res.status).toBe(200);
});
- Real-time: add Socket.IO on the same HTTP server for chat/notifications.
- Deployment: Render, Railway, Fly.io, a VPS with PM2 + Nginx, or Docker. Read
PORTfrom the environment.
11. Examples with Output
Example 1 — Route params and query
app.get('/greet/:name', (req, res) => {
res.json({ message: `Hello, ${req.params.name}!`, lang: req.query.lang || 'en' });
});
curl "http://localhost:5000/greet/Asha?lang=hi"
{"message":"Hello, Asha!","lang":"hi"}
Example 2 — Validation error
curl -X POST http://localhost:5000/api/notes -H "Content-Type: application/json" -d '{"title":"a"}'
{"message":"Title must be at least 3 characters"}
Example 3 — Unknown route
curl http://localhost:5000/nope
{"message":"Not found: /nope"}
12. Practice Problems
- Build a CRUD API for a "todos" resource stored in an array, then switch it to MongoDB.
- Add a request logger middleware that prints method, URL, status and time taken.
- Add validation with zod and a central error handler that returns JSON for every error.
- Implement register/login with bcrypt + JWT and protect
POST /todos. - Add pagination and search (
?q=) toGET /todosand return{ items, total, page }. - Upload a profile picture with multer and reject files over 1 MB.
- Add a rate limit on the login route and test it with a loop of requests.
- Write supertest tests for create, read, update and delete.
13. Interview Questions
1. What is middleware in Express?
A function (req, res, next) in the request pipeline that can modify the request/response, end it, or call next() to continue.
2. Difference between app.use() and app.get()?
app.use() mounts middleware for all methods on a path prefix; app.get() handles only GET requests on an exact path pattern.
3. How do you handle errors?
A final middleware with four arguments (err, req, res, next); call next(err) or throw in async handlers (Express 5) to reach it.
4. req.params vs req.query vs req.body?
Path variables, query string values and the request body respectively.
5. Why express.json()?
It parses JSON request bodies into req.body; without it req.body is undefined.
6. What is CORS and how do you enable it?
Browsers block cross-origin requests unless the server allows them; use the cors middleware with the allowed origin.
7. How do you structure a large Express app? Routers per resource, controllers, models, middleware and config folders; separate the app from the server start.
8. How do you secure an Express API? Helmet, strict CORS, input validation, rate limiting, hashed passwords, JWT/session auth, HTTPS, secrets in env vars.
9. What does next('route') do?
Skips the remaining handlers of the current route and moves to the next matching route.
10. Express vs Node's http module?
Express adds routing, middleware, helpers (res.json, static files) and a large ecosystem on top of the low-level http module.
14. Cheat Sheet & References
App setup
import express from 'express'
const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(express.static('public'))
app.listen(process.env.PORT || 5000)
Routes
app.get('/items', list)
app.post('/items', create)
app.patch('/items/:id', update)
app.delete('/items/:id', remove)
const router = express.Router()
app.use('/api/items', router)
Request and response
req.params.id; req.query.page; req.body
req.get('Authorization'); req.cookies.token
res.status(201).json(obj)
res.sendStatus(204)
res.redirect('/login')
res.cookie('token', t, { httpOnly: true, secure: true })
Middleware and errors
app.use((req, res, next) => next())
app.get('/admin', requireAuth, requireAdmin, handler)
app.use((req, res) => res.status(404).json({ message: 'Not found' }))
app.use((err, req, res, next) => res.status(err.status || 500).json({ message: err.message }))
Common packages
npm i cors helmet morgan cookie-parser dotenv
npm i mongoose bcryptjs jsonwebtoken zod
npm i multer express-rate-limit compression
npm i -D nodemon supertest
Official documentation