new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Bun · Runtime · all subjects

bun apis/routing

40 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Bun.FileSystemRouter routing API

Bun provides Bun.FileSystemRouter for file system-based routing capabilities.

FileSystemRouter.match() method signature

The match() method accepts a string path, Request object, or Response object. When a Request or Response object is passed, its url property is used to resolve the route. The method returns a match object or null if no route matches.

FileSystemRouter.match() return object properties

The match() method returns an object with these properties: filePath (string) is the full file system path to the matched file; kind (string) is one of "exact", "catch-all", "optional-catch-all", or "dynamic"; name (string) is the route pattern name; pathname (string) is the requested pathname and query string; src (string) is the constructed source URL combining origin and assetPrefix; params (optional, Record<string, string>) contains URL parameters from dynamic segments; query (optional, Record<string, string>) contains parsed query string parameters.

FileSystemRouter.reload() method

The reload() method re-scans the directory contents to pick up any file changes. The router reads the directory contents only on initialization, so reload() must be called to detect new or deleted files.

FileSystemRouter supports Next.js-style routing only

Bun.FileSystemRouter supports only Next.js-style file-system routing with the pages directory pattern. The Next.js 13 app directory is not supported.

FileSystemRouter Next.js routing pattern examples

Supported routing patterns include: index.tsx for root routes; named files like settings.tsx for exact routes; directories with nested index.tsx for nested routes; [slug].tsx for dynamic segments; [[...catchall]].tsx for optional catch-all routes that match zero or more path segments.

FileSystemRouter query parameters

Query parameters from the request URL are parsed and returned in the query property of the match result as a Record<string, string>. For example, /settings?foo=bar returns {query: {foo: "bar"}}.

FileSystemRouter dynamic route parameters example

For a file at pages/blog/[slug].tsx, requesting /blog/my-cool-post matches with kind "dynamic" and params {slug: "my-cool-post"}. The params object contains the extracted values from dynamic segments in the route pattern.

FileSystemRouter.match() with exact route example

Creating a router with const router = new Bun.FileSystemRouter({style: "nextjs", dir: "./pages", origin: "https://mydomain.com", assetPrefix: "_next/static/"}) and calling router.match("/") returns {filePath: "/path/to/pages/index.tsx", kind: "exact", name: "/", pathname: "/", src: "https://mydomain.com/_next/static/index.tsx"}.

FileSystemRouter class constructor parameters

The Bun.FileSystemRouter constructor accepts an object with the following properties: dir (required, string) specifies the pages directory to route against; style (required, string) must be "nextjs"; origin (optional, string) is the base URL for the origin property; assetPrefix (optional, string) is prepended to the src URL; fileExtensions (optional, string array) specifies which file extensions to match.

Route precedence order

