Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 ยท HTTP Servers

Routing, Middleware and Static Files in Deno

Route requests in Deno with URLPattern, compose middleware for logging and auth, serve static files with the standard library and see when a framework like Hono or Oak is worth adding.

Deno.serve gives you one function for every request, so something has to decide which code runs for GET /users/7 and which for POST /login. That decision is routing. The code that runs around every route, such as logging, authentication or adding headers, is middleware. Deno has the building blocks for both in the platform itself, and for larger apps there are small frameworks that package them.

This lesson builds a router from URLPattern, composes middleware as plain functions, serves static files, and then compares the DIY approach with Hono and Oak so you can choose.

The runnable blocks use Node 24 (which has the same URLPattern, Request and Response). Deno commands and Deno.* or jsr: imports are read-only.

URLPattern: routes without regex

URLPattern is a web standard that matches URLs against patterns with named parameters. It is built into Deno, so no library is needed.

TypeScript
const pattern = new URLPattern({ pathname: "/users/:id" });

const match = pattern.exec("http://localhost/users/42");
match?.pathname.groups.id;   // "42"
Pattern Matches Groups
/users/:id /users/42 id = "42"
/files/* /files/a/b.txt 0 = "a/b.txt"
/posts/:year(\\d{4}) /posts/2026 year = "2026"
/blog/:slug? /blog and /blog/hello slug optional
/api/:version/:resource /api/v1/orders two groups

A router is then a list of { method, pattern, handler } entries and a loop. The example below is complete and runnable; the same code works unchanged in Deno.

Node.js A router built on URLPattern

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two details make this a proper router. A path that exists under a different method answers 405 with an Allow header instead of a misleading 404. And handlers receive the parsed params, so they never touch the URL themselves.

The standard library ships a similar helper, route() in jsr:@std/http/unstable-route, taking the same kind of list. It is marked unstable, which is why many projects keep a ten-line router like the one above.

Middleware as function composition

Middleware is a function that receives the request and a next function, and returns a response. It can act before next (check a header, reject a request), call next(), and act after it (add headers, measure time).

TypeScript
type Handler = (req: Request) => Promise<Response> | Response;
type Middleware = (req: Request, next: Handler) => Promise<Response> | Response;

function compose(middlewares: Middleware[], final: Handler): Handler {
  return middlewares.reduceRight<Handler>(
    (next, mw) => (req) => mw(req, next),
    final,
  );
}
flowchart LR
  A["Request"] --> B["logger"]
  B --> C["auth"]
  C --> D["router"]
  D --> E["handler"]
  E -. "Response" .-> D
  D -. "Response" .-> C
  C -. "Response" .-> B
  B -. "Response" .-> F["Client"]

The request travels inward through each layer; the response travels back out, so every layer sees both.

Here is a runnable chain with logging, timing, a bearer-token check and a catch-all error handler:

Node.js Composing middleware

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Order matters. errors is outermost so it catches failures from every inner layer, auth sits before the router so protected routes are never reached, and logger records the final status because it looks at the response after next.

Serving static files

For HTML, CSS, images and a built front end, jsr:@std/http/file-server provides serveDir and serveFile:

TypeScript
import { serveDir } from "jsr:@std/http/file-server";

Deno.serve((req) => {
  const { pathname } = new URL(req.url);

  if (pathname.startsWith("/api/")) {
    return Response.json({ hello: "api" });
  }

  return serveDir(req, {
    fsRoot: "./public",     // folder on disk
    urlRoot: "",            // URL prefix to strip
    showDirListing: false,  // never list folders in production
    enableCors: false,
  });
});
Terminal
deno run --allow-net --allow-read=./public server.ts

serveDir handles content types, ETag and Last-Modified headers, conditional requests (304), byte ranges for video, and protects against ../ path traversal. Narrow --allow-read to the one folder so that even a bug cannot expose other files. For a single page app, route unknown paths to index.html with serveFile(req, "./public/index.html").

When to use a framework

A hand-built router is fine for a few endpoints. Frameworks add conveniences once an app grows: nested routers, typed context, validators, cookie and session helpers, templating.

DIY (URLPattern) Hono Oak
Install nothing jsr:@hono/hono jsr:@oak/oak
Style functions app.get(path, c => ...) router.get(path, ctx => ...)
Runs elsewhere anywhere Deno, Node, Bun, edge mainly Deno and Node
Best for small services APIs, edge, portable code Koa-style apps
TypeScript
import { Hono } from "jsr:@hono/hono";

const app = new Hono();

app.use(async (c, next) => {
  await next();
  c.header("x-frame-options", "DENY");
});
app.get("/users/:id", (c) => c.json({ id: c.req.param("id") }));
app.post("/users", async (c) => c.json(await c.req.json(), 201));

Deno.serve(app.fetch);

Hono is built on the same Request/Response model, so app.fetch is just a handler and plugs straight into Deno.serve. Whatever you choose, the ideas from this lesson stay the same: match a route, run layers around it, return a Response. Fresh, Deno's full-stack web framework, builds on these ideas too if you want server-rendered pages with islands of interactivity.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which URLPattern pathname captures the id in /users/42?

    URLPattern uses a colon prefix for named groups, so /users/:id matches /users/42 with groups.id = '42'.
  2. 2. A client sends DELETE to a path that only has GET and POST routes. What should the router answer?

    The path exists but not for that method, so 405 plus an Allow header listing the supported methods is the accurate answer.
  3. 3. Why is the error-handling middleware placed outermost in the chain?

    Each middleware wraps the ones after it. The outermost wrapper sees every exception from the inner layers.
  4. 4. What does serveDir protect against that a naive file server might not?

    serveDir resolves paths safely inside fsRoot. Narrowing --allow-read to that folder adds a second line of defense.

Summary

  • URLPattern matches paths and extracts parameters without regular expressions or libraries.
  • A router is a list of method, pattern and handler entries; answer 405 with Allow for a wrong method.
  • Middleware wraps a handler: act before next, call it, act after; compose layers with reduceRight.
  • serveDir serves static files safely; restrict --allow-read to the public folder.
  • Reach for Hono or Oak when you need nested routers, validators and ready-made helpers.

Next: Streaming, Server-Sent Events and WebSockets