express icon indicating copy to clipboard operation
express copied to clipboard

Middleware for router at mount

Open seth-admittedly opened this issue 12 years ago • 4 comments

It would be helpful to be able to chain middleware at the time a router is mounted to an application.

app.use("/admin", ensureLogin.ensureLoggedIn("/login"), adminRouter);

rather than having to attach the middleware to the router like so

adminRouter.use(ensureLogin.ensureLoggedIn("/login"), ensureLogin.ensureIsAdmin("/home"));

With the former, the mounting application can assign middleware to be executed for a given router, while the latter means the router needs to be aware of which particular middleware is needed by the application.

seth-admittedly avatar Apr 29 '14 18:04 seth-admittedly

I disagree. I think it makes more sense to have your admin router use the middleware it requires to function. Alternatively you can just use multiple .use calls. I dislike the pattern of passing middleware after middleware args type of API.

defunctzombie avatar Apr 29 '14 18:04 defunctzombie

.use calls won't work because they'll apply to all later middleware. If the router is responsible for applying all middleware, then every router has to be aware of application-wide issues like authentication and caching. It seems much more elegant for the application to handle these pieces of middleware and assign them as appropriate to each router.

seth-admittedly avatar Apr 29 '14 18:04 seth-admittedly

app.use("/admin", ensureLogin.ensureLoggedIn("/login"));
app.use("/admin", adminRouter);

Does that not do what you want?

defunctzombie avatar Apr 29 '14 18:04 defunctzombie

Ah, I see how that works. Yes, I think it will, thanks. :+1:

seth-admittedly avatar Apr 29 '14 18:04 seth-admittedly