> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Targets with handlers

> Run your own Node code as a target's performer: on the managed target sandbox, or on AWS Lambda, Cloud Run or any HTTPS server you deploy.

Bijection's kernel never runs compute. Queries and mutations do no I/O, and
work outside a transaction is a [target](https://docs.bijection.com/functions/effects.md). When that work is
your own code, such as a vendor SDK, a scrape or a multi-request protocol,
declare a target with no `via`. A **handler** then performs it: a plain Node
module that gets the task's args and returns the target's value.

A target with a handler is a [slot](https://docs.bijection.com/operate/placement.md) of the `handler@1`
protocol, named by its path. Who runs the handler is
[placement](https://docs.bijection.com/operate/placement.md), not code:

* **Managed** (the default): the installation's host runs it in a fresh
  sandbox per request. You deploy nothing.
* **Your own endpoint**: you deploy the handler on [AWS Lambda](https://docs.bijection.com/functions/targets/lambda.md),
  [Cloud Run](https://docs.bijection.com/functions/targets/cloud-run.md) or any HTTPS server, and bind the
  target to it in the installation's bindings file.

Both speak the same protocol as any `http` target, so the kernel treats them
alike.

## Declare the contract

The contract is an ordinary target declaration with a `handler`: the module
that performs it and the origins it may reach. The handler module imports the
contract too, so both sides share one type.

```ts bijection/scoring.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { label, secret, t, target } from "@bijectionhq/bijection";

/** The vendor's API key. Set it with `bijection secret set scoring.vendorKey`. */
export const vendorKey = secret();

export const score = target({
  label: label.public,
  handler: { module: "handlers/score.ts", egress: ["https://api.vendor.com"] },
  args: { applicant: t.string, income: t.decimal },
  returns: { score: t.number },
  refuses: { Unscorable: null },
  within: { minutes: 5 },
  secret: { vendor: vendorKey },
});
```

Place it in the app tree like any target (here at `scoring.score`), then
submit to it from a mutation:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
await ctx.submit(score, { applicant, income }, { once: ["score", applicant], then: scored.with({ applicant }) });
```

`scored` receives `{ applicant, result }`, where `result` is a `Result` of the
target: its value, `Unscorable`, `Failed`, `Expired` or `Unknown`.

## Receive at a member's label

Use `label: tenants` or `label: tenants.and(vendor)` on a target or receiver
to take its member from the submitting transaction's commit label. The
request must name exactly one member of that family. The kernel resolves
the rule again at claim from the recorded request label. The Fate and its
continuation live at the join of the request label and the resolved target
label. The deployer's grant ceiling must clear `tenants.all` and any fixed
tags in the rule.

A receiver credential or handler secret declared with
`secret({ under: tenants })` uses that member's value, sealed at its member
label. The request carries the same member's erasure unit. A request cannot
select a member through its arguments.
The lock records the provider assumption that replies for a member depend
only on requests that flow to that member. Shared throttling, errors,
latency, and provider-side memory can expose activity across members.

## Write the handler

```ts handlers/score.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { handler, refuse } from "@bijectionhq/target-handler";
import { score } from "../bijection/scoring";

export default handler(score, async ({ args, secrets }) => {
  const reply = await fetch("https://api.vendor.example/score", {
    method: "POST",
    headers: { authorization: `Bearer ${secrets.vendor}` },
    body: JSON.stringify({ applicant: args.applicant, income: args.income.toString() }),
  });
  if (reply.status === 422) refuse("Unscorable", "The vendor has no file for this applicant");
  const { value } = await reply.json();
  return { score: value };
});
```

* `args` are decoded by the target's declared types.
* `refuse(code, message)` settles the task with one of the target's `refuses`.
  Any other throw settles it `Failed`.
* A handler does not read or write the app's data. The submitting mutation
  passes in everything the handler needs, and the continuation writes the
  result, files included.

## Run it on the managed sandbox

An unbound target runs managed: no binding is needed. `bijection deploy`
builds the handler module for Node and ships it with the deployment. The build is pinned by its digest: the target's destination names
`<path>@<SHA-256 of the built artifact>`, so `bijection.lock` shows which handler
code each target runs, and the provider runs only the artifact whose bytes
match that digest.

The managed sandbox runs each request in a fresh sandbox. The handler's
`fetch` and Node `http(s)` go through the sandbox's egress proxy, which admits
only the `egress` origins (`https://host[:port]`; the default `[]` reaches
nothing). Raw sockets, child processes and native addons are refused. A
declared secret reaches the handler only as a placeholder, which the proxy
replaces with the secret's value on the way out to an `egress` origin, so the
clear value never enters the sandbox.

A managed target has no token. The installation signs each delivery to the
managed sandbox with a key the two share, and the sandbox refuses an
unsigned, expired or replayed request before any handler runs.

Where the installation's host offers no `handler@1` provider, as on a private
installation by default, deploy refuses with `PlacementUnavailable`
(`NotOffered`). Bind the target to your own endpoint instead.

## Run it yourself

Bind the target to an `endpoint` in the installation's bindings file. `url` names the
installation input that holds the URL, `hosts` the hosts it may connect to,
and `credential` the secret that holds the target's token:

```ts bindings.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { placement } from "@bijectionhq/bijection";
import app from "./bijection/app";
const { bind, endpoint, env, bindings } = placement;

export default bindings([
  bind(app.scoring.score, endpoint({
    url: env("SCORING_URL"), hosts: ["score.example.com"], credential: "scoring.score.token",
  })),
]);
```

Set the URL and the token on the installation. The binding names the input,
allowed hosts and credential. A deploy trial reports the evaluated URL and
the placement move.

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection env set SCORING_URL https://score.example.com/scoring.score
bijection secret set scoring.score.token
bijection deploy --bindings bindings.ts --trial
```

The handler checks every request against the target's token. Set
`BIJECTION_TARGET_TOKEN` to the same value where the handler runs. The
`handler.module` on the target is not built or shipped for a target you bind
to an endpoint; you build and deploy it yourself. Declared
secrets arrive as request headers, so the handler reads them as
`secrets.<name>` wherever it runs.

* [AWS Lambda](https://docs.bijection.com/functions/targets/lambda.md)
* [Cloud Run](https://docs.bijection.com/functions/targets/cloud-run.md)
* Any Node server: `serve(handler)` from `@bijectionhq/target-handler/serve`
  listens on `$PORT`, or 8787.

## The protocol

A handler request is one `POST` whose JSON body is the task's args. It carries
each declared secret in `Bijection-Secret-<name>` and, for an endpoint
binding, the target's token in `Bijection-Target-Token`. `egress` applies to
the managed sandbox only: your own endpoint reaches whatever its deployment
allows. The handler
answers with:

| Answer | The task settles |
| - | - |
| 2xx, JSON body | `ok` with that value |
| 4xx, `{ "code", "message" }` naming a declared code | with that code |
| other 4xx (except 408, 425 and 429) | `Failed` |
| 408, 425 or 429 without a declared code, any 5xx, or no answer | in doubt (see below) |

Bijection sends a request to your own endpoint at most once,
and a lost answer is `Unknown`, which is final. Make that handler's effect safe
to reconcile, for example by passing a key from its args to your vendor as an
idempotency key.

A managed target's receiver is `fenced`. Each request carries the task's key
in `Idempotency-Key` and its deadline in `Bijection-Request-Expires`, and the
managed sandbox runs each key once, on any of its replicas. When an answer is
lost, Bijection sends the request again, and the provider answers with the
result it kept for that key without running the handler a second time. A run
lost mid-way, such as one whose sandbox was lost, stays in doubt and settles
`Unknown`.
The handler has
the target's `within` to answer, up to the receiver window.

A task runs and settles at the placement generation it was submitted under.
When you change the target's binding and deploy, tasks already submitted
finish on the old provider and new submits go to the new one
([moves](https://docs.bijection.com/operate/placement.md#switch-providers)).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.