Creating custom middleware

Undoubtedly, there will be a time when you want to write your own custom middleware in addition to the existing middleware provided by Connect or any other third party. Before you write your own custom middleware in Node, make it a habit to search through https://www.npmjs.org/ first, as there's a fairly big chance someone else has already done the work.

Writing your own custom middleware is pretty simple. While using an Express framework, it documents various types of middleware that we would simply categorize into two types, that is, application-based and route-based middlewares.

Here is a super basic example of application-based middleware:

app.use((err, req, res, next)=> { 
    // do whatever you want here, alter req, alter res, throw err etc. 
    return next(); 
});

The app.use function allows us to register as a middleware. At its basic level, it is a function that is called on receiving a request in the http.createServer method. Further, we need to write a function that accepts four parameters: err, req, res, and next.

  • The first parameter is an error object, and if there were any stack errors prior to your middleware running, that error would be passed to your middleware so that you can handle it accordingly. This is an optional parameter; hence, we can skip it if no error handling is required for the specific implementation of functionality.
  • You are already familiar with the req and res parameters, having written your routes.
  • The fourth parameter is actually a reference to a callback. This next parameter is how the middleware stack is able to behave like a stack—each executing and ensuring that the next middleware in the pipeline is returned and called via next.

An app.use method also accepts the first parameter as a route or an endpoint. This forms the second type of middleware called the route-based middleware that was mentioned earlier. Here is the syntax:

app.use('/get_data', (err, req, res, next)=>{ 
    console.log('Hello world!')     
    return next(); 
}, (err, req, res, next)=>{ 
    console.log('Hello world Again!')     
    return next();
});

So, this depicts that instead of applying a middleware to all the incoming requests, we make it specific to a route and call on the route match.

The only important thing to keep in mind while writing your own custom middleware is that you have the correct parameters and you return next(). The rest is completely up to you!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.184.102