Currently, Polka only allows 1 handler per route pattern. Express, on the other hand, allows you to assign as many as you want, constructing per-route middleware groups.
// no auth
app.get('/items', noop);
// require auth for posting
app.post('/items', authenticate, noop);
// no auth again
app.get('/items/:id', noop);
This is still a _maybe_ as it would require changes to Trouter. Speed is still the #1 priority, and you can already achieve similar behavior by manually calling middleware from within the single handler.
Current "workaround"
function authenticate(req, res, next) {
let token = req.headers.authorization;
if (!token) return res.end('Token required!');
// If used as middleware, iterate
// But if not in loop, return "success" boolean
return next ? next() : true;
}
// later, in app...
app.post('/items', (req, res) => {
let isUser = authenticate(req, res); // <~ no next()
if (!isUser) return; // already sent `res.end` before
// Continue with route handler
let body = req.body;
// ...
});
I think your current work around is cool.. Probably using the current workaround will be okay so far it doesn't affect the speed of polka.
I'm strongly in favor of per route middleware. I just faced a case when I need to use different body-parser options for each route. I had to workaround it like shown in the example in docs (pathname.startsWith etc). but that's really not a pretty solution in my opinion.
@plakak I hear ya. Still deciding. Please remember that you can can attach a global middleware that specifies which parser to use based on Content-Type. This is how that body-parser package works in the first place~!
Most helpful comment
I think your current work around is cool.. Probably using the current workaround will be okay so far it doesn't affect the speed of polka.