Routes, parameters and routers

Topic 2 of 4 in Express7 min readIntermediateFree course

Overview

A request carries information in several places: the path, the query string, the headers and the body. Express parses each into a property on req. This topic shows where each piece lands, how to write route paths, and how to split a growing app into tidy, separate route files.

For PATCH /courses/42/lessons/7?notify=true: req.method is ‘PATCH’; req.params is { courseId: ‘42’, lessonId: ‘7’ }; req.query is { notify: ‘true’ }; req.body holds the JSON body once express.json() has run; req.get(‘Authorization’) reads a header. The route is app.patch(‘/courses/:courseId/lessons/:lessonId’, handler), and every param and query value is a string.

Path parameters

A segment starting with : is a parameter. Express captures whatever is in that position:

JavaScript
app.get('/courses/:courseId/lessons/:lessonId', (req, res) => {
  const { courseId, lessonId } = req.params;
  res.json({ courseId, lessonId });
});
// GET /courses/node/lessons/7 → { "courseId": "node", "lessonId": "7" }

Parameters are always strings. Convert and check them before using them:

JavaScript
app.get('/orders/:id', async (req, res) => {
  const id = Number(req.params.id);
  if (!Number.isInteger(id) || id <= 0) {
    return res.status(400).json({ error: 'Order id must be a positive whole number' });
  }
  // …
});

In the next chapter you’ll validate all of this cleanly with a schema.

Optional parts and wildcards (Express 5)

Express 5 uses a stricter, clearer path syntax than Express 4:

JavaScript
app.get('/files/:name{.:ext}', handler);  // /files/report and /files/report.pdf
app.get('/docs/*splat', handler);         // any depth: req.params.splat is ['guide', 'intro']
app.get('/{*splat}', handler);            // match everything, including '/'

If you see app.get('*', …) or /:id? in older code, those are Express 4 patterns; Express 5 needs the named and braced forms above.

Query strings

Everything after ? is parsed into req.query:

JavaScript
// GET /courses?level=beginner&page=2
app.get('/courses', (req, res) => {
  const level = req.query.level;              // 'beginner'
  const page = Number(req.query.page ?? 1);   // 2
  const limit = Math.min(Number(req.query.limit ?? 20), 100);
  // …
});

Query values are strings too (or missing). A parameter repeated in the URL, like ?tag=js&tag=node, gives an array — so code that expects one string should check. Use the query string for optional things such as filtering, sorting, searching and pagination; use the path for identity (which resource).

The request body

With express.json() registered, a JSON request body becomes req.body:

JavaScript
app.use(express.json());

app.post('/courses', (req, res) => {
  const { title, level } = req.body;
  // …create and respond with 201
});

For HTML form posts (application/x-www-form-urlencoded), add express.urlencoded(). File uploads need a different parser — see File uploads.

Never trust req.body. It’s whatever the client chose to send — missing fields, wrong types, extra fields you didn’t expect, or very long strings. Validating input shows how to check it properly.

Headers

JavaScript
req.get('Authorization');   // case-insensitive header lookup
req.headers['user-agent'];
req.ip;                      // client IP (see 'trust proxy' in production)
req.is('application/json');  // does the body have this content type?

Route handler chains

A route can have several handlers. Each calls next() to pass control on — this is how per-route middleware like authentication works:

JavaScript
app.delete('/courses/:id', requireAuth, requireRole('admin'), async (req, res) => {
  await deleteCourse(req.params.id);
  res.sendStatus(204);
});

app.route() groups the methods for one path:

JavaScript
app.route('/courses/:id')
  .get(getCourse)
  .patch(updateCourse)
  .delete(deleteCourse);

Routers: splitting the app

Putting every route in app.js quickly becomes a thousand-line file. An express.Router is a mini-app for one area of your API:

JavaScript
// src/routes/courses.js
import { Router } from 'express';

export const coursesRouter = Router();

coursesRouter.get('/', listCourses);          // GET /courses
coursesRouter.post('/', createCourse);        // POST /courses
coursesRouter.get('/:id', getCourse);         // GET /courses/:id
coursesRouter.patch('/:id', updateCourse);
coursesRouter.delete('/:id', deleteCourse);
JavaScript
// src/app.js
import { coursesRouter } from './routes/courses.js';
import { usersRouter } from './routes/users.js';

app.use('/courses', coursesRouter);
app.use('/users', usersRouter);

Paths inside the router are relative to where it’s mounted. Routers can have their own middleware (coursesRouter.use(requireAuth)), which applies only to their routes.

Nested routers

Lessons belong to courses: /courses/:courseId/lessons/:lessonId. A lessons router mounted under that path needs to read courseId, which belongs to the parent path. Pass mergeParams: true:

JavaScript
export const lessonsRouter = Router({ mergeParams: true });
lessonsRouter.get('/', (req, res) => {
  res.json(findLessons(req.params.courseId)); // available thanks to mergeParams
});

app.use('/courses/:courseId/lessons', lessonsRouter);

Versioning

Prefix your routes with a version so you can make breaking changes later without breaking existing clients:

JavaScript
const v1 = Router();
v1.use('/courses', coursesRouter);
v1.use('/users', usersRouter);
app.use('/api/v1', v1);

Route order

Express checks routes top to bottom. Define specific routes before ones with parameters, or the parameter route will catch them:

JavaScript
coursesRouter.get('/featured', getFeatured);  // ✓ first
coursesRouter.get('/:id', getCourse);         // otherwise 'featured' would be treated as an id

A good structure: one router file per resource (courses.js, users.js, orders.js), mounted in app.js. Anyone can find the code for an endpoint by looking at its URL.

Exercise

A lessons router

Create routes/lessons.js with an Express Router mounted at /courses/:courseId/lessons. Support GET / (list lessons for the course, optional ?search= filter) and GET /:lessonId. Use mergeParams so the router can read courseId.

JavaScript
import { Router } from 'express';

const lessons = [
  { id: '1', courseId: 'node', title: 'Introduction' },
  { id: '2', courseId: 'node', title: 'Streams' },
  { id: '3', courseId: 'js', title: 'Closures' },
];

export const lessonsRouter = Router(/* … */);

Summary

  • :name segments become req.params.name; query strings become req.query — both are always strings.
  • JSON bodies arrive in req.body once express.json() is registered.
  • Express 5 wildcards are named (/*splat) and optional parts use braces (/:file{.:ext}).
  • express.Router() groups related routes in their own module; mount them with app.use(prefix, router).
  • Use mergeParams: true when a nested router needs its parent’s parameters.