AceDevHub
Intermediate Node.js Interview QuestionsIntermediatePractical

Node.js · Question 44

How does routing work in Express.js?

Direct answer

Express matches HTTP method + path patterns — app.get/post/put/delete, route params (:id), optional regex, and mounted Routers at prefixes; first matching route wins, so order static paths before parametric ones.

Routing maps URL + verb to handler functions. Express builds a routing table internally — similar mental model to Fastify route registration with method and url.

PatternExampleMatches
Literalapp.get('/health')GET /health
Paramapp.get('/topics/:slug')GET /topics/nodejs-interview-questions
Optionalapp.get('/users/:id?')GET /users or /users/42
Router mountapp.use('/interviews', router)All paths under /interviews/*
  • req.params — named segments from :slug, :id.
  • Route order — /users/me before /users/:id or 'me' is captured as id.
  • app.all — same path, any HTTP method.
express-routing.mjs
import express from "express";

const app = express();
const topics = express.Router({ mergeParams: true });

topics.get("/:topicSlug/questions/:questionSlug", (req, res) => {
  const { topicSlug, questionSlug } = req.params;
  res.json({ topicSlug, questionSlug });
});

app.use("/interviews/topics", topics);

// Specific before generic
app.get("/users/me", (req, res) => res.json({ self: true }));
app.get("/users/:id", (req, res) => res.json({ id: req.params.id }));