---
title: Handler spec
description: The h(spec, run) factory and every field of HandlerSpec, with raw request handlers and streaming handlers.
related:
  - /lunas/write-handlers
  - /lunas/check-arguments-with-types
  - /http/serve-http-routes
---

`h(spec, run)` declares one handler: `spec` says what it takes, returns and may fail with, and `run` is its code.

```ts luna/lunas/list.ts
import { defineLuna, t, table } from "luna";

export const List = defineLuna({
  name: "List",
  key: { id: t.string() },
  schema: { items: table({ id: t.id(), text: t.string() }) },
  handlers: (h) => ({
    add: h({ args: { text: t.string() } }, (ctx, { text }) => {
      ctx.db.items.insert({ text });
    }),
  }),
});
```

## Reference

### h(spec, run)

`h` is passed to the `handlers` option of [`defineLuna`](/sdk/define-luna), typed for that luna type.

| Prop | Type | Default | Description |
| - | - | - | - |
| `spec` | `HandlerSpec` | - | What the handler takes and how it runs. |
| `run` | `(ctx, input) => R \| Promise<R> \| AsyncGenerator` | - | The code. input holds the key fields and the arguments in one object. |

Returns a `Handler`, with `spec` and `run` as given.

### HandlerSpec

| Prop | Type | Default | Description |
| - | - | - | - |
| `args?` | `Record<string, Ty> \| t.request()` | `{}` | The arguments, checked before run starts. t.request() takes the raw HTTP request instead. |
| `returns?` | `Ty` | - | The result's type, checked before the result is sent. Without it, any JSON. |
| `errors?` | `Record<string, Ty>` | - | The errors the handler may fail with, by code, each with the type of its data. |
| `query?` | `boolean \| { maxStale: number \| string }` | `false` | Makes the handler read only. With maxStale, a read copy this far behind may answer calls from outside while the luna is busy. |
| `shared?` | `boolean` | `false` | For a query whose result depends only on its arguments and the luna's data: apps subscribed to the same query share one run each time the data changes. |
| `exclusive?` | `boolean` | `false` | No other handler starts on the luna until this one finishes. |
| `requires?` | `"exists"` | - | Refuses calls to a luna that has no stored data yet, with NotFound. |
| `durable?` | `boolean` | `false` | Each call or message starts a durable run that survives crashes and can wait with ctx.step, ctx.sleep and ctx.waitFor. |
| `route?` | `string \| RouteSpec` | - | An HTTP method and path that also reach the handler, such as "GET /lists/:id". |
| `description?` | `string` | - | What the handler does. Kept with the app, and given no other meaning. |

### RouteSpec

The long form of `route`. [Serve HTTP routes](/http/serve-http-routes) covers each field.

| Prop | Type | Default | Description |
| - | - | - | - |
| `path` | `string` | - | A method (GET, POST, PUT, PATCH or DELETE) and a path with :params and an optional trailing *. |
| `auth?` | `"none" \| "token" \| "publishable"` | `"publishable" for a public type, "token" for a private one` | Who may call the route. |
| `cors?` | `{ origins: string[]; credentials?: boolean; headers?: string[]; exposeHeaders?: string[]; maxAge?: number \| string }` | - | Browsers on other sites that may read the answers. |
| `rateLimit?` | `{ limit: number; window: number \| string; per?: "ip" \| "credential" }` | - | At most limit requests each window, per IP address by default. More are refused with 429. |
| `errors?` | `Record<string, number>` | - | The HTTP status for each declared error code. Others answer 422. |
| `key?` | `Record<string, string>` | - | Where key fields not in the path come from: "query:<NAME>", "header:<NAME>" or "param:<NAME>". |

## Good to know

- A handler's name starts with a lower-case letter and holds letters, digits and `_`, up to 64 characters. An error code starts with a capital letter.
- Arguments that do not match `args` fail the call with [`Invalid`](/errors/invalid). Unknown fields are refused, and an optional argument may be left out or `null`.
- A result that does not match `returns` fails the call with [`Internal`](/errors/internal), and so does `ctx.fail` with a code that is not in `errors`.
- A declared error from a luna you called passes through your handler when your handler declares the same code. Otherwise it reaches your caller as `Internal`.
- A query that writes fails with `Internal`.
- A durable handler cannot be a query, stream, or take the raw request.
- A handler with `args: t.request()` declares no other arguments. Called by name instead of through its route, its arguments arrive as a JSON body.
- Any handler may return a web `Response`. A route sends it as it is. A caller through an SDK gets its body, or an [`HttpError`](/sdk/errors) when the status is 400 or above.
- An `async function*` handler streams what it yields. Through a route each value goes out as it comes, and `sse()` gives it an id or event name. A caller that cannot stream, such as another luna, gets an array of everything yielded once the handler ends.

## Examples

### Check the result and refuse with an error

```ts luna/lunas/list.ts
add: h(
  { args: { text: t.string({ maxLength: 200 }) }, returns: t.int(), errors: { Full: t.object({ limit: t.int() }) } },
  (ctx, { text }) => {
    if (ctx.db.items.count() >= 100) ctx.fail("Full", { limit: 100 });
    return ctx.db.items.insert({ text });
  },
),
```

### Share one live query between apps

```ts luna/lunas/list.ts
all: h({ query: { maxStale: "1s" }, shared: true }, (ctx) => ctx.db.items.find({ orderBy: "id" })),
```

### Refuse calls to lists that do not exist

```ts luna/lunas/list.ts
rename: h({ args: { item: t.int(), text: t.string() }, requires: "exists" }, (ctx, { item, text }) => {
  ctx.db.items.update({ where: { id: item }, set: { text } });
}),
```

### Take the raw request

The `:id` parameter fills the `id` key field.

```ts luna/lunas/list.ts
hook: h({ args: t.request(), route: { path: "POST /lists/:id/hook", auth: "none" } }, async (ctx, req) => {
  if (req.headers.get("x-token") !== ctx.env.HOOK_TOKEN) return new Response("wrong token", { status: 401 });
  const { text } = (await req.json()) as { text: string };
  ctx.db.items.insert({ text });
  return new Response(null, { status: 204 });
}),
```

### Stream server-sent events

Import `sse` from `"luna"`.

```ts luna/lunas/list.ts
progress: h({ route: "GET /lists/:id/progress" }, async function* (ctx) {
  for (const item of ctx.db.items.find({ orderBy: "id" })) {
    yield sse({ data: item, id: item.id });
  }
}),
```
