How can I split my koa routes into separate files?


EDIT: I’ve updated the code examples below because the koa-router package on npm is no longer maintained. The Koa team has made an official fork of it under the name @koa/router.


For anyone reading this, who is curious on how to do this in Koa 2.X:

app.js

import Koa from 'koa'
import rootRouter from './routes/root'
import userRouter from './routes/user'

const app = new Koa()

app.use(rootRouter.routes())
app.use(rootRouter.allowedMethods())
app.use(userRouter.routes())
app.use(userRouter.allowedMethods())

export default app

routes/root.js

import Router from '@koa/router'
const router = new Router()

router.get("https://stackoverflow.com/", async (ctx, next) => {
  ctx.body = 'Hello'
})

export default router

routes/user.js

import Router from '@koa/router'
const router = new Router({ prefix: '/user' })

router.get("https://stackoverflow.com/", async (ctx, next) => {
  ctx.body = 'Some User'
})

export default router

If you want to avoid the repetition with the routes() and the allowedMethods(), you can use koa-compose to compose the middleware together. For simplicity, I made a wrapper around it to simplify working with koa-router. Using it would look something like this:

app.js

import Koa from 'koa'
import router from './routes'

const app = new Koa()

app.use(router())

export default app  

routes/index.js

import combineRouters from 'koa-combine-routers'
import rootRouter from './root'
import userRouter from './user'

const router = combineRouters(
  rootRouter,
  userRouter
)

export default router

And it would do the same thing.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)