Routing
Mapping URLs and HTTP methods to handler functions - route parameters, query strings, route chaining, and the Router class for organizing larger apps.
What it is, in plain English: Routing in Express means defining which function runs for a given combination of HTTP method (GET, POST, PUT, DELETE...) and URL path. Routes are defined with app.get(), app.post(), etc, each taking a path pattern and a handler function. Dynamic segments in the path (like /users/:id) become available as req.params. The Router class lets you group related routes into separate, mountable modules -- essential for any app with more than a handful of routes.
Mapping URLs to handler functions
The basic pattern -- method + path + handler
app.get("/products", (req, res) => {
res.json(["Apple", "Banana", "Cherry"]);
});
app.post("/products", (req, res) => {
// handle creating a new product
res.status(201).json({ created: true });
});
app.put("/products/:id", (req, res) => { /* update */ });
app.delete("/products/:id", (req, res) => { /* delete */ });
// One method per HTTP verb: app.get, app.post, app.put, app.patch, app.delete
// app.all() matches ANY method (rarely needed)Route parameters -- capturing parts of the URL
// :id is a named parameter -- matches anything in that position:
app.get("/users/:id", (req, res) => {
console.log(req.params.id); // whatever was in the URL
res.send(`User: ${req.params.id}`);
});
// GET /users/42 --> req.params = { id: "42" }
// GET /users/abc --> req.params = { id: "abc" }
// Multiple parameters in one route:
app.get("/users/:userId/posts/:postId", (req, res) => {
const { userId, postId } = req.params;
res.json({ userId, postId });
});
// GET /users/42/posts/7 --> { userId: "42", postId: "7" }Query strings -- the part after ?
// Query strings are NOT part of the route pattern -- read via req.query:
app.get("/search", (req, res) => {
const { q, sort } = req.query;
res.json({ searchTerm: q, sortBy: sort });
});
// GET /search?q=shoes&sort=price
// --> req.query = { q: "shoes", sort: "price" }
// Always provide defaults for optional query params:
app.get("/products", (req, res) => {
const page = req.query.page ?? 1;
const limit = req.query.limit ?? 20;
res.json({ page, limit });
});Route order matters
// Express matches routes top-to-bottom, FIRST match wins:
app.get("/users/me", (req, res) => res.send("Current user")); // must come FIRST
app.get("/users/:id", (req, res) => res.send(`User ${req.params.id}`));
// If /users/:id were defined first, a request to /users/me would
// match :id="me" instead of ever reaching the specific /users/me route.
// Rule: more SPECIFIC routes go before more GENERAL ones.
Try It Yourself (Node.js logic)
Official Sources
The Codex links only to official documentation. No third-party tutorials.