Routing determines how your application responds to client requests. Middleware functions are the backbone of Express — they process requests at every stage of the pipeline.
Route Methods
Express provides methods for every HTTP verb:
HTTP Methods at a Glance
| Method | Purpose | Idempotent |
|---|---|---|
| GET | Retrieve a resource | Yes |
| POST | Create a new resource | No |
| PUT | Replace a resource entirely | Yes |
| PATCH | Partially update a resource | Yes |
| DELETE | Remove a resource | Yes |
Route Parameters
Capture dynamic values from the URL path:
Query Parameters
Query parameters come after ? in the URL:
Route Chaining with route()
Group different methods for the same path:
What is Middleware?
Middleware functions have access to the request object, response object, and the next function. They can execute code, modify the request/response, end the request-response cycle, or call next() to pass control to the next middleware.
The Middleware Pipeline
Requests flow through middleware in the order they are registered:
Request → Logger → Auth → Route Handler → Error Handler → ResponseBuilding Custom Middleware
Request Logger
Request Validator
Rate Limiter
CORS Middleware
Cross-Origin Resource Sharing allows your API to be called from different domains:
npm install corsServing Static Files
Files in the public directory become accessible at the root URL (or under /assets with the prefix).
Error Handling Middleware
Error middleware has four parameters — Express identifies it by the (err, req, res, next) signature:
Practical Exercise
Build a middleware stack for a production API:
Key Takeaways
- Express routes match HTTP methods and URL patterns to handler functions.
- Middleware functions form a pipeline — each can modify the request/response or pass control with
next(). - Register middleware in order: parsers first, then loggers, auth, routes, and error handlers last.
- Custom middleware like validators and rate limiters keep your route handlers clean.
- Error-handling middleware must have exactly four parameters:
(err, req, res, next).