Process HTTP Requests in Express
Express·2 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.
Define middleware functions
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) { //}Modify the request-response lifecycle
Beyond executing internal logic, a middleware 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();