Routing
🎯 Introduction
By the end of this article, you will be able to add routing to a Koa application, give GET /users and POST /users separate responsibilities, read dynamic path parameters, and manage routes in separate files. Koa does not include routing, so we will add it here.
🧱 Install @koa/router
As discussed earlier, Koa has a minimal core. The official @koa/router package provides routing. This article was written and verified with Node.js v22 LTS + @koa/router 15.7.0.
npm install @koa/router
There are three basic steps: create a router instance, define routes, and register the router as middleware:
import Koa from 'koa';
import Router from '@koa/router';
const app = new Koa();
const router = new Router();
router.get('/', async (ctx) => {
ctx.body = 'Home page';
});
router.get('/about', async (ctx) => {
ctx.body = 'About page';
});
// Register the router with the application
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
Visiting / and /about now returns different content, while other paths return 404. The router.get() syntax is almost identical to Express routing; the callback receives (ctx) instead of (req, res).
🛠 Common HTTP Methods
RESTful APIs distinguish between HTTP methods. @koa/router supports them all:
router.get('/users', async (ctx) => {
ctx.body = 'Get users';
});
router.post('/users', async (ctx) => {
ctx.body = 'Create user';
});
router.put('/users/1', async (ctx) => {
ctx.body = 'Update user';
});
router.delete('/users/1', async (ctx) => {
ctx.body = 'Delete user';
});
Using the same path with different methods is a standard RESTful API pattern. You can test requests in a browser or an API client; the address bar sends GET requests. Use a tool such as Apifox or Postman for DELETE, POST, and PUT requests.
🧱 Route Parameters and Query Parameters
Route parameters are dynamic parts of the path. Define them with :parameterName and read them through ctx.params:
router.get('/users/:id', async (ctx) => {
const id = ctx.params.id; // For /users/42, id is '42'
ctx.body = { id, name: 'Alex' };
});
Query parameters appear after ?. Read them through ctx.query, as introduced earlier:
router.get('/users', async (ctx) => {
// Visit /users?page=2&size=10
const { page, size } = ctx.query;
ctx.body = { page, size };
});
ctx.params reads values from the path (/users/:id), while ctx.query reads values after the question mark (?page=2). These values are strings, so convert them when you need numbers.💡 What Does allowedMethods Do?
The line app.use(router.allowedMethods()) serves two purposes:
- More precise status codes: If a path exists but the method is wrong (for example,
POST /userswhen onlyGET /usersis defined), it returns 405 Method Not Allowed instead of 404, telling the client that the path exists but the method is unsupported. - Automatic OPTIONS responses: For OPTIONS requests, including those used in browser CORS preflights, it reports the methods supported by the path.
Adding it makes your API's responses to unsupported requests more consistent with HTTP semantics. Include it whenever you register a router.
🧰 Organize Routes into Modules
Keeping every route in app.js becomes difficult to maintain as a project grows. In practice, routes for different modules belong in separate files:
import Router from '@koa/router';
const router = new Router({
prefix: '/users', // Automatically prepend /users to the routes below
});
router.get('/', async (ctx) => {
ctx.body = 'User list';
});
router.get('/:id', async (ctx) => {
ctx.body = `User details: ${ctx.params.id}`;
});
export default router;
Import and register the router in the entry file:
import Koa from 'koa';
import usersRouter from './routes/users.js';
const app = new Koa();
app.use(usersRouter.routes());
app.use(usersRouter.allowedMethods());
app.listen(3000);
With prefix: '/users', router.get('/') matches /users, while router.get('/:id') matches paths such as /users/1. A router file for each application module keeps the structure clear, using the same approach as express.Router() in Express.
❓ Questions and Answers
Q1: Does the order of route definitions matter?
Yes. @koa/router matches routes in registration order, so earlier matches take precedence. Define /users/new before /users/:id; otherwise, new can be treated as the id parameter.
Q2: Can one route handle multiple methods?
Yes, but that is not the usual approach. For RESTful APIs, define a separate route for each method to keep the logic clear.
Q3: Is ctx.params.id a number?
No, it is a string because paths are text. Use Number(ctx.params.id) if you need a number, and remember to handle NaN.
Q4: What happens if I forget allowedMethods?
Your endpoints still work, but unsupported methods return 404 instead of 405, and OPTIONS requests are not handled automatically. Make a habit of registering both middleware functions.
🧪 Practice
- Create
routes/articles.jswith two endpoints:GET /articlesreturns a list of articles (mock data is fine), andGET /articles/:idreturns the article with the specified id. Register the router inapp.js.
import Router from '@koa/router';
const router = new Router({ prefix: '/articles' });
// Write your code here
export default router;
- Visit
/articlesand/articles/1in your browser and confirm that both routes respond correctly.
🎉 Your Koa application now has routing! Next, we will tackle two practical tasks: parsing request bodies from the frontend and handling API errors gracefully.
