Routes, parameters and routers
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.
Path parameters
A segment starting with : is a parameter. Express captures whatever is in that position:
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:
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:
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:
// 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:
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
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:
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:
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:
// 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);// 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:
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:
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:
coursesRouter.get('/featured', getFeatured); // ✓ first
coursesRouter.get('/:id', getCourse); // otherwise 'featured' would be treated as an idA good structure: one router file per resource (
courses.js,users.js,orders.js), mounted inapp.js. Anyone can find the code for an endpoint by looking at its URL.
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.
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(/* … */);import { Router } from 'express';
export const lessonsRouter = Router({ mergeParams: true });
lessonsRouter.get('/', (req, res) => {
const search = String(req.query.search ?? '').toLowerCase();
const result = lessons.filter(
(l) => l.courseId === req.params.courseId && l.title.toLowerCase().includes(search),
);
res.json(result);
});
lessonsRouter.get('/:lessonId', (req, res) => {
const lesson = lessons.find(
(l) => l.courseId === req.params.courseId && l.id === req.params.lessonId,
);
if (!lesson) return res.status(404).json({ error: 'Lesson not found' });
res.json(lesson);
});
// app.js
// app.use('/courses/:courseId/lessons', lessonsRouter);Summary
:namesegments becomereq.params.name; query strings becomereq.query— both are always strings.- JSON bodies arrive in
req.bodyonceexpress.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 withapp.use(prefix, router).- Use
mergeParams: truewhen a nested router needs its parent’s parameters.