How to skip a middleware in Express.js ?
If we want to skip a middleware we can pass parameters to the middleware function and decide based on that parameter which middleware to call and which middleware to not call.
Prerequisite:
- express.js: To handle routing.
Setting up environment and execution:
-
Step 1: Initialize node project
npm init
-
Step 2: Install required modules
npm install express
Example:
index.js
const express = require( "express" ); // const database = require('./sqlConnection'); const app = express(); // Start server on port 5000 app.listen(5000, () => { console.log(`Server is up and running on 5000 ...`); }); // define middleware 1 let middleware1 = (req, res, next) => { // decide a parameter req.shouldRunMiddleware2 = false ; console.log( "Middleware 1 is running !" ); next(); } // define middleware 2 let middleware2 = (req, res, next) => { if (!req.shouldRunMiddleware2) { console.log( "Skipped middleware 2" ); return next(); } console.log( "Middleware 2 is running !" ); } // define middleware 3 let middleware3 = (req, res, next) => { console.log( "Middleware 3 is running !" ); } // create route for home page '/' app.get( "/" , middleware1, middleware2, middleware3); |
Output: Run the below command to start the server. After that go to http://localhost:5000 on browser to see output in console
node index.js
- In browser.
- Console:
Contact Us