Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

234
Views
How to optimize router in nodejs koa?

I use koa to create a nodejs application, and I try to optimize.

app.js

'use strict';
const Koa = require("koa");
const app = new Koa();
const Router = require("koa-router");
const router = new Router();

const stuff = require("./router/stuff.js");
router.use("/stuff", stuff.routes());
//more routers like above
const home = require("./router/home.js");
router.use(home.routes());

app.use(router.routes(), router.allowedMethods());
app.listen(port);

There're some router files in folder router, such as stuff.js, home.js, client.js

stuff.js

'use strict';
const router = require("koa-router")();
router
    .get("/", async (ctx) => {
        await ctx.render("stuff", {

        });
    })
module.exports = router;

home.js

'use strict';
const router = require("koa-router")();
router
    .get("/", async (ctx) => {
        await ctx.render("home", {

        });
    })
module.exports = router;

client.js

'use strict';
const router = require("koa-router")();
router
    .get("/", async (ctx) => {
        await ctx.render("client", {

        });
    })
module.exports = router;

I think the way I wrote is still very amateurish, how to optimize it? Thank you.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

After researching, I am using the following solution

app.js

'use strict';
const Koa = require("koa");
const app = new Koa();
const router = require("./router");
router(app);
app.listen(port);

in folder router, add index.js with following code

'use strict';
const fs = require('fs');
module.exports = (app) => {
  fs.readdirSync(__dirname).forEach(file => {
    if (file === 'index.js') { return; }
    const route = require(`./${file}`);
    app.use(route.routes()).use(route.allowedMethods());
  });
}

Other router files are the same, e.g. home.js

'use strict';
const router = require("koa-router")();
router
    .get("/", async (ctx) => {
        await ctx.render("home", {

        });
    })
module.exports = router;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!