How to write your custom middleware in Node.js

At some point in time you will probably want to write your own middleware. However, before starting to write your own middleware you should browse the npm official website since there is a big chance that the middleware is already written.

A custom middleware is just a function that accepts four parameters: err, req, res, and next.

The err is an error object. It is passed to your middleware if there was an error prior of running your middleware. If there is an error passed to your middleware then you can decide how to deal with it.

The req is an object that contains the information about the HTTP request to the server. Basically, you tell the server what your requests are.

The res is also an object. It is used in response of the req.

The next is a reference to a callback. It calls the next middleware.

Below is an example of a simple middleware:

app.use(function(err, req, res, next) { // important line
// some code here
return next(); // important line

You must have the correct parameters and the return next(); line.

Leave a Reply