Express.js: APIs and Middleware
Master building RESTful APIs and custom middleware with Express.js from scratch to production patterns. By the end, you will have built a fully functional REST API with authentication, error handling, and structured middleware pipelines.
Course Content
6 modules · 30 lessonsExpress.js Fundamentals
Set up an Express server and understand the core request-response cycle.
What is Express.js and why use it over plain Node.js
Express.js definition, Node.js HTTP module vs Express, unopinionated framework, routing abstraction, npm install express, minimal server setup
How to create your first Express server and handle requests
require express, app.listen, port binding, req object, res object, res.send vs res.json, HTTP methods in Express
Express routing — defining GET, POST, PUT, DELETE routes
app.get, app.post, app.put, app.delete, HTTP verb semantics, route handlers, app.route chaining, REST conventions
Route parameters and query strings in Express
req.params, req.query, dynamic route segments, colon syntax, optional params, query string parsing, multiple query params
Express Router — how to split routes into separate files
express.Router, router instance, router.get router.post, app.use prefix, modular routing, require router file, route organization
Middleware Deep Dive
Understand how middleware works and write custom middleware for logging, validation, and request transformation.
What is middleware in Express and how the middleware stack works
middleware definition, req res next, middleware execution order, app.use, global vs route-level middleware, middleware chain, stack concept
How to write a custom logging middleware in Express
custom middleware function, req.method, req.url, Date.now timing, res.on finish event, response status logging, middleware placement
How to write request validation middleware in Express
validation middleware, req.body checks, 400 Bad Request, early return pattern, field presence checking, type checking, reusable validators, middleware factory functions
How third-party middleware works — morgan, cors, helmet
morgan HTTP logger, cors middleware, helmet security headers, npm install, app.use order, cors options origin, helmet defaults, middleware configuration
How to pass data between middleware using req object
req custom properties, attaching data to req, req.user, req.locals vs res.locals, middleware composition, auth middleware data passing, downstream access
Building RESTful APIs
Design and implement production-pattern RESTful APIs with proper status codes, error handling, and response structure.
REST API design principles every developer should know
REST constraints, resource naming, noun vs verb URLs, statelessness, URI design, plural nouns, nested resources, HTTP method semantics, idempotency
How to structure consistent JSON API responses
response envelope pattern, data field, error field, meta pagination, success flag, HTTP status vs response body, JSend convention, consistent structure
Express error handling middleware — how to catch all errors
error handler middleware, 4-parameter signature, next(err), app.use placement, operational vs programmer errors, custom AppError class, centralized error handling
Pagination, filtering, and sorting in REST APIs
page and limit query params, skip and offset, sorting by field, filter by property, cursor pagination concept, totalPages calculation, query builder pattern
How to handle async route handlers without crashing Express
async await in Express, unhandled promise rejection, try catch boilerplate, asyncHandler wrapper, process uncaughtException, error propagation with next
Authentication and Authorization
Implement JWT-based authentication and role-based access control in an Express API.
How JWT authentication works in REST APIs
JWT structure, header payload signature, Base64 encoding, HMAC SHA256, token signing, token verification, stateless auth, Bearer token
How to write JWT authentication middleware in Express
jwt.verify, Authorization header, Bearer token extraction, 401 vs 403, req.user from token, token expiry handling, JsonWebTokenError, middleware placement
Role-based access control (RBAC) middleware in Express
RBAC pattern, role middleware factory, req.user.role, 403 Forbidden, authorize function, multiple roles, middleware chaining with auth, resource ownership
How to hash passwords and store them securely with bcrypt
bcrypt hashing, salt rounds, bcrypt.hash, bcrypt.compare, why not plain SHA256, timing attacks, password never stored plain, environment variables for secret
How to use environment variables to protect secrets in Express
dotenv package, .env file, process.env, .gitignore env file, JWT_SECRET, DATABASE_URL, NODE_ENV, env validation on startup
Advanced Middleware Patterns
Build production-grade middleware for rate limiting, request caching, input sanitization, and file uploads.
How to build a rate limiting middleware from scratch
rate limiting concept, in-memory request tracking, IP-based limits, window reset, 429 Too Many Requests, Retry-After header, sliding vs fixed window, express-rate-limit library
Input sanitization middleware — preventing injection attacks
XSS prevention, HTML entity encoding, SQL injection concept, input trimming, mongo injection, sanitize-html, express-validator sanitizers, req.body sanitization
How to handle file uploads in Express with Multer
multer package, diskStorage, memoryStorage, upload.single, upload.array, file size limits, file type filtering, req.file, req.files, MIME type check
Response caching middleware — how to cache API responses
in-memory cache, Cache-Control headers, cache key generation, TTL expiry, cache invalidation, stale data tradeoff, when to cache, ETag concept
How to structure Express middleware for large-scale applications
middleware folder structure, index.js barrel file, middleware ordering strategy, app-level vs router-level, conditional middleware, middleware composition, testing middleware
Testing and Deploying Express APIs
Write integration tests for Express routes and deploy a production-ready Express API.
How to test Express routes with Jest and Supertest
supertest library, jest test runner, describe it blocks, request(app).get, expect status, expect body, beforeEach afterEach, test isolation, app export pattern
How to test authenticated Express routes in Jest
JWT in tests, test token generation, Authorization header in supertest, beforeAll token setup, test user fixture, authenticated request helper, 401 testing
Express app configuration for production — compression, logging, and CORS
compression middleware, morgan combined, trust proxy, NODE_ENV production, CORS origin whitelist, express.static, security headers production, PORT env var
How to deploy an Express API to Railway or Render
Railway deployment, Render deployment, start script in package.json, PORT from env, Procfile optional, environment variables in dashboard, zero-downtime deploy, health check endpoint
How to document an Express API with Swagger/OpenAPI
swagger-jsdoc, swagger-ui-express, OpenAPI 3.0 spec, JSDoc annotations, @swagger tag, path definitions, schema components, /api-docs endpoint, info block
