Express routing: matching requests by HTTP method and path
Routing selects a handler according to an HTTP method and URL path. In Express, connect methods and paths with calls such as `app.get()` and `app.post()`. You can group related routes in an `express.Router()` and mount that router under an application path. The examples here target Express 5.
Routing selects a handler according to an HTTP method and URL path. In Express, connect methods and paths with calls such as app.get() and app.post(). You can group related routes in an express.Router() and mount that router under an application path. The examples here target Express 5.
What determines which Express route is selected?
An Express route combines an HTTP method with a path. GET /items and POST /items use the same path but represent different requests. A method-specific registration such as app.get('/items', handler) runs its handler for a matching request. Paths can be strings or regular expressions. (Express: Routing)
The query string is not part of the route path, so /items?page=2 still matches /items. A named parameter such as :itemId captures one URL segment in req.params.itemId. That value is a string; validate its format and allowed range before using it as a number or passing it to a database lookup. (Express: Routing)
How are path parameters different from query strings?
Path parameters represent values in the URL structure, often a resource identifier. /items/42 matches /items/:itemId, and req.params.itemId is the string '42'. A query string is an optional condition after the path, as in /items?page=2. It does not change route matching, so treat pagination and sorting values as separate request input.
Declaring a route does not validate its inputs. Reject missing or malformed identifiers and unsupported page values in a handler or validation middleware, and return a status and body consistent with the service's error contract. (Express: Routing)
How can several HTTP methods share a resource path?
Registering method-specific handlers on one resource path separates the intent of each request. app.route('/items') declares the path once and chains .get(), .post(), and other methods, reducing repeated path strings and typos. Choose supported methods according to the API contract and resource behavior. (Express: Routing)
const express = require('express');
const app = express();
const itemsRouter = express.Router();
itemsRouter.get('/', (req, res) => {
res.json({ items: [] });
});
itemsRouter.get('/:itemId', (req, res) => {
const { itemId } = req.params;
res.json({ itemId });
});
itemsRouter.post('/', (req, res) => {
res.status(201).json({ created: true });
});
app.use('/api/items', itemsRouter);
app.listen(3000);This example illustrates route organization; it was not run or verified. In a project with Express 5 installed, it is written so that GET /api/items returns the sample list, GET /api/items/42 returns JSON containing the string identifier, and POST /api/items sends a 201 response. Real creation requires body parsing, input validation, persistence, and error responses, which are outside this example. (Express: Routing)
How do you organize routes with a Router?
express.Router() creates a mountable unit for routes. Define router.get() and router.post() in a feature module, then mount it with a path such as app.use('/api/items', itemsRouter). The router's / then corresponds to /api/items, while /:itemId corresponds to /api/items/:itemId. Router-specific middleware can also be registered with router.use(). (Express: Routing)
As routes grow, group them by feature or resource and check which routes receive shared authentication or authorization middleware. If a child router needs a parameter from its parent mount path, consult Express's mergeParams option. Parent path parameters are not available in child routes by default without that option. (Express: Routing)
What should you check when a route does not match or behaves unexpectedly?
Check that both the HTTP method and path match the declaration. The query string is not part of path matching.
Confirm that `:itemId` appears in `req.params`; validate its format and range because the value is a string.
Combine the router mount prefix with its internal path to determine the actual URL.
Check that each handler ends the response or passes control onward. If no route responds, inspect the later 404 or error flow.
For chained handlers, confirm that `next()` reaches the intended next handler and that branching happens only on the intended route.
Check path-pattern syntax for the Express major version in use. Express 5 uses `path-to-regexp` v8, so do not assume older string patterns can be copied unchanged. ([Express: Routing](https://expressjs.com/en/guide/routing/))