Holis
Holis

Reputation: 215

Express - using application-level middleware conditionally on route-level

I'm trying to understand how to use an application-level middleware (or at least usually used like this) like cookie-parser on route-level and conditionally.

I tried something like:

const myMiddleware = (req, res, next) => {
 if (myCondition) {
   return cookieParser();
 } else {
   next();
 }
}

app.use('/admin', myMiddleware, (req, res) => {
 res.sendStatus(401)
})

But it's not working, the request will be just stuck.

Is this possible?

Traditional cookie-parser implementation:

app.use(cookieParser())

Upvotes: 0

Views: 498

Answers (1)

cbr
cbr

Reputation: 13662

cookieParser() returns a middleware function, i.e. a function that takes in req, res, next as arguments. You just have to pass it the arguments:

const cookieParserMiddleware = cookieParser();

const myMiddleware = (req, res, next) => {
  if (myCondition) {
    return cookieParserMiddleware(req, res, next);
  }

  next();
};

app.use("/admin", myMiddleware, (req, res) => {
  res.sendStatus(401);
});

Notice that I'm creating the cookieParser middleware outside myMiddleware - technically we could also just do return cookieParser()(req, res, next) but recreating the same middleware again and again on every request would be wasteful.

I've also removed the else since the if block returns from the function (guard clause).

Upvotes: 1

Related Questions