Skip to main content

@std/http@1.0.8
Built and signed on GitHub Actions

Utilities for building HTTP servers

This package works with DenoIt is unknown whether this package works with Bun
This package works with Deno
It is unknown whether this package works with Bun
JSR Score
94%
Published
20 hours ago (1.0.8)
function route
Unstable
route(
routes: Route[],
defaultHandler: () => Response | Promise<Response>,
): () => Response | Promise<Response>

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

Examples

Usage

import { route, type Route } from "@std/http/unstable-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)
  },
  {
    method: ["GET", "HEAD"],
    pattern: new URLPattern({ pathname: "/api" }),
    handler: (req: Request) => new Response(req.method === 'HEAD' ? null : 'ok'),
  },
];

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

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

Parameters

routes: Route[]

Route configurations

defaultHandler: () => 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.

Return Type

Request handler

Add Package

deno add jsr:@std/http

Import symbol

import { route } from "@std/http";

---- OR ----

Import directly with a jsr specifier

import { route } from "jsr:@std/http";

Add Package

bunx jsr add @std/http

Import symbol

import { route } from "@std/http";