temporary_user_name
temporary_user_name

Reputation: 37058

Confusion over middleware ordering in express.js?

As I understand things, calling app.use on a piece of middleware before a route declaration such as app.get('/hello') causes that middleware to be run on a request before it reaches that routing function. My confusion arises when you have a situation with at least three routes and three pieces of middleware, and you want things set up like this:

I am of course missing something, since my current understanding renders such a setup impossible. There is no way to order the statements in the code which would allow such a configuration.

How can this be done? What am I missing?

Upvotes: 0

Views: 27

Answers (1)

David Stenstrøm
David Stenstrøm

Reputation: 783

This should be easy enough to accomplish. Set it up like this

app.use('/route1', middlewareA, middlewareB, (req, res, next) => {})
app.use('/route2', middlewareB, middlewareC, (req, res, next) => {})
app.use('/route3', middlewareA, middlewareC, (req, res, next) => {})

When you define the routes like this, the middleware is only applied to the specific route. If you do it like app.use(middlewareA) then the middleware is used in all routes after it.

Upvotes: 1

Related Questions