Skip to content

How can I combine multiple middlewares into one? #5213

Answered by krzysdz
sadeghhosseini asked this question in Q&A
Discussion options

You must be logged in to vote

Your usage of connect is very similar to creating a Router or even express() app, since connect also is an extensible HTTP server framework, so you could probably use that if you don't want additional dependencies.

You could also use next('route') or next('router') to (conditionally) skip some middleware or whole router. This however won't let you run it inside other middleware - only before or after.

const skippedSym = Symbol('skipped1');
function skipRandom(req, res, next) {
    if (Math.random() < 0.5) {
        req[skippedSym] = true;
        next('route');
    } else {
        next();
    }
}
function skipNotSkipped(req, res, next) {
    if (req[skippedSym]) { next(); }
    else { next 

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@sadeghhosseini
Comment options

@krzysdz
Comment options

Answer selected by sadeghhosseini
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants