skip to content

REST API Patterns

Resource routers under a version prefix, validation middleware wrapping a schema, one response helper, honest status codes. Interviewers judge from these whether you designed an API or wired handlers.

on this pageshow

questions

6

In Express 5, how do you organise an orders API as one express.Router per resource, mounted under a /v1 prefix?

level: middleimportance: must knowfreq 70%

answer

  1. a mini-app per resource
  2. paths relative to the mount
  3. one version router, mounted once
  4. req.baseUrl holds the mount path

basics

~20 s

Give each resource its own express.Router with paths relative to its mount, mount those routers on a v1 router, and mount that once with app.use('/v1', v1), so each prefix is written in exactly one place.

solid answer

~40 s

I create one module per resource that builds an `express.Router()`, declares its routes relative to the mount (`'/'`, `'/:id'`) and exports the router. A version router mounts them — `v1.use('/orders', orders)`, `v1.use('/customers', customers)` — and `app.js` mounts that once with `app.use('/v1', v1)`. Express strips the mount path before the router matches, so inside the orders router `req.baseUrl` is `/v1/orders`, `req.url` is the remainder and `req.originalUrl` is the full path. Middleware added with `orders.use()` runs only for requests that reach that router, so per-resource auth stays local. The payoff is that the version prefix and each resource path are written exactly once, and a router module can be mounted again elsewhere without editing its routes.

code

javascript · 23 lines
javascript
const express = require('express');

// orders.routes.js: paths are relative to wherever the router is mounted
const orders = express.Router();
orders.get('/', (req, res) => res.json({ baseUrl: req.baseUrl, url: req.url }));
orders.get('/:id', (req, res) => res.json({ id: req.params.id }));

// customers.routes.js
const customers = express.Router();
customers.get('/', (req, res) => res.json([]));

// v1.js: the version prefix is written once
const v1 = express.Router();
v1.use('/orders', orders);
v1.use('/customers', customers);

// app.js
const app = express();
app.use(express.json());
app.use('/v1', v1);

module.exports = app;
// GET /v1/orders?page=2 -> {"baseUrl":"/v1/orders","url":"/?page=2"}

go deeper

for a junior

Know that express.Router creates a mountable set of routes, that app.use mounts it at a path, and that the router's own paths leave the mount path out.

for a middle

Explain how Express strips the mount path, what req.baseUrl, req.url and req.originalUrl hold inside a mounted router, and why router.use middleware stays local to that router.

for a senior

Show you can debug a route that 404s because its prefix is repeated, order literal routes before parameter routes, and build self-referencing URLs from req.baseUrl so routers can be remounted.

for a principal

Be ready to say how a one-router-per-resource layout scales across teams: who owns the version router, how routers are reused between versions, and when nesting routers costs more than it saves.

## What a resource router is `express.Router()` returns a **router**: an object that the Express documentation calls a complete middleware and routing system, often described as a *mini-app*. It has the same registration methods as the application — `router.get`, `router.post`, `router.use`, `router.route` — but no settings and no server of its own. A router does nothing until it is **mounted** on the app (or on another router) with `use()`. The REST pattern is to give **each resource its own router module**: - `orders.routes.js` creates `const orders = express.Router()`, declares the order routes and exports `orders`. - `customers.routes.js` does the same for customers. - A small version module creates a `v1` router and mounts each resource router on it. - `app.js` mounts the version router once, with `app.use('/v1', v1)`. ## Paths are relative to the mount When a request reaches a mounted router, Express **removes the mount path** before the router tries to match. A router mounted at `/v1/orders` therefore declares `'/'` and `'/:id'`, not `'/v1/orders/:id'`. Writing the full path inside the router is the classic mistake: the router would only match `/v1/orders/v1/orders/7`, so a request for `/v1/orders/7` falls through every layer and ends as a 404. Three request properties show what was stripped. For `GET /v1/orders/7?page=2` handled inside the orders router: | Property | Value | Meaning | |---|---|---| | `req.originalUrl` | `/v1/orders/7?page=2` | the URL as the client sent it | | `req.baseUrl` | `/v1/orders` | every mount path the request passed through | | `req.url` | `/7?page=2` | what is left for this router to match | | `req.params.id` | `'7'` | the parameter the route declared | `req.baseUrl` is also the right input when a route must build a URL to itself — for example the `Location` header of a create response — because it stays correct if the router is mounted somewhere else. ## Why mount through a version router Mounting resource routers on a `v1` router, rather than calling `app.use('/v1/orders', orders)` for each one, gives the prefix a single home: 1. The string `/v1` appears once, in `app.js`. 2. The version router is the natural place for things that apply to the whole version but not to the rest of the app, such as a JSON not-found handler at the end of its stack. 3. A resource router can be mounted again under another prefix without edits, because none of its paths mention the version. How many versions to run, and whether the version belongs in the path at all, is an API-design decision covered with REST versioning; this pattern is only how an Express app wires whichever answer was chosen. ## Router-level middleware stays local `orders.use(requireAuth)` registers middleware **inside** the orders router. It runs only for requests that reach that router, and only ahead of the routes declared after it, because Express walks a router's stack in registration order. The same rule decides which route answers: the first registered route that matches wins, so a literal path such as `'/summary'` must be declared before `'/:id'` or `'/:id'` captures it. ## Things that go wrong - **Repeating the prefix** inside the router: the route never matches and the request 404s. - **Reading `req.url`** in a mounted router and expecting the full path; use `req.originalUrl`. - **Nested resources** such as `/orders/:orderId/items`: a child router does not see the parent's `:orderId` unless it is created with `express.Router({ mergeParams: true })` — the option belongs to Express's router API and is covered with routing. - **Mount order**: the body parser has to run before any route that reads a body — on the app ahead of the version router, or inside the router — or `req.body` is `undefined` in Express 5 handlers. - **One giant router** for every resource: it works, but every change touches the same file and the per-resource middleware stops being local. ## Grouping one path's verbs Inside a resource router, `orders.route('/:id')` returns a route object on which `.get()`, `.patch()` and `.delete()` chain, so the handlers for one URL sit together and the path string is written once. It is purely a registration convenience: Express builds the same layers as three separate `orders.get('/:id')`-style calls, and match order still follows registration order. Keeping each resource module to its own routes, with shared concerns such as authentication added by `orders.use()` at the top of the file, makes the module readable on its own. The result is an app file that reads like a table of contents — parsers, the version router, the not-found handler, the error handler — and resource modules that know nothing about where they are mounted.

  • How would you expose the same orders router under /v2 while a few of its routes change?
    Because its paths are relative, the module mounts again unchanged: `v2.use('/orders', orders)`. For the routes that change, mount a small v2 orders router first, `v2.use('/orders', v2Orders)`, then the shared one. Express tries layers in registration order, so a v2 route answers when it matches and everything else falls through to the shared router. Whether to version this way is an API-design question.
  • What changes for a nested resource such as /v1/orders/:orderId/items?
    Mount an items router at `'/:orderId/items'` inside the orders router. By default a child router does not see its parent's route parameters, so `req.params.orderId` is undefined in the items handlers; create the child with `express.Router({ mergeParams: true })` to keep them. Keep nesting shallow, since each level adds a mount path to `req.baseUrl`.

A version router is like a building directory: the lobby sends you to floor 1, the floor sign sends you to Orders, and inside Orders the rooms are numbered without repeating the floor or the department.

  • Repeating the full /v1/orders path inside the router mounted at /v1/orders.
  • Thinking middleware added with router.use runs for every request in the app.
  • Reading req.url inside a mounted router and expecting the full original path.
  • Writing the /v1 prefix into every route string instead of mounting it once.
  • Assuming the order routes are declared in has no effect on which one answers.
open as a page

In Express 5, how do you write a reusable validation middleware that wraps a schema and keeps invalid input away from route handlers?

level: middleimportance: must knowfreq 65%

basics

~20 s

Write a factory that takes a schema and returns (req, res, next) middleware: parse the input, stop with a 400 or next(err) on failure, store the parsed result and call next() on success, mounted after express.json and before the handler.

open as a page

In an Express 5 JSON API, why does an unmatched route return an HTML 'Cannot GET' page, and how do you send a JSON 404?

level: juniorimportance: should knowfreq 55%

basics

~10 s

When no middleware or route responds, Express's final handler sends a 404 HTML page reading Cannot GET /path. Register app.use((req, res) => res.status(404).json(...)) after every router so unmatched requests get JSON.

open as a page

In Express 5, how do you send 201 with a Location header on create and 204 on delete, and what do response helpers add?

level: middleimportance: should knowfreq 50%

basics

~10 s

Chain the status before the body: res.status(201).location(url).json(order) on create, res.sendStatus(204) or res.status(204).end() on delete. A helper fixes each pairing once, so no route forgets the Location header or sends a body with 204.

open as a page

After an Express 5 upgrade, a validation middleware running req.query = schema.parse(req.query) throws a TypeError; where should the validated query live, and what must its schema expect?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Leave req.query as the raw parse, since Express 5 made it read-only, and have the middleware write the validated result to a property it owns, such as req.valid.query, with a schema that coerces the strings the query string arrives as.

open as a page

As the lead standardising Express 5 services, what house layout would you mandate for resource routers, validation middleware and response helpers, and what does it cost?

level: principalimportance: should knowfreq 25%

basics

~20 s

Mandate one router module per resource, a fixed app.js order, one shared validation factory that stores parsed input in one named place, and thin response helpers; the cost is a shared package every service must keep upgraded.

open as a page