---
title: Effect API
description: Use Agentside as an Effect service, with layers, typed errors and the prerender programs, through @usenotra/agentside/effect.
sidebar:
  order: 8
---

`agentside()` and the helpers in `@usenotra/agentside/build` are promise wrappers around Effect programs. If your app already runs on Effect, use those programs directly from `@usenotra/agentside/effect`: Agentside is a service you provide with a layer, every operation fails with typed errors, and remote sources go through Effect's `HttpClient`.

```ts
import { Agentside, layer, layerFetch } from "@usenotra/agentside/effect";
import { prerender, prerenderHtml } from "@usenotra/agentside/effect/build";
```

`@usenotra/agentside/effect` has no Node imports, so it runs on edge runtimes. The prerender programs read and write files, so they live in the Node-only `@usenotra/agentside/effect/build`.

## The Agentside service

`Agentside` is a `Context.Service`. Provide it with one of two layers:

| Layer | Requires | Use it when |
| --- | --- | --- |
| `layerFetch(config)` | nothing | You want the default fetch-based HTTP client. |
| `layer(config)` | `HttpClient.HttpClient` | You already provide an `HttpClient` (with your own tracing, proxy or test client). |

Both build the router and the cache once and fail with `InvalidConfig` if a route doesn't start with `/`.

| Member | Type |
| --- | --- |
| `match(path)` | `Match \| null` with `{ pattern, params, source }` for the route that matches a page path. |
| `serve(path, request, agent)` | `Effect<Served, ServeError>` that loads the twin with variants, retries, timeouts and the cache. |

`serve` takes the page path without `.md`, the request and the agent from `detectAgent`. It succeeds with `{ body, tokens, variant, cached }` and fails with one of the typed errors. Variant failures are already folded into the control, so a failure always belongs to the control twin.

## Example

```ts
import { Effect } from "effect";
import { detectAgent, type AgentsideConfig } from "@usenotra/agentside";
import { Agentside, layerFetch, markdownResponse } from "@usenotra/agentside/effect";

const config: AgentsideConfig = {
  routes: {
    "/pricing": () => renderPricingMarkdown(),
  },
};

const handle = Effect.fn("Site.markdown")(function* (request: Request) {
  const agentside = yield* Agentside;
  const agent = detectAgent(request.headers.get("user-agent"));
  return yield* agentside.serve("/pricing", request, agent).pipe(
    Effect.map(({ body, variant }) => markdownResponse(body, config, 200, { "X-Agentside-Variant": variant })),
    Effect.catchTags({
      NotFound: () => Effect.succeed(new Response("No twin", { status: 404 })),
      RenderFailed: () => Effect.succeed(markdownResponse("# Unavailable\n", config, 503)),
      RemoteFailed: (error) =>
        Effect.succeed(
          markdownResponse(error.status ? `# Upstream returned ${error.status}\n` : "# Upstream unavailable\n", config, 502)
        ),
      SourceTimeout: () => Effect.succeed(markdownResponse("# Timed out\n", config, 504)),
    })
  );
});

const response = await Effect.runPromise(
  handle(new Request("https://acme.dev/pricing.md")).pipe(Effect.provide(layerFetch(config)))
);
```

Provide the layer once at the edge of your app, so every request shares one router and one cache.

## Remote sources

Remote sources use `HttpClient` with `HttpClient.retryTransient`: transport errors and `408`, `429`, `500`, `502`, `503` and `504` responses are retried up to `retries` times (default 2) on a jittered exponential schedule, and the whole load is capped by `timeoutMs`. A `404` means the page has no twin. Any other non-2xx status fails with `RemoteFailed` and its `status`.

## Prerendering

`prerender(config, options)`, `prerenderHtml(options)` and `applyVercelBuildOutput(options)` are the Effect versions of the helpers in [`@usenotra/agentside/build`](/docs/static-sites). They take the same options. Pages are processed with bounded concurrency, and every failing page is collected into one `PrerenderFailed` error with a `failures` array of `{ path, reason }`, so a broken build lists everything at once. File access fails with `FileFailed` (with the `path` and the `operation`: `read`, `write` or `list`), and a page that can't be converted fails with `RenderFailed`.

`prerender` builds the full service, so it always needs an `HttpClient`, even when every route is local. Provide `FetchHttpClient.layer` from `effect/http` or your own. `applyVercelBuildOutput` decodes `.vercel/output/config.json` with Schema and fails with `InvalidConfig` if it isn't a valid Build Output config.

```ts
import { Effect } from "effect";
import { FetchHttpClient } from "effect/http";
import { prerender, prerenderHtml } from "@usenotra/agentside/effect/build";

const build = Effect.gen(function* () {
  yield* prerender(config, { outDir: "dist", paths: ["/", "/pricing"] });
  return yield* prerenderHtml({ dir: "dist", siteUrl: "https://acme.dev", llms: { title: "Acme" } });
}).pipe(
  Effect.catchTag("PrerenderFailed", (error) => Effect.die(new Error(`${error.failures.length} pages failed`))),
  Effect.provide(FetchHttpClient.layer)
);
```

## Tracing

Operations that do I/O or run once per process are `Effect.fn` spans: `Agentside.make`, `Agentside.fetchRemote`, `Agentside.prerender`, `Agentside.prerenderHtml`, `Agentside.convertPage`, file reads and writes, and `Agentside.applyVercelBuildOutput`. The per-request path (`serve` on a cache hit) is untraced on purpose: a span costs about a microsecond, which would double a cached response. Wrap `serve` in `Effect.withSpan` yourself if you want request spans.

## markdownResponse

`markdownResponse(body, config, status?, extraHeaders?, tokens?)` builds a `Response` with the same headers `handle` uses: `Content-Type`, `X-Markdown-Tokens`, `Vary`, `Cache-Control`, `X-Content-Type-Options` and `X-Robots-Tag` unless `noindex` is `false`. `handle` drops that header when it serves a twin on the page URL, unless `noindex` is `true`, so pass `noindex: false` when you answer a negotiated request yourself: by default `X-Robots-Tag: noindex` belongs only on `.md` URLs.

## CONTROL

`CONTROL` is the string `"control"`, the variant id reported when the route's own source is served.

## Errors

All errors are `Schema.TaggedError` classes. Match them with `Effect.catchTag`, `Effect.catchTags` or a `switch` on `_tag`.

| Error | Fields | When |
| --- | --- | --- |
| `NotFound` | `path` | No route matches or the source returned `null`. |
| `RenderFailed` | `path`, `cause` | A local source threw or rejected, or a page couldn't be converted. |
| `RemoteFailed` | `path`, `url`, `status?`, `cause?` | A remote source failed after retries. |
| `SourceTimeout` | `path`, `timeoutMs` | A source took longer than `timeoutMs`. |
| `InvalidConfig` | `message` | A route or a Build Output config is invalid. |
| `FileFailed` | `path`, `operation`, `cause` | Reading, writing or listing files failed while prerendering. |
| `PrerenderFailed` | `failures` | One or more pages failed during `prerender` or `prerenderHtml`. |

`ServeError` is the union of the first four.
