---
title: API reference
description: Every export of @usenotra/agentside, @usenotra/agentside/effect and @usenotra/agentside/build with its signature and defaults.
sidebar:
  order: 10
---

## agentside(config)

```ts
function agentside(config: AgentsideConfig): {
  handle(request: Request, next: () => Promise<Response>): Promise<Response>;
  serve(request: Request, pathname?: string): Promise<Response>;
};
```

`handle` negotiates the request and either answers with markdown or calls `next()`. See [Content negotiation](/docs/negotiation). `serve` treats the request as an explicit markdown request for `pathname`, which defaults to the request URL's path. The returned object's type is exported as `Agentside`.

## AgentsideConfig

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `routes` | `Record<string, Source>` | required | Page paths or patterns mapped to their twin's source. |
| `variants` | `Record<string, Variant[]>` | `{}` | Variants per route pattern. See [A/B variants](/docs/variants). |
| `accept` | `"contains" \| "q-value"` | `"contains"` | `"contains"` serves markdown whenever `Accept` mentions `text/markdown` or `text/x-markdown` without `q=0`, matching CDN rules that can't parse q-values. `"q-value"` weighs q-values strictly. See [Content negotiation](/docs/negotiation#the-accept-header). |
| `skip` | `string[]` | `[]` | Path prefixes that `handle` never touches. |
| `cache` | `{ ttlMs?, capacity? } \| false` | `{ ttlMs: 300000, capacity: 1000 }` | In-memory cache settings. See [Caching](/docs/caching). |
| `timeoutMs` | `number` | `5000` | Timeout for each source load, including retries. |
| `retries` | `number` | `2` | Retries for remote sources on network errors and `408`, `429`, `500`, `502`, `503` and `504` responses. |
| `cacheControl` | `string` | `"public, max-age=3600"` | `Cache-Control` for markdown responses. |
| `noindex` | `boolean` | unset | `X-Robots-Tag: noindex` on markdown responses. Unset: `handle` sends it on `.md` URLs but not on markdown it negotiates on the page URL, while `serve()` and `markdownResponse()` always send it, so pass `noindex: false` when you answer a negotiated request yourself with `markdownResponse()`. `true`: on every markdown response. `false`: never. |
| `linkHeader` | `boolean` | `true` | Adds a `Link` header to HTML responses that have a twin. |
| `normalize` | `boolean` | `true` | Replaces typographic Unicode with ASCII. |
| `onServe` | `(event: ServeEvent) => void` | | Runs after every successful markdown response. |
| `onError` | `(error: unknown, path: string) => void` | | Runs when a source fails. |

## Sources

```ts
type Source = string | LocalSource | RemoteSource;
type LocalSource = (context: RenderContext) => string | null | undefined | Promise<string | null | undefined>;

function remote(
  url: string | ((context: RenderContext) => string),
  options?: { headers?: Record<string, string> }
): RemoteSource;
```

## Variant

```ts
interface Variant {
  readonly id: string;
  readonly source: Source;
  readonly agents?: readonly string[];
  readonly vendors?: readonly string[];
  readonly purposes?: readonly AgentPurpose[];
}
```

## Types

```ts
type AgentPurpose = "training" | "search" | "user-action";
type Format = "html" | "markdown";

interface Agent {
  readonly name: string;
  readonly vendor: string;
  readonly purpose: AgentPurpose;
}

interface RenderContext {
  readonly path: string;
  readonly params: Readonly<Record<string, string>>;
  readonly request: Request;
  readonly agent: Agent | null;
}

interface ServeEvent {
  readonly path: string;
  readonly variant: string;
  readonly agent: Agent | null;
  readonly status: number;
  readonly cached: boolean;
  readonly durationMs: number;
}
```

## Helpers

