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

# Write a TypeScript function

> Write a TypeScript handler for the node:24 runtime, deploy it from source or as an image with a JSON Schema or Arrow contract, and invoke it.

This guide takes a TypeScript handler from a file on your machine to a
deployed, invoked function. It covers both contract kinds and both ways to
deploy: source files that Alchemy lays over the runtime image, and an OCI
image you build yourself.

The commands assume a server on `localhost:8780` with no auth, as in the
[Quickstart](https://alchemy.getgalaxy.io/pages/get-started/quickstart.md). With auth enabled, add
`-H "Authorization: Bearer $TOKEN"` to every call.

## The Node runtime

| | |
| - | - |
| Image | `<imagePrefix>/node:24`, `ghcr.io/galaxy-io/alchemy/runtime/node:24` by default |
| Base | `node:24-alpine` |
| Entrypoint | `node /app/handler.ts` |
| Libraries | Node's built-in modules and `apache-arrow` 21.0.0 |

Node runs `handler.ts` directly with its built-in type stripping, so there is
no compile step. Write TypeScript whose types can simply be erased, and import
local files with their `.ts` extension. The runtime's `package.json` sets
`"type": "module"`, so the handler is an ES module.

Nothing is installed at build time. A function built from source can import
Node's modules, `apache-arrow` and its own files under `/app`. A function that
needs other packages ships as an [image](#deploy-as-an-image).

`ListRuntimes` returns the exact runtime image for your server:

```sh theme={null}
curl -s localhost:8780/functions.v1.FunctionsService/ListRuntimes \
  -H 'Content-Type: application/json' -d '{}' \
  | jq -r '.runtimes[] | select(.id == "node") | .image'
```

## The protocol

For each invocation the supervisor starts `node /app/handler.ts` as a new
process, writes the input to stdin and closes it, takes stdout as the output
and streams stderr to the invocation's log. A non-zero exit is a crash, with
the exit status and the last 4 KiB of stderr as the error message. An
uncaught exception exits non-zero, so it is reported the same way.

A JSON Schema contract passes one JSON value each way. An Arrow contract
passes one Arrow IPC stream with exactly one record batch each way. See
[Contracts](https://alchemy.getgalaxy.io/pages/concepts/contracts.md).

Write diagnostics with `console.error`. `console.log` writes to stdout, which
is the output.

## Write a JSON handler

The runtime's JSON Schema starter reads one value and returns it:

```ts handler.ts theme={null}
import { readFileSync, writeSync } from "node:fs";

const handler = (event: unknown) => event;

const input: unknown = JSON.parse(readFileSync(0, "utf8"));
writeSync(1, JSON.stringify(handler(input)));
```

`readFileSync(0)` reads stdin to the end and `writeSync(1, ...)` writes stdout
before the process exits.

## Write an Arrow handler

An Arrow function receives a batch of rows and returns a batch with the same
number of rows in the same order. The runtime's Arrow starter:

```ts handler.ts theme={null}
import { readFileSync, writeSync } from "node:fs";

import { type Table, tableFromIPC, tableToIPC } from "apache-arrow";

const handler = (table: Table): Table => table;

const output = handler(tableFromIPC(readFileSync(0)));
writeSync(1, tableToIPC(output, "stream"));
```

[`examples/embed/typescript/handler.ts`](https://github.com/galaxy-io/alchemy/tree/main/examples/embed/typescript)
is a complete one. It reads `id` and `text` columns and returns per row the
cleaned text, its token count and a 64-dimension embedding.

The contract carries both schemas as serialized Arrow IPC. Build them for the
embed example with `apache-arrow`, in a directory where it is installed
(`npm install apache-arrow@21.0.0`):

```ts schemas.ts theme={null}
import { Field, FixedSizeList, Float64, Schema, Uint32, Utf8 } from "apache-arrow";

export const INPUT = new Schema([
  new Field("id", new Utf8(), false),
  new Field("text", new Utf8(), true),
]);
export const OUTPUT = new Schema([
  new Field("id", new Utf8(), false),
  new Field("cleaned_text", new Utf8(), false),
  new Field("token_count", new Uint32(), false),
  new Field("embedding", new FixedSizeList(64, new Field("item", new Float64(), false)), false),
  new Field("model", new Utf8(), false),
]);
```

```ts contract.ts theme={null}
import { type Schema, Table, tableToIPC } from "apache-arrow";

import { INPUT, OUTPUT } from "./schemas.ts";

const encode = (schema: Schema) => Buffer.from(tableToIPC(new Table(schema), "stream")).toString("base64");

process.stdout.write(JSON.stringify({ inputSchema: encode(INPUT), outputSchema: encode(OUTPUT) }));
```

```sh theme={null}
node contract.ts > arrow.json
```

This is how the web UI encodes the schemas from its field editor. Fields are
matched by position, name, type and nullability.

## Deploy from source

A function built from source names the runtime image and carries its files.
The server keeps them in its artifacts bucket and hosts extract them over the
image at `/app`, at most 64 files and 1 MiB in total. The runtime runs
`handler.ts`. Do not send a `package.json`: it would replace the runtime's,
and nothing is installed.

**1. Create the function**

```text Web UI theme={null}
1. Click New function.
2. Choose Code and pick Node 24 as the language.
3. Define the contract: JSON Schema, or Arrow with the
   fields from schemas.ts.
4. Replace the starter handler with your handler.ts.
5. Set resources and limits, name the function and click
   Create function.
```

```sh API (JSON Schema) theme={null}
IMAGE=$(curl -s localhost:8780/functions.v1.FunctionsService/ListRuntimes \
  -H 'Content-Type: application/json' -d '{}' \
  | jq -r '.runtimes[] | select(.id == "node") | .image')

jq -n --arg image "$IMAGE" --rawfile src handler.ts '{
  name: "echo-typescript",
  spec: {
    image: $image,
    protocol: "INVOCATION_PROTOCOL_EXEC",
    contract: {jsonSchema: {input: {type: "object"}, output: {type: "object"}}},
    source: {files: [{path: "handler.ts", content: ($src | @base64)}]}
  }
}' | curl -s localhost:8780/functions.v1.FunctionsService/CreateFunction \
  -H 'Content-Type: application/json' -d @- | jq '{id: .function.id, status: .version.status}'
```

```sh API (Arrow) theme={null}
jq -n --arg image "$IMAGE" --rawfile src handler.ts --slurpfile arrow arrow.json '{
  name: "embed-typescript",
  spec: {
    image: $image,
    protocol: "INVOCATION_PROTOCOL_EXEC",
    contract: {arrow: $arrow[0]},
    source: {files: [{path: "handler.ts", content: ($src | @base64)}]}
  }
}' | curl -s localhost:8780/functions.v1.FunctionsService/CreateFunction \
  -H 'Content-Type: application/json' -d @- | jq '{id: .function.id, status: .version.status}'
```

`protocol` is required and `INVOCATION_PROTOCOL_EXEC` is the only one
implemented. Leave `timeoutMs`, `maxConcurrency`, `retries` and
`resources` out to take the defaults: a 30 s timeout, no concurrency
limit, 2 retries, 1 vCPU and 128 MiB.

**2. Wait for the build**

The version starts in `BUILDING` and turns `READY` once a host has built
and snapshotted it. Only a ready version can be invoked.

```sh theme={null}
curl -s localhost:8780/functions.v1.FunctionsService/GetFunctionVersion \
  -H 'Content-Type: application/json' \
  -d '{"functionId": "<function-id>", "version": 1}' \
  | jq '.version | {status, statusMessage}'
```

> [!NOTE]
>
> Source builds need the server's `ARTIFACTS_BUCKET`. Without it,
> `CreateFunction` refuses a spec with `source`.

## Deploy as an image

Ship an image when the function needs packages beyond `apache-arrow`. Build
on the runtime so the entrypoint stays `node /app/handler.ts`. The embed
example's Dockerfile:

```dockerfile Dockerfile theme={null}
FROM ghcr.io/galaxy-io/alchemy/runtime/node:24
COPY handler.ts /app/
```

To add packages, copy your own `package.json` over the runtime's, keep
`apache-arrow` in it if you use Arrow, and run `npm install` in the
Dockerfile. Then build for the hosts' architecture and push:

```sh theme={null}
docker build --platform linux/amd64 -t registry.example.com/embed-typescript:1 examples/embed/typescript
docker push registry.example.com/embed-typescript:1
```

Create the function with that image and no `source`:

```sh theme={null}
jq -n --slurpfile arrow arrow.json '{
  name: "embed-typescript",
  spec: {
    image: "registry.example.com/embed-typescript:1",
    protocol: "INVOCATION_PROTOCOL_EXEC",
    contract: {arrow: $arrow[0]}
  }
}' | curl -s localhost:8780/functions.v1.FunctionsService/CreateFunction \
  -H 'Content-Type: application/json' -d @- | jq '{id: .function.id, status: .version.status}'
```

In the web UI, choose **Image** and enter the reference. The version runs the
digest the tag resolved to when it was built. See
[Deploy any OCI image](https://alchemy.getgalaxy.io/pages/guides/image-function.md) for private registries.

## Invoke it

POST the input to `/functions/<function-id>/invoke` with the contract's
content type.

```sh JSON theme={null}
curl -i localhost:8780/functions/<function-id>/invoke \
  -H 'Content-Type: application/json' -d '{"hello": "world"}'
```

```sh Arrow theme={null}
cat > input.ts <<'EOF'
import { writeFileSync } from "node:fs";
import { makeData, RecordBatch, Struct, Table, tableToIPC, Utf8, vectorFromArray } from "apache-arrow";
import { INPUT } from "./schemas.ts";

const children = [
  vectorFromArray(["a", "b"], new Utf8()).data[0],
  vectorFromArray(["Hello  World", null], new Utf8()).data[0],
];
const batch = new RecordBatch(INPUT, makeData({ type: new Struct(INPUT.fields), length: 2, nullCount: 0, children }));
writeFileSync("input.arrows", tableToIPC(new Table(INPUT, [batch]), "stream"));
EOF
node input.ts

curl -s localhost:8780/functions/<function-id>/invoke \
  -H 'Content-Type: application/vnd.apache.arrow.stream' \
  --data-binary @input.arrows -o output.arrows
```

The response carries `Alchemy-Invocation-Id` and `Alchemy-Version`. A handler
that throws answers `500` with the error as JSON, and one past its timeout
answers `504`. The function's **Invocations** tab shows each call with its
stderr, and the **Workbench** tab invokes it from the browser. See
[HTTP invoke](https://alchemy.getgalaxy.io/pages/usage/http.md) for versions, retries and async calls.

## Next steps

> [card] [Troubleshooting](https://alchemy.getgalaxy.io/pages/guides/troubleshooting.md)
>
> Read contract violations, crashes, timeouts and build failures.

> [card] [Runtimes and builds](https://alchemy.getgalaxy.io/pages/concepts/runtimes-and-builds.md)
>
> How a spec becomes a root filesystem and a snapshot.


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