Express.js tutorial
Build web servers and REST APIs with Express 5 and Node.js, one route at a time.
Course contents
Express.js Foundations
- Introduction to Express.js — What Express.js is and why it was created, its history and features, Express versus the Node.js http module, Express 4 versus Express 5, how a request flows through an app, what you can build, and how to set up, configure, run and test your first Express 5 server.
- HTTP Fundamentals — Clients and servers, requests and responses, URLs, origins, paths and endpoints, headers and bodies, HTTP methods, status codes, content types, and the Express request-response cycle.
Requests and Routing
- Application, Request and Response — The app object and its settings, app.locals and sub-apps, everything req holds, every way res can answer, the one-response rule, and caching with ETags, 304 answers and range requests.
- Routing and Routers — Route methods, parameters, query strings, the Express 5 path syntax, route order, handler chains, app.route, router files, router middleware, nested routers, mergeParams and router.param.
Express Middleware
- Middleware Fundamentals — What middleware is, the (req, res, next) pipeline, the three ways to finish, middleware types, global, path-based and route-specific mounting, registration order, custom middleware, access-control middleware, factories and async middleware in Express 5.
- Body Parsers and Third-Party Middleware — express.json and its options, handling invalid JSON, express.urlencoded for forms, express.text and express.raw for webhooks, body size limits, and how to choose, install, configure and place third-party middleware.
Views and Static Content
- Views and Static Files — EJS templates, passing data, loops, conditions, partials and safe escaping, then serving CSS, images and scripts with express.static, caching, SPA fallbacks and keeping private files safe.
Data Handling
- Input Processing and Validation — Reading JSON, form data and headers, converting values, the Post-Redirect-Get pattern, validation rules, validation middleware, 400 versus 422, sanitization with trimming and allowlists, and validation libraries like Zod.
- Cookies and Sessions — How cookies travel, setting, reading, signing and clearing cookies with cookie-parser, cookie options, sessions with express-session, session stores, login with hashed passwords, protecting page and API routes, logout, and session security.
- File Handling — Sending files with res.sendFile, downloads with res.download and res.attachment, streaming large files, uploads with Multer, memory and disk storage, checking uploads, path traversal and other file security, and upload error handling.
- Working with a Database — SQLite with node:sqlite, prepared statements and SQL injection, CRUD routes on a database, joins, transactions, repositories and migrations, and where PostgreSQL and ORMs fit.
APIs and Errors
- Building REST APIs — REST basics, idempotency, API routers and versioning, collection routes with filtering, search, sorting, pagination and field selection, create, read, update and delete, PUT versus PATCH, status codes, consistent JSON and route structure.
- Error Handling — Operational and programming errors, how errors reach Express, Express 5 async forwarding and its limits, error middleware, res.headersSent, custom error classes, 404 handling, HTML and JSON errors, and development versus production error output.
- Token Authentication and Authorization — Sessions versus tokens, how a JWT is built, login that signs tokens, Bearer middleware, expiry and refresh tokens, role and ownership checks, token storage, Passport and Google sign-in.
Advanced HTTP
- Redirects, Content Negotiation and Proxies — Content negotiation with Accept headers, req.accepts and res.format, 406, redirect status codes, res.redirect and res.location, building and checking redirect URLs, open redirects, reverse proxies, trust proxy and forwarded headers.
- Calling APIs, Background Jobs and Real-Time — Calling other APIs with fetch, checking response.ok, timeouts, retries with backoff, idempotency keys, caching, background jobs with 202 Accepted, fire-and-forget work, Server-Sent Events and WebSockets.
Operations
- Logging and Debugging — What to log, a custom logger with the finish event, request IDs, Morgan formats and custom tokens, error logging, the DEBUG environment variable, debugging routes, middleware order and async handlers, and health checks.
- Express Security — Security headers with Helmet, HTTPS, CORS and why it is not authentication, XSS and CSRF, rate limiting, request timeouts, keeping secrets safe, the order of security middleware, and a security review checklist.
- Deploying an Express App — Config from environment variables, failing fast, NODE_ENV=production, npm start and PM2, liveness and readiness checks, graceful shutdown on SIGTERM, Docker, hosting platforms and HTTPS.
Architecture and Reference
- Application Structure — Splitting app.js and server.js, a project folder layout, a central config module, registration order, startup errors and graceful shutdown, testing with node:test and Supertest, Express Generator, and keeping code healthy.
- Express with TypeScript — Setting up tsx and tsc, catching bugs with tsc --noEmit, typing params, bodies and responses, extending Request with req.user, runtime type guards and Zod, and building for production.
- Capstone: The Complete Canteen API — One full project: SQLite tables, hashed passwords, JWT login, staff and student roles, validated orders with ownership checks, central errors, supertest tests, OpenAPI docs, health checks and graceful shutdown.
- Express.js Cheat Sheet — A one-page reference for Express 5: project setup, application settings, request and response methods, routing and Express 5 path syntax, routers, middleware, views, static files, sessions, files, REST status codes, errors, redirects, proxies, logging, security, registration order and an Express 4 to 5 migration checklist.