Search code examples
node.jskoakoa-router

How can I split my koa routes into separate files?


I'm trying to figure out how to split my routes into separate files.

I have this so far, but it doesn't work. I just get Not found when I try to access http://localhost:3001/api/things

//server.js
var koa = require('koa');
var app = koa();
var router = require('koa-router');

app.use(router(app));
require('./routes')(app);


// routes.js
module.exports = function *(app){
  app.use('/api/things', require('./api/things'));
};


// api/things/index.js

var Router = require('koa-router');
var router = new Router({
  prefix: '/api/things'
});

router.get('/', function *(){
  this.body = [{ name: 'Foo'}, { name: 'Bar' }];
});

module.exports = router;

Solution


  • 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('/', 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('/', 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.