Middleware and its type in expressjs/Nodejs

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 m…


This content originally appeared on DEV Community and was authored by Rahul kumar

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;
}

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);

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);

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]);

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);

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()
})

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!')
})

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)
    }
})

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!')
})

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


This content originally appeared on DEV Community and was authored by Rahul kumar


Print Share Comment Cite Upload Translate Updates
APA

Rahul kumar | Sciencx (2021-05-02T16:44:25+00:00) Middleware and its type in expressjs/Nodejs. Retrieved from https://www.scien.cx/2021/05/02/middleware-and-its-type-in-expressjs-nodejs/

MLA
" » Middleware and its type in expressjs/Nodejs." Rahul kumar | Sciencx - Sunday May 2, 2021, https://www.scien.cx/2021/05/02/middleware-and-its-type-in-expressjs-nodejs/
HARVARD
Rahul kumar | Sciencx Sunday May 2, 2021 » Middleware and its type in expressjs/Nodejs., viewed ,<https://www.scien.cx/2021/05/02/middleware-and-its-type-in-expressjs-nodejs/>
VANCOUVER
Rahul kumar | Sciencx - » Middleware and its type in expressjs/Nodejs. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/05/02/middleware-and-its-type-in-expressjs-nodejs/
CHICAGO
" » Middleware and its type in expressjs/Nodejs." Rahul kumar | Sciencx - Accessed . https://www.scien.cx/2021/05/02/middleware-and-its-type-in-expressjs-nodejs/
IEEE
" » Middleware and its type in expressjs/Nodejs." Rahul kumar | Sciencx [Online]. Available: https://www.scien.cx/2021/05/02/middleware-and-its-type-in-expressjs-nodejs/. [Accessed: ]
rf:citation
» Middleware and its type in expressjs/Nodejs | Rahul kumar | Sciencx | https://www.scien.cx/2021/05/02/middleware-and-its-type-in-expressjs-nodejs/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.