Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/deno/tests/registry/jsr/@std/http/1.0.0/mod.ts>route

A modern runtime for JavaScript and TypeScript.
Go to Latest
function route
import { route } from "https://deno.land/x/deno@v2.0.4/tests/registry/jsr/@std/http/1.0.0/mod.ts";

Routes requests to different handlers based on the request path and method.

[!WARNING] UNSTABLE: New API, yet to be vetted.

Examples

Usage

import { route, type Route } from "@std/http/route";
import { serveDir } from "@std/http/file-server";

const routes: Route[] = [
  {
    pattern: new URLPattern({ pathname: "/about" }),
    handler: () => new Response("About page"),
  },
  {
    pattern: new URLPattern({ pathname: "/users/:id" }),
    handler: (_req, _info, params) => new Response(params?.pathname.groups.id),
  },
  {
    pattern: new URLPattern({ pathname: "/static/*" }),
    handler: (req: Request) => serveDir(req)
  }
];

function defaultHandler(_req: Request) {
  return new Response("Not found", { status: 404 });
}

Deno.serve(route(routes, defaultHandler));

Parameters

routes: Route[]

Route configurations

defaultHandler: (request: Request, info?: Deno.ServeHandlerInfo) => Response | Promise<Response>

Default request handler that's returned when no route matches the given request. Serving HTTP 404 Not Found or 405 Method Not Allowed response can be done in this function.

Returns

(request: Request, info?: Deno.ServeHandlerInfo) => Response | Promise<Response>

Request handler