# Serverless (fetchHandler)

> Run services and workflows on Vercel, Cloudflare Workers, AWS Lambda, Deno and Bun.

Source: https://cairnflow.dev/docs/workflows/serverless

`serve()` needs a long-running process that holds a port. On platforms that only take a function
`(Request) => Promise<Response>`, use the Fetch adapter from `@cairnflow/sdk/fetch`. It shares its
core with `serve()`.

```ts title="app/api/cairn/[...path]/route.ts"

const orders = service("OrderService", {
  async submit(ctx: ServiceContext, input: { amount: number }) {
    const receipt = await ctx.run("charge", () => charge(input.amount));
    return { receipt };
  },
});

const handler = fetchHandler({
  services: [orders],
  identityKeys: ["publickeyv1_…"],
});

export const GET = handler;
export const POST = handler;
```

Register the **base URL** where the handler is mounted, for example
`https://my-app.vercel.app/api/cairn`.

## Platforms

| Platform | Mount | Notes |
|---|---|---|
| Vercel (Next.js App Router) | `app/api/cairn/[...path]/route.ts`: `export const GET = handler; export const POST = handler;` | Node.js runtime. Register the production domain: preview deployments behind Deployment Protection answer with a login page |
| Cloudflare Workers | `export default { fetch: handler };` | Enable `compatibility_flags = ["nodejs_compat"]`. If turns fail once bodies reach 8 KiB, set `compression: false` |
| AWS Lambda (Function URL or HTTP API, payload v2) | `export const handler = lambdaHandler(fetchHandler({ … }));` | `lambdaHandler` comes from `@cairnflow/sdk/fetch`. Bodies travel base64-encoded both ways |
| Deno, Bun | `Deno.serve(handler)`, `Bun.serve({ fetch: handler })` | — |

The adapter is tested on Node.js (the standard Fetch API, and Lambda payload v2 events built by
hand), not yet on these platforms themselves. Report anything that behaves differently on one of
them.

## What is different from `serve()`

- **Request-response only.** Each wait whose result is not ready (`ctx.sleep`, a call, a promise)
  ends the request; cairnflow sends the journal again with the next one. It works everywhere, and
  costs more bytes and latency than streaming for handlers with many steps — which is why long
  agents belong on `serve()`.
- **A turn must finish within the platform's time limit** and within the handler's
  `inactivityTimeout` (see [Turn time limit](/docs/cloud/limits#turn-time-limit)). A step that
  runs longer is cut and runs again on the next attempt. Split long work into several short
  `ctx.run` steps.
- **Set `identityKeys`.** A function URL is public; without signature checks, anyone who knows the
  URL can call your handlers. The signature covers the request body and the host it was sent to.
  Set `identityHosts` to the public hosts you registered to bind it to this endpoint; it is
  required when a proxy in front of the function rewrites the `Host` header.
- **Keep files out of the journal.** In request-response mode the journal travels with every
  request. Pass files and images through `ctx.artifact` so the journal keeps only a reference;
  large JSON values are stored as segments (see [Payload](/docs/cloud/limits#payload)).
- **The replay cache is off by default.** A function process does not live across turns, so
  `fetchHandler` sets `replayCache: false`; turn it on only on a long-lived server such as
  `Deno.serve` or `Bun.serve`.

`fetchHandler` takes the same `identityKeys`, `identityHosts`, `segmentOrigins`, `compression`,
`replayCache`, `valueCacheBytes`, `maxValueBytes` and `maxTurnValueBytes` options as `serve()`
([serve() options](/docs/develop/services#serve-options)), plus `basePath`: when set, only
requests under exactly that path prefix are accepted; when unset, routing uses the end of the
path, so the handler can be mounted under any prefix.
