Skipping middleware in Express.js

Express JSServer Side ProgrammingProgramming

You need to pass some parameters to skip the middleware in an Express application. On the basis of that parameter with logic in place, you can decide whether to execute a middleware or not

Syntax

There is no syntax defined. You can introduce a parameter and then check based upon that parameter whether to use the middleware or not.

Example

Create a file with the name "skipMiddleware.js" and copy the following code snippet. After creating the file, use the command "node skipMiddleware.js" to run this code as shown in the example below −

// app.set() Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;


// Defining a middleware
let middleware1 = (req, res, next) => {

   // Passing a middleware parameter
   req.shouldRunMiddleware2 = false;
   console.log("Middleware 1 is running !");
   next();
}

// Defining another middleware
let middleware2 = (req, res, next) => {
   // SKipping middleware based in boolean value
   if(!req.shouldRunMiddleware2) {
      console.log("Skipped middleware 2");
      return next();
   }
   console.log("Middleware 2 is running !");
}

// Defining another middleware
let middleware3 = (req, res, next) => {
   console.log("Middleware 3 is running !");
}

// Creating the route page for all the middlewares
app.get("/", middleware1, middleware2, middleware3);

// Listening on the port:3000
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Output

C:\home\node>> node skipMiddleware.js
Server listening on PORT 3000
Middleware 1 is running !
Skipped middleware 2
Middleware 3 is running !
raja
Updated on 28-Mar-2022 14:50:14

Advertisements