Search code examples
node.jskoakoa-router

Define koa-router nested routes w/ prefixes


I'm trying to define different routes using koa-router and I'm having a hellova time getting it working.

Something like this:

const apiRouter = new KoaRouter({
  prefix: '/api'
})
.use(bodyParser)
.post('/sign-in', signinMiddleware)
.get('auth-check', authCheckMiddleware)

const protectedApisRouter = new KoaRouter()
.use(authorizeMiddleware)
.get('/widgets', getWidgetsListMiddleware)
.post('/widgets', createWidgetMiddleware)
.get('/widgets/:widgetId', getWidgetByIdMiddleware)
.patch('/widgets/:widgetId', updateWidgetMiddleware)


apiRouter.use(
  prodectedApisRouter.routes(),
  prodectedApisRouter.allowedMethods()
)

koaApp.use(apiRouter.routes())
koaApp.use(apiRouter.allowedMethods())
 

I would expect that an requests to /api/widgets/* SHOULD enter into their respective middleware, after the bodyParser and authorizeMiddleware middleware` run, based on the documentation here: https://github.com/alexmingoia/koa-router#nested-routers

But instead, I'm getting 404's for all of those routes. What am I doing wrong?


Solution

  • Apparently the above code works just fine.. but in my authorizeMiddleware I was doing await next instead of await next() 🤦

    Too bad there isn't a way to delete questions on here.. people are now gonna come here for issues not related to my idiocy.