I had the same questions of why we need to use koa-compose, since koa itself can handle multiple middlewares. But recently I have been working on the authentication part of my koa server.
I have to check if user is authenticated and sometimes I need to check if user role meets the requirement. In that case, I have two middlewares one is called isAuthenticated
, another is hasRoles
Some routes expose to any user that is authenticated, so I can do
.get('/', auth.isAuthenticated, handler())
But for routes need to check if user role meets the requirement, I need to do
.get('/', auth.isAuthenticated, auth.hasRole('admin'), handler())
When I have other authentication middlewares, the middlewares I put in the route becomes pretty long.
I am benefited by using koa-compose, since in my case I can chain the isAuthenticated
and hasRoles
middlewares together.
requiresRole(role) {
return compose([isAuthenticated, hasRole(role)])
}
.get('/', auth.requiresRole('admin'), handler())
It's neat and less errors.