| Export | Signature | Description |
| --- | --- | --- |
| `detectAgent` | `(userAgent: string \| null \| undefined) => Agent \| null` | Detects a known AI agent from a user agent. |
| `KNOWN_AGENTS` | `readonly Agent[]` | Every agent `detectAgent` recognizes. |
| `negotiateFormat` | `(accept: string \| null \| undefined, mode?: "q-value" \| "contains") => Format \| null` | Picks markdown or HTML from an `Accept` header, or `null` when neither is acceptable. `mode` defaults to `"q-value"`. |
| `toMarkdownPath` | `(pathname: string) => string` | Maps a page path to its twin URL, `/pricing` to `/pricing.md` and `/` to `/index.md`. |
| `estimateTokens` | `(text: string) => number` | The whitespace-based estimate sent as `X-Markdown-Tokens`. |
| `normalizeUnicode` | `(text: string) => string` | The normalization applied when `normalize` is on. |

## Errors

`NotFound`, `RenderFailed`, `RemoteFailed`, `SourceTimeout` and the `ServeError` union, plus `InvalidConfig`, `FileFailed` and `PrerenderFailed`. See [Error handling](/docs/error-handling#typed-errors) and [Effect API](/docs/effect#errors).

## agentside/effect

| Export | Description |
| --- | --- |
| `Agentside` | The service tag, with `match` and `serve`. |
| `layer(config)` | Provides `Agentside`, requires an `HttpClient`. |
| `layerFetch(config)` | Provides `Agentside` with the fetch `HttpClient`. |
| `make(config)` | The Effect program behind `agentside()`, returning `{ match, serve }`. Requires an `HttpClient`. |
| `markdownResponse(body, config, status?, extra?, tokens?)` | Builds a markdown `Response` with Agentside's headers, including `X-Robots-Tag: noindex` unless `config.noindex` is `false`. |
| `CONTROL` | `"control"` |
| `Interface`, `Match`, `Served` | The service shape and the types returned by `match` and `serve`. |
| `prerender`, `prerenderHtml`, `applyVercelBuildOutput` | The Effect versions of the build helpers. |
| Errors | `NotFound`, `RenderFailed`, `RemoteFailed`, `SourceTimeout`, `ServeError`, `InvalidConfig`, `FileFailed`, `PrerenderFailed` |

`@usenotra/agentside/effect/build` exports the same `prerender`, `prerenderHtml` and `applyVercelBuildOutput` programs.

See [Effect API](/docs/effect) for an example.

## agentside/build

Build-time helpers, imported from `@usenotra/agentside/build`. They use `node:fs` and run in Node and Bun, not at the edge.

### prerender

```ts
function prerender(
  config: AgentsideConfig,
  options: { outDir: string; paths?: string[]; siteUrl?: string }
): Promise<{ written: string[]; skipped: string[] }>;
```

```ts
import { prerender } from "@usenotra/agentside/build";

const { written, skipped } = await prerender(config, {
  outDir: "dist/client",
  paths: ["/", "/pricing", "/blog/hello"],
  siteUrl: "https://example.com",
});
```

`prerender` renders each path once with the cache off and writes it to `outDir` at its `.md` URL (`/` becomes `index.md`). `paths` defaults to every route without parameters. `siteUrl` is the origin of the `Request` your sources receive and defaults to `http://localhost`. Twins that return `null` end up in `skipped`. If any twin fails, it throws one error listing every failing path, so a broken twin stops the build instead of reaching agents.

### prerenderHtml

```ts
function prerenderHtml(options: PrerenderHtmlOptions): Promise<PrerenderedPage[]>;

interface PrerenderHtmlOptions {
  readonly dir: string;
  readonly outDir?: string;
  readonly selector?: string;
  readonly siteUrl?: string;
  readonly exclude?: readonly string[];
  readonly llms?: LlmsOptions | false;
  readonly normalize?: boolean;
}

interface LlmsOptions {
  readonly title: string;
  readonly description?: string;
  readonly siteUrl?: string;
  readonly sections?: Record<string, string>;
  readonly order?: readonly string[];
  readonly links?: Record<string, readonly { title: string; url: string; description?: string }[]>;
}

interface PrerenderedPage {
  readonly path: string;
  readonly title: string;
  readonly description: string;
  readonly markdown: string;
}
```

```ts
import { prerenderHtml } from "@usenotra/agentside/build";

const pages = await prerenderHtml({
  dir: "dist",
  siteUrl: "https://example.com",
  exclude: ["/admin"],
  llms: { title: "Acme", description: "We make anvils.", sections: { "/legal": "Legal" } },
});
```

Converts every built `.html` file in `dir` (except `404.html` and `500.html`) to markdown and writes it to `outDir`, which defaults to `dir`, at its `.md` URL. Only the `selector` element is converted, which defaults to `<main>`, then `<article>`, then `<body>`. `data-ai-ignore` drops an element, `data-ai-content` replaces it with the attribute's markdown, tables become GFM tables, `<dl>` lists become `**term**: definition` items and cards become a linked heading followed by their text. `normalize: true` applies `normalizeUnicode` to the output, which is off by default. With `llms`, it also writes `llms.txt` and `llms-full.txt`. Returns the converted pages in `llms.order` and then by path; any failure throws one error listing every failing path. See [Static sites](/docs/static-sites) for every rule.

### htmlToMarkdown

```ts
function htmlToMarkdown(html: string, options?: { selector?: string; siteUrl?: string }): string;
```

Converts a single HTML document with the same rules as `prerenderHtml`, without Unicode normalization.

### llmsTxt and llmsFullTxt

```ts
function llmsTxt(
  pages: readonly PrerenderedPage[],
  options: {
    title: string;
    description?: string;
    siteUrl?: string;
    sections?: Record<string, string>;
    order?: string[];
    links?: Record<string, { title: string; url: string; description?: string }[]>;
  }
): string;

function llmsFullTxt(pages: readonly PrerenderedPage[], options?: { siteUrl?: string }): string;
```

`llmsTxt` lists each page as a link to its `.md` URL, prefixed with `siteUrl`, grouped into `##` sections. Page titles come from the page's `<h1>`, falling back to `<title>`, so site-name suffixes stay out of the list. Top-level pages without children go under "Pages", other pages are grouped by their first path segment, and `sections` maps a path prefix to a section title that wins over the default. Sections appear in the order you pass them, and `order` lists page paths in the order you want them (for example your navigation order), with unlisted pages after them. `links` adds sections of links that aren't pages, such as API docs, an OpenAPI spec or an MCP server. A section called "Optional" always comes last, as the llms.txt format expects.

`llmsFullTxt` joins every page's markdown with `---` and starts each page with `Source: <url>`, so an agent can tell which page each part came from. `prerenderHtml` passes your `llms` options to both and uses `order` for `llms-full.txt` too.

### vercelRoutes

```ts
function vercelRoutes(paths?: readonly string[]): {
  routes: Array<{
    src: string;
    dest?: string;
    has?: Array<{ type: "header"; key: string; value: string }>;
    missing?: Array<{ type: "header"; key: string; value: string }>;
    headers: Record<string, string>;
    continue?: boolean;
  }>;
};
```

```ts
import { vercelRoutes } from "@usenotra/agentside/build";

await Bun.write("vercel.json", JSON.stringify(vercelRoutes(), null, 2));
```

Returns Vercel's `routes` array, which runs before the static file lookup. Requests with `Accept: text/markdown` or a known AI agent user agent are rewritten to the page's `.md` file with `Content-Type: text/markdown; charset=utf-8` and `Vary: Accept, User-Agent`. Direct `.md` requests get the same headers plus `X-Robots-Tag: noindex`, which `vercelRoutes()` always sets because it takes no config, and HTML pages get `Link: </page.md>; rel="alternate"; type="text/markdown"` plus `Vary: Accept, User-Agent`. Without `paths` it covers every path without a file extension; with `paths` it covers only those pages.

`routes` can't be combined with `rewrites`, `redirects`, `headers`, `cleanUrls` or `trailingSlash` in the same `vercel.json`.

### applyVercelBuildOutput

```ts
function applyVercelBuildOutput(options?: { outputDir?: string; paths?: readonly string[] }): Promise<void>;
```

Reads `config.json` in `outputDir` (default `.vercel/output`), inserts the routes from `vercelRoutes(paths)` just before `{ "handle": "filesystem" }` and writes it back. Run it after a framework build that emits the Build Output API, such as `@astrojs/vercel`, SvelteKit's `adapter-vercel` or Nuxt's `vercel` preset.
