Processing HTTP Requests With Middlewares in Express.js
Express.js·4 min read·Jan 1, 2025
In Express, incoming HTTP requests can be intercepted before they reach a route's request listener using a special type of function called a middleware.
These middlewares are at the core of Express' design and are used for a variety of actions, such as logging requests, verifying request headers, parsing request payloads, and so on.
The request-response lifecycle
Just like a request listener, a middleware has access to the request and response objects, as well as an additional parameter named next.
function middleware(req, res, next) { //}Beyond executing internal logic, it can terminate the request-response lifecycle by sending an immediate response to the client using one of the methods of the response object, such as send() or sendStatus():
function middleware(req, res, next) { // Execute internal logic res.sendStatus(200);}Or it can forward the request to the next middleware (or request listener) in the call stack, by invoking its next() argument, which is actually a function — as without it, the request will be left hanging until it times out:
function middleware(req, res, next) { // Execute internal logic next();}Unlock the Build RESTful APIs in Node.js module
Learn how to build real database-backed and framework-powered RESTful APIs with MySQL, Sequelize, and Express.
You get immediate access to:
- 37 focused lessons across MySQL, Sequelize, backend, and Express
- 4 real-world projects with commented solutions
- Ongoing updates to this bundle
- Lifetime access to this bundle