TIL: Writing Express.js middlewares

2022-04-13 00:00:00 +0000 UTC

Express.js middlewares have this type signature:

function(req, res, next) { ... }

req is the familiar Express request object. res is the response object. next is the next middleware or handler registered to the route.

The general structure of the middleware is something like this:

function mw(req, res, next) {
	if( condition ) {
		// do something with the request body here
		// can modify the request for the next handler/middleware
		// verify a token or something
	}

	if( somethingWrong ) {
		res.json({message: 'you can abort the request/response cylce early'});
	}

	//or just pass along to the next middleware/router
	next();
}

There are other details: next('route') passes the control to the next router; a middleware with the signature function(err, req, res, next) gets called when an error is thrown or passed to next(err).

Express: Writing Middleware, Using Middleware, Error handling.

Tags: til express nodejs