Implement a Router From Scratch in JavaScript
Build a router from scratch in JavaScript with path parameters, wildcards, HTTP methods, query strings, 404 and 405 answers and a Node.js server. Node.js 24.

A router answers one question: given a method and a path, which function should handle this request, and what values did the path contain? Every web framework has one, and the interview version asks for a small one that supports parameters like /users/:id, a wildcard, several HTTP methods and a clear order of matching. The hard parts are not in the matching. They are in the decisions around it: what happens with a trailing slash, which route wins when two match, and how to avoid a regular expression that an attacker can make slow. This post builds a router on Node.js 24 in stages, shows the matching with printed results and ends by wiring it to node:http. It is pure logic, so you can run every example without a network. For related code that chains handlers, see writing a middleware chain.
The contract
router.add(method, pattern, handler) registers a route. router.match(method, path) returns the handler and the extracted parameters, or null. Patterns support literal segments, :name parameters that match one segment and a trailing * that matches the rest. The first registered route that matches wins, which makes the order visible and predictable.
Compiling a pattern
Turn each pattern into a list of segment checks once, at registration, not on every request.
function compile(pattern) {
const parts = pattern.split("/").filter(Boolean);
return parts.map((part) => {
if (part === "*") return { type: "wildcard" };
if (part.startsWith(":")) return { type: "param", name: part.slice(1) };
return { type: "literal", value: part };
});
}
console.log(compile("/users/:id/posts/*"));[
{ type: 'literal', value: 'users' },
{ type: 'param', name: 'id' },
{ type: 'literal', value: 'posts' },
{ type: 'wildcard' }
]Splitting on / and dropping empty parts ignores leading and trailing slashes, so /users/ and /users compile the same. Working with segments, not a generated regular expression, is the safer design for a small router: there is no backtracking, so no input can make matching slow, and the matching code reads like what it does.
Matching a path
function matchSegments(segments, path) {
const parts = path.split("/").filter(Boolean);
const params = {};
for (let i = 0; i < segments.length; i += 1) {
const segment = segments[i];
if (segment.type === "wildcard") {
params["*"] = parts.slice(i).map(decodeURIComponent).join("/");
return params;
}
if (i >= parts.length) return null;
if (segment.type === "literal") {
if (segment.value !== parts[i]) return null;
} else {
params[segment.name] = decodeURIComponent(parts[i]);
}
}
return parts.length === segments.length ? params : null;
}
const segments = compile("/users/:id");
console.log(matchSegments(segments, "/users/42"));
console.log(matchSegments(segments, "/users/42/"));
console.log(matchSegments(segments, "/users"));
console.log(matchSegments(segments, "/users/42/extra"));
console.log(matchSegments(compile("/files/*"), "/files/a/b%20c.txt"));{ id: '42' }
{ id: '42' }
null
null
{ '*': 'a/b c.txt' }Each line shows a rule. A trailing slash is tolerated. A missing segment fails, and an extra segment fails, because the final comparison requires the path to have exactly as many parts as the pattern. A wildcard returns early with everything left, joined back with slashes. Parameter values are decoded with decodeURIComponent, so %20 becomes a space, and that call can throw a URIError on malformed input such as %E0%A4%A, which a production router catches and treats as a non-match or a 400.
The router
class Router {
#routes = [];
add(method, pattern, handler) {
this.#routes.push({ method: method.toUpperCase(), segments: compile(pattern), handler });
return this;
}
get(pattern, handler) {
return this.add("GET", pattern, handler);
}
post(pattern, handler) {
return this.add("POST", pattern, handler);
}
match(method, path) {
for (const route of this.#routes) {
if (route.method !== method.toUpperCase()) continue;
let params;
try {
params = matchSegments(route.segments, path);
} catch {
return null;
}
if (params) return { handler: route.handler, params };
}
return null;
}
}
const router = new Router()
.get("/users/new", () => "new form")
.get("/users/:id", ({ id }) => `user ${id}`)
.post("/users", () => "create")
.get("/static/*", ({ "*": rest }) => `file ${rest}`);
for (const [method, path] of [
["GET", "/users/new"],
["GET", "/users/7"],
["POST", "/users"],
["GET", "/static/css/app.css"],
["DELETE", "/users/7"],
]) {
const found = router.match(method, path);
console.log(method, path, "->", found ? found.handler(found.params) : null);
}GET /users/new -> new form
GET /users/7 -> user 7
POST /users -> create
GET /static/css/app.css -> file css/app.css
DELETE /users/7 -> nullThe first route, /users/new, is registered before /users/:id. If the order were reversed, /users/new would match the parameter route with id equal to "new", and the form would never be reached. That is the single most common routing bug, and first-match-wins makes it a rule you can state: put specific routes before general ones. Some routers instead rank routes by specificity, so literals beat parameters beat wildcards regardless of order. That removes a class of mistakes, at the cost of a rule the reader has to remember.
The last line returns null for DELETE, because no route has that method. An HTTP server should distinguish "no such path" from "path exists, wrong method". The first is 404, the second is 405 with an Allow header.
404 versus 405
A server should tell "no such path" apart from "this path exists, but not for this method". The first is a 404. The second is a 405, and the specification requires an Allow header that lists the methods the resource does support. To produce that list, the router needs to find every route whose path matches, whatever its method, so a subclass keeps its own record of the compiled routes.
class Router2 extends Router {
#all = [];
add(method, pattern, handler) {
this.#all.push({ method: method.toUpperCase(), segments: compile(pattern) });
return super.add(method, pattern, handler);
}
resolve(method, path) {
const found = this.match(method, path);
if (found) return { status: 200, ...found };
const allow = [...new Set(
this.#all.filter((r) => matchSegments(r.segments, path)).map((r) => r.method),
)];
return allow.length > 0 ? { status: 405, allow } : { status: 404 };
}
}
const r2 = new Router2().get("/users/:id", () => "x").post("/users/:id", () => "y");
console.log(r2.resolve("GET", "/users/1").status);
console.log(r2.resolve("DELETE", "/users/1"));
console.log(r2.resolve("GET", "/nope"));200
{ status: 405, allow: [ 'GET', 'POST' ] }
{ status: 404 }A 405 response must include an Allow header listing the methods the resource supports, as the HTTP specification requires, and the array here is exactly what you need to build it. That level of detail is what separates a toy from a router someone could use.
Query strings
The path to match excludes the query. Split it off with the URL class, which is built into Node.js and parses the query for you.
function parseTarget(target) {
const url = new URL(target, "http://localhost");
return { path: url.pathname, query: Object.fromEntries(url.searchParams) };
}
console.log(parseTarget("/search/books?q=js%20guide&page=2"));{ path: '/search/books', query: { q: 'js guide', page: '2' } }The second argument to URL is a base, needed because a request target such as /search/books is not an absolute URL. Notice that Object.fromEntries keeps only the last value for a repeated key, so ?tag=a&tag=b yields tag: 'b'. If repeated keys matter, use searchParams.getAll.
Connecting it to node:http
import { createServer } from "node:http";
const app = new Router2()
.get("/hello/:name", ({ name }) => ({ greeting: `hello ${name}` }))
.get("/health", () => ({ ok: true }));
const server = createServer((req, res) => {
const { path } = parseTarget(req.url);
const result = app.resolve(req.method, path);
if (result.status === 200) {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify(result.handler(result.params)));
} else {
res.writeHead(result.status, result.allow ? { allow: result.allow.join(", ") } : {});
res.end();
}
});
server.listen(3000);GET /hello/ada -> 200 {"greeting":"hello ada"}
POST /hello/ada -> 405 with header: allow: GET
GET /missing -> 404The block above lists the responses those three requests produce, worked out from the code, since the server is not started here. The router itself needed no knowledge of HTTP beyond method strings, which is why it was testable on its own.
What this version leaves out
Real routers add middleware that runs before handlers, nested routers mounted under a prefix, optional parameters, regular expression constraints such as :id(\\d+) and a radix tree so that matching does not scan every route. The scan is linear in the number of routes, which is fine for dozens and slow for thousands. A tree indexed by the first segments turns it into a lookup per segment. Also note what happens with case: /Users does not match /users here, which is the standard choice because paths are case sensitive by specification.
Trailing slashes and other policies
Every router has to settle a few policies, and the answers matter more in production than the matching code. The version here treats /users and /users/ as the same route, which is friendly. Many sites instead redirect one form to the other with a 301, because two URLs for one page split search engine signals and cache entries. If you redirect, pick one canonical form and apply it everywhere.
Case is the second policy. Paths are case sensitive by specification, so /About and /about are different resources, and a router that lowercases the path is making a product decision. Encoded slashes are the third. A segment such as a%2Fb decodes to a/b only after splitting, so it stays a single parameter, which is the safe behavior. Decoding the whole path first would turn it into two segments and let a request reach a route it was never meant to.
Finally, decide what the handler receives. Passing only the parameters, as here, keeps handlers pure and easy to test. A real framework passes the request and response too, and that is where the router stops being a function and starts being a framework.
Testing it
import test from "node:test";
import assert from "node:assert/strict";
test("extracts parameters and decodes them", () => {
const router = new Router().get("/tags/:name", () => null);
assert.deepEqual(router.match("GET", "/tags/c%2B%2B").params, { name: "c++" });
});
test("first matching route wins", () => {
const router = new Router().get("/a/b", () => 1).get("/a/:x", () => 2);
assert.equal(router.match("GET", "/a/b").handler(), 1);
});
test("returns null for an unknown path or method", () => {
const router = new Router().get("/a", () => 1);
assert.equal(router.match("GET", "/b"), null);
assert.equal(router.match("POST", "/a"), null);
});ℹ tests 3
ℹ pass 3
ℹ fail 0