Routes are matched in order of specificity: first exact routes like /users/all, second parameter routes like /users/:id, third wildcard routes like /users/*, and finally global catch-all /* routes.

BunRequest interface with params and cookies

BunRequest extends Request and includes a params property of type Record<T, string> for route parameters and a readonly cookies property of type CookieMap.

TypeScript type-safe route parameters

When route paths are passed as string literals to Bun.serve(), TypeScript automatically parses route parameters and provides autocomplete for request.params in the editor. You can optionally pass a type parameter to BunRequest with the route path as a string literal type.

Route parameters with percent-decoding and Unicode

Bun automatically decodes percent-encoded route parameter values, including Unicode characters. Invalid Unicode is replaced with the Unicode replacement character (\uFFFD).

Static Response routes with zero-allocation optimization

Routes can be Response objects without handler functions. Bun.serve() optimizes them for zero-allocation dispatch, suitable for health checks, redirects, and fixed content. Static responses do not allocate additional memory after initialization and generally provide at least 15% performance improvement over manually returning Response objects.

Static route response caching and reloading

Static responses in routes are cached for the lifetime of the server object. To reload static routes, call server.reload(options).

Static file routes vs buffered file routes

Static routes (new Response(await Bun.file().bytes())) buffer content in memory at startup with zero filesystem I/O during requests, automatic ETag generation, and If-None-Match support returning 304 Not Modified. They cause startup errors for missing files. File routes (new Response(Bun.file(path))) read from filesystem on each request with built-in 404 handling, Last-Modified support, If-Modified-Since header support, Range request support, and streaming transfers with backpressure handling for memory efficiency.

Directory routes with dir property

To serve an entire directory tree at a URL prefix, pass { dir: "./path" } as the route value. The route path must end in /*. The part of the request URL after the prefix is percent-decoded once and opened relative to dir. Non-canonical paths containing ., .., empty segments, %2F, or %XX sequences encoding special characters are rejected with 404.

Directory routes security with openat2 on Linux

On Linux, directory route opens use openat2(RESOLVE_IN_ROOT), so symlinks that would escape dir are clamped by the kernel, preventing directory escape attacks.

Directory routes case-sensitivity with case-insensitive filesystems

Routing is case-sensitive but filesystems on macOS and Windows are case-insensitive by default. A case-varied URL like /static/Admin/secret.txt will route to a directory wildcard handler and open the case-insensitive path admin/secret.txt. Do not place access-controlled content inside dir and rely on an overlapping route to gate it.

Directory routes response handling

Directory routes set Content-Type from file extension, send Last-Modified and a weak ETag (W/"<size>-<mtime>") on every response, honor If-Modified-Since/If-None-Match with 304 Not Modified, support Range requests with Accept-Ranges: bytes and Content-Range, redirect requests to directories without trailing slash to the trailing-slash URL, serve index.html from that directory with trailing slash, and return 404 for missing files.

Directory routes statCache option

Pass statCache: false to disable the per-path Last-Modified cache in directory routes, saving roughly 20 KB per route.

Streaming files with BunFile in Response body

To stream a file, return a Response object with a BunFile object as the body. Bun automatically uses the sendfile(2) system call when possible, enabling zero-copy file transfers in the kernel.

Partial file serving with slice() method

To send part of a file, use the slice(start, end) method on the Bun.file object. Bun automatically sets the Content-Range and Content-Length headers on the Response object.

fetch handler for unmatched routes

The fetch handler runs for incoming requests that no route matched. It receives a Request object and returns a Response or Promise<Response>. The fetch handler supports async/await and receives the Server object as its second argument.

Server.requestIP() in fetch handler

The Server object passed as the second argument to the fetch handler has a requestIP(req) method that returns an object with an address property containing the client's IP address.

Route handler example with basic routes

Example showing basic route setup with Bun.serve() including static path "/" returning "Home", "/api" returning JSON {success: true}, and "/users" returning async JSON {users: []}. Unmatched routes handled by fetch returning "Unmatched route".

Async route handler examples with Promise and async/await

Two examples showing async routes: first using async/await with sql SELECT to return version as JSON; second using Promise constructor with setTimeout to delay and then call sql query. Both import sql and serve from bun.

Type-safe route parameters example

Example showing TypeScript route parameter type safety with /orgs/:orgId/repos/:repoId receiving req with destructured params, and optional explicit BunRequest<"/orgs/:orgId/repos/:repoId/settings"> type annotation for autocomplete.

Static Response routes examples

Examples of static routes: /health returning Response("OK"), /ready returning Response with X-Ready header, /blog returning Response.redirect to https://bun.com/blog, and /api/config returning Response.json with version and env fields.

Static vs file routes serving example

Example showing /logo.png as static route using new Response(await Bun.file("./logo.png").bytes()) with content buffered at startup, and /download.zip as file route using new Response(Bun.file("./download.zip")) reading from filesystem on each request.

Directory route example

Example showing /static/* route with { dir: "./public" } value to serve entire directory tree at URL prefix.

Streaming file response example

Example showing streaming file by returning new Response(Bun.file("./hello.txt")) in fetch handler.

Partial file with Range header example

Example parsing Range header from request as "Range: bytes=0-100", extracting start and end values, creating bigFile reference to Bun.file("./big-video.mp4"), and returning new Response(bigFile.slice(start, end)) with automatic Content-Range and Content-Length headers.

fetch handler basic example

Example showing fetch handler checking url.pathname for /, /blog routes and returning responses or 404.

fetch handler with async/await example

Example showing async fetch handler with performance.now() timing, await sleep(10) call, and response message showing elapsed time. Imports sleep and serve from bun.

fetch handler forwarding request example

Example showing fetch handler returning fetch("https://example.com") to forward incoming request to another server.

fetch handler with Server.requestIP() example

Example showing fetch handler receiving server as second argument, calling server.requestIP(req) to get IP, and returning response with client IP address.

Route precedence ordering example

Example showing route precedence with most specific first: /api/users/me exact route, /api/users/:id parameter route, /api/* wildcard route, /* global catch-all route.

Bun.serve() routing with routes property

Add routes to Bun.serve() using the routes property, which supports static paths, parameters, and wildcards. Routes receive a BunRequest object and return a Response or Promise<Response>. Unmatched requests are handled by the fetch method.

Give your agent this brain