Organizing Routes with express.Router

An express.Router holds one resource's routes in a file of its own, app.use("/games", gamesRouter) puts them under their path, and app.js exports the app while server.js starts it, so tests can use the app without a port.

Journeyman · Node.js · REST API · Updated

By

After this lesson you can

  • Group a resource's routes in an express.Router and mount it with app.use and a path
  • Split an Express app into route files, app.js and server.js, so tests can import the app without a port

Key takeaways

  • express.Router() makes a router, a small group of routes with the same methods as app, such as get, post and use.
  • app.use("/games", gamesRouter) mounts the router at /games, so its route "/:id" answers /games/3. Inside the router, paths leave out /games.
  • One router per resource, each in its own file under routes/, keeps app.js short and each resource's routes together.
  • app.js makes and exports the app with export const app = express(), and server.js imports it and calls app.listen. Tests import app.js and never start a server.

A real API has dozens of routes: products, orders, customers, reviews. Put them all in one file and finding the route you need means scrolling past every other one, and two people changing the file at once trip over each other. Every Express project you join splits its routes this way, so knowing the layout tells you where to look on your first day.

The Rolling Dice café's API now has three game routes, and the café wants a second resource: its tables, so customers can see which ones are free. A resource is one kind of thing an API lets you work with; here, games and tables.

A router for each resource

express.Router() makes a router: a small group of routes with the same methods as the app (get, post, use), which the app mounts under one path. Move the game routes into routes/games.js:

import express from "express";
import { games } from "../data/games.js";

export const gamesRouter = express.Router();

gamesRouter.get("/", (req, res) => {
  res.json(games);
});

gamesRouter.get("/:id", (req, res) => {
  const game = games.find((g) => g.id === Number(req.params.id));
  if (game === undefined) {
    res.status(404).json({ message: `There's no game ${req.params.id}.` });
    return;
  }
  res.json(game);
});

The POST route from Your First Express App: Routes and JSON moves in too, as gamesRouter.post("/", ...), and the games array moves to data/games.js, exported with export const games = [...]. Notice the paths: "/" and "/:id", with no /games. A router doesn't know where it will be mounted, so its paths start from wherever that is.

Mounting a router with app.use

app.js now makes the app and mounts each router at its path:

import express from "express";
import { gamesRouter } from "./routes/games.js";
import { tablesRouter } from "./routes/tables.js";

export const app = express();

app.use(express.json());
app.use("/games", gamesRouter);
app.use("/tables", tablesRouter);

app.use("/games", gamesRouter) reads "send every request whose path starts with /games to this router". The router sees the rest of the path, so /games/2 reaches its "/:id" route with req.params.id as "2". routes/tables.js has the same shape, with a tablesRouter and one route, tablesRouter.get("/", ...). Every address answers as before:

GET /games/2
HTTP/1.1 200 OK
{"id":2,"title":"Moon Mice","minPlayers":3,"maxPlayers":6,"minutes":20,"available":false}

GET /tables
HTTP/1.1 200 OK
[{"number":1,"seats":2,"bookedBy":null},{"number":2,"seats":4,"bookedBy":"Nadia"},{"number":3,"seats":6,"bookedBy":null}]

The mistake almost everyone makes once is writing the full path inside the router: gamesRouter.get("/games/:id", ...). Mounted at /games, that route answers /games/games/3, and GET /games/3 gets Express's Cannot GET /games/3. When a router's route never answers, check that its path leaves out the mount path.

A router has use too. gamesRouter.use(middleware) runs a middleware only for requests that reach the games router, such as a check that only staff may add games.

A file for each job

The café's project now looks like this:

rolling-dice/
  app.js            makes the app, adds middleware, mounts the routers
  server.js         starts the app with app.listen
  routes/
    games.js        every /games route
    tables.js       every /tables route
  data/
    games.js        the games array
    tables.js       the tables array
  cafe.http         requests to try with REST Client
  package.json

Each file has one job. A bug in looking up a game sends you to routes/games.js, and adding a third resource means a new router file and one more app.use line in app.js.

app.js and server.js

app.js exports the app and never calls listen. Starting the server is server.js's only job:

import { app } from "./app.js";

app.listen(3100, () => {
  console.log("The café's API is listening on http://localhost:3100");
});
The café's API is listening on http://localhost:3100

This is the split Routing by Hand, and Why Frameworks Exist made with node:http, and it pays off the same way. A test imports app from app.js and hands it requests directly, with no server running and no port to choose, so tests can't clash with a server you left running. This chapter's exercise is built this way: its tests import your app, and Testing an API with Supertest shows how to write tests like them.

Check yourself

2 questions to try on the lesson page.

So what

One router per resource, one file per router, and an app.js that only puts them together: that's the shape of nearly every Express project, so you'll know where to find any route, in your code or someone else's.

Key terms

Related