Is there a canonical way to remove middleware added with app.use
from the stack? It seems that it should be possible to just modify the app.stack
array directly, but I am wondering if there is a documented method I should be considering first.
Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next function in the application's request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
Express middleware are functions that execute during the lifecycle of a request to the Express server. Each middleware has access to the HTTP request and response for each route (or path) it's attached to. In fact, Express itself is compromised wholly of middleware functions.
use
actually comes from Connect (not Express), and all it really does is push the middleware function onto the app's stack
.
So you should be just fine splicing the function out of the array.
However, keep in mind there is no documentation around app.stack
nor is there a function to remove middleware. You run the risk of a future version of Connect making changes incompatible with your code.
There seems to be no built in way to do that, but you can manage to get the same result with a small trick. Create your own array of middleware (let's call it dynamicMiddleware
) but don't push that into express, instead push just 1 middleware that will execute all the handlers in dynamicMiddleware
asynchronously and in order.
const async = require('async') // Middleware const m1 = (req, res, next) => { // do something here next(); } const m2 = (req, res, next) => { // do something here next(); } const m3 = (req, res, next) => { // do something here next(); } let dynamicMiddleware = [m1, m2, m3] app.use((req, res, next) => { // execute async handlers one by one async.eachSeries( // array to iterate over dynamicMiddleware, // iteration function (handler, callback) => { // call handler with req, res, and callback as next handler(req, res, callback) }, // final callback (err) => { if( err ) { // handle error as needed } else { // call next middleware next() } } ); })
The code is a bit rough as I don't have a chance to test it right now, but the idea should be clear: wrap all dynamic handlers array in 1 middleware, that will loop through the array. And as you add or remove handlers to the array, only the ones left in the array will be called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With