DEV Community

loading...
Cover image for Middleware and its type in expressjs/Nodejs

Middleware and its type in expressjs/Nodejs

Rahul kumar
I am a computer science engineer by passion.
・3 min read

What is middleware

Middleware is a kind of function that can change the request and response object and also can finish the request and response cycle.

This article assumes that you have basic knowledge of middleware

Rights of middleware

Middleware has all rights that any route handler can have in expressjs. Middleware can do everything which any route handler can do.

Middleware can

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware function in the stack.

Withour wasting much time, lets queckly jump on the types of middleware

Types of middleware

There are five types of middleware

  1. Application-level middleware
  2. Router level middleware
  3. Error handling middleware
  4. Built-in middleware
  5. Third-party middleware

Router level and application leven middleware can be loaded with optional mount path


For the rest of the article, we'll use the following middleware for demonstration and express instance

const express = require('express');
const app = express(); // express instance

function MW(req,res,next){
    console.log("I am middleware!");
    next(0;
}
Enter fullscreen mode Exit fullscreen mode

Application-level middleware

Application-level middleware can be registered with the express instance directly.

If we don't use any mount path then middleware will be executed for every request.

app.use(MW);
Enter fullscreen mode Exit fullscreen mode

We can use any mount path to register middleware.

// here, /path and /path/:userid are mount paths
app.use("/path",MW);

// it can also accept params
app.use("/path/:userId",MW);
Enter fullscreen mode Exit fullscreen mode

We can also register more than one middleware for a single mount path at once

// insted of doing
app.use("/path",MW1);
app.use("/path",MW2);
app.use("/path",MW3);

// we can do
app.use("/path",MW1,MW2,MW3);

// we can also pass array of middleware
app.use("/path",[MW1,MW2,MW3]);
Enter fullscreen mode Exit fullscreen mode

Router level middleware

Router level middleware can be defined in the same way as application-level middleware

var router = express.Router()
router.use("/path",MW1);
Enter fullscreen mode Exit fullscreen mode

We can also assign middleware to any specific path.

router.use('/user/:id', function (req, res, next) {
  console.log('Request URL:', req.originalUrl)
  next()
}, function (req, res, next) {
  console.log('Request Type:', req.method)
  next()
})
Enter fullscreen mode Exit fullscreen mode

Error-handling middleware

Error-handling middleware always takes four arguments (err, req, res, next)

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})
Enter fullscreen mode Exit fullscreen mode

You must take care of the ordering of the middleware while declaring error handling middleware.

// i will be never called
app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

app.get("/*",(_,res,next)=>{
    try{
        throw new Error("This is the error!");
    }catch(e){
        next(e)
    }
})
Enter fullscreen mode Exit fullscreen mode

Here, the above middleware will be never called because the route is declared after middleware, to make it work we need to define it after the route.

// This works fine
app.get("/*",(_,res,next)=>{
    try{
        throw new Error("This is the error!");
    }catch(e){
        next(e)
    }
})

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})
Enter fullscreen mode Exit fullscreen mode

Built-in middleware

Built-in middleware is provided by express itself like, express.static() etc.

Third-party middleware

Third-party middleware is provided by any third party of any NPM module, like cooki-parser, body-parser, etc.

Thanks

Discussion (0)