Build Your First Managed Worker
Write an HTTP handler in TypeScript, Rust, Go, or Python, package it with the runtime adapter, and deploy it with the managed HTTP template.
Build a managed HTTP Worker that returns a greeting and writes a log entry for each request. You write the handler and a worker.json manifest. You package them with the runtime adapter image and deploy them with the managed-http-worker template.
Before You Start
You need:
- A tenant with Workers enabled, and permission to create Workers and push images.
- The Contextual CLI, signed in, with Docker configured for the image hosts. Follow step 1 of Deploy Your First Worker.
- Docker that builds
linux/amd64images. - For TypeScript, Node.js 24 or later. The adapter image runs Node.js 24, and the bundle targets it.
The example uses Worker ID hello-managed and CLI configuration ID my-config. Replace them with your own.
1. Write the Handler and Manifest
Create a project directory. Add worker.json, the release manifest. It names the app, its handlers, the triggers each handler accepts, and the JSON Schema of its configuration:
{
"workerId": "hello-managed",
"version": "1.0.0",
"handlers": { "default": { "triggers": ["http"] } },
"configSchema": {
"type": "object",
"additionalProperties": false,
"required": ["greeting"],
"properties": { "greeting": { "type": "string" } }
}
}
Then add the handler in your language. In every language, the handler logs through the host and returns an HTTP response object: status, optional headers, and a string body.
Only the TypeScript adapter checks the Worker's CONFIG against configSchema, when the Worker starts. The Rust, Go, and Python adapters pass the configuration to your handler unchecked, so check the values you read.
Add "entrypoint": "index.cjs" to worker.json. Install the build tools and save the context types, as Get the Runtime Adapters shows. Adapter 0.10.0 has no library to import: your module default-exports the Worker, and the adapter supplies context at run time. Save src/index.ts:
import type { Context, Invocation } from "./worker-types"
type Config = { greeting: string }
export default {
apiVersion: "1",
name: "hello-managed",
version: "1.0.0",
// The TypeScript adapter has already checked the configuration against worker.json's configSchema.
parseConfig: (raw: unknown) => raw as Config,
async run(event: Invocation, context: Context<Config>) {
await context.logger.info("Request received", { id: event.id, trigger: event.trigger.type })
if (event.trigger.type !== "http") return
return {
status: 200,
headers: { "content-type": "application/json" },
body: JSON.stringify({ message: context.config.greeting, path: event.trigger.path }),
}
},
}
Save tsconfig.json so you can type-check before you bundle:
{
"compilerOptions": { "strict": true, "target": "es2024", "module": "preserve", "noEmit": true, "types": ["node"] },
"include": ["src"]
}
Copy the contextual-worker crate out of the adapter image, as Get the Runtime Adapters shows. Save Cargo.toml:
[package]
name = "hello-managed"
version = "1.0.0"
edition = "2024"
[dependencies]
contextual-worker = { path = "contextual-worker" }
[profile.release]
strip = true
lto = "thin"
Save src/main.rs. The name must match worker.json, and the version comes from Cargo.toml, so keep it equal to worker.json's:
use contextual_worker::{Worker, anyhow::Context as _, json};
fn main() -> std::process::ExitCode {
Worker::new("hello-managed", env!("CARGO_PKG_VERSION"))
.handler("default", |event, ctx| async move {
let greeting = ctx.config()["greeting"].as_str().context("CONFIG.greeting is required")?;
ctx.log().info("Request received", json!({"id": event.id(), "trigger": event.trigger()["type"]})).await?;
Ok(json!({
"status": 200,
"headers": {"content-type": "application/json"},
"body": json!({"message": greeting, "path": event.trigger()["path"]}).to_string(),
}))
})
.run()
}
Copy the contextual.io/worker module out of the adapter image, as Get the Runtime Adapters shows. Save go.mod:
module hello-managed
go 1.26
require contextual.io/worker v0.0.0
replace contextual.io/worker => ./contextual-worker
Save main.go. The name and version must match worker.json:
package main
import (
"context"
"encoding/json"
"errors"
"os"
"contextual.io/worker"
)
func main() {
w := worker.New("hello-managed", "1.0.0")
w.Handle("default", func(ctx context.Context, event worker.Event, c *worker.Context) (any, error) {
var cfg struct {
Greeting string `json:"greeting"`
}
if err := c.ConfigAs(&cfg); err != nil {
return nil, err
}
if cfg.Greeting == "" {
return nil, errors.New("CONFIG.greeting is required")
}
if err := c.Log().Info("Request received", map[string]any{"id": event.ID(), "trigger": event.Trigger()["type"]}); err != nil {
return nil, err
}
body, _ := json.Marshal(map[string]any{"message": cfg.Greeting, "path": event.Trigger()["path"]})
return map[string]any{"status": 200, "headers": map[string]string{"content-type": "application/json"}, "body": string(body)}, nil
})
os.Exit(w.Run())
}
Save src/main.py. The entrypoint in worker.json defaults to main.py; set it to load another file in src. The name and version must match worker.json:
import json
from contextual_worker import Worker
worker = Worker("hello-managed", "1.0.0")
@worker.handler("default")
async def default(event, ctx):
greeting = ctx.config.get("greeting")
if not isinstance(greeting, str):
raise ValueError("CONFIG.greeting is required")
await ctx.log.info("Request received", {"id": event.id, "trigger": event.trigger.get("type")})
return {
"status": 200,
"headers": {"content-type": "application/json"},
# Compact separators, so the body matches the other languages byte for byte.
"body": json.dumps({"message": greeting, "path": event.trigger.get("path")}, separators=(",", ":")),
}
To use third-party packages, add src/requirements.txt. List every package, including each dependency of a dependency, pinned with == and its --hash=sha256:, as pip-compile --generate-hashes or uv pip compile --generate-hashes writes them. The packaged image installs exactly those, as prebuilt wheels for Python 3.14 on linux/amd64, so a package without such a wheel cannot be installed.
2. Build
Compile the handler for linux/amd64.
Type-check, then bundle the handler and its imports into one CommonJS file:
npx tsc -p .
npx esbuild src/index.ts --bundle --platform=node --target=node24 --format=cjs --outfile=dist/index.cjs
Save Dockerfile.build. It copies the crate from the adapter image, builds the binary, and exports only the binary:
FROM images.contextual.io/worker/base/worker-adapter-rust:0.7.0 AS adapter
FROM rust:1.99.1-bookworm AS build
COPY --from=adapter /opt/contextual/worker-adapter-rust/contextual-worker /app/contextual-worker
WORKDIR /app
COPY Cargo.toml ./
COPY src ./src
RUN cargo build --release && cp target/release/hello-managed /worker-bin
FROM scratch AS binary
COPY --from=build /worker-bin /worker-bin
Build it and write the binary to build/worker-bin:
docker build --platform linux/amd64 -f Dockerfile.build --target binary -o build .
For repeatable builds, commit a Cargo.lock, copy it in beside Cargo.toml, and build with --locked.
Save Dockerfile.build. It copies the module from the adapter image, builds a static binary, and exports only the binary:
FROM images.contextual.io/worker/base/worker-adapter-go:0.4.0 AS adapter
FROM golang:1.27.3-bookworm AS build
COPY --from=adapter /opt/contextual/worker-adapter-go /app/contextual-worker
WORKDIR /app
COPY go.* *.go ./
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -o /worker-bin .
FROM scratch AS binary
COPY --from=build /worker-bin /worker-bin
Build it and write the binary to build/worker-bin:
docker build --platform linux/amd64 -f Dockerfile.build --target binary -o build .
go.* copies go.mod and, when your app has dependencies, go.sum. Keep both beside your source.
There is nothing to compile. The package command copies src into the release, and the packaged image installs requirements.txt and precompiles the modules.
3. Package the Release
Run the adapter image's package command. It checks worker.json, hashes the release, and writes .worker-image: a Docker build directory whose image is built FROM the adapter and labeled with the release and its digest. Saving a managed Worker whose image wasn't packaged this way fails with "A managed host must depend on exactly one release-labelled application".
docker run --rm --platform linux/amd64 -u "$(id -u):$(id -g)" -v "$PWD:/work" -w /work \
images.contextual.io/worker/base/worker-adapter-node:0.10.0 \
package worker.json dist .worker-image
docker run --rm --platform linux/amd64 -u "$(id -u):$(id -g)" -v "$PWD:/work" -w /work \
images.contextual.io/worker/base/worker-adapter-rust:0.7.0 \
package worker.json build/worker-bin .worker-image
docker run --rm --platform linux/amd64 -u "$(id -u):$(id -g)" -v "$PWD:/work" -w /work \
images.contextual.io/worker/base/worker-adapter-go:0.4.0 \
package worker.json build/worker-bin .worker-image
docker run --rm --platform linux/amd64 -u "$(id -u):$(id -g)" -v "$PWD:/work" -w /work \
images.contextual.io/worker/base/worker-adapter-python:0.4.0 \
package worker.json src .worker-image
Add the build output, the installed packages, and the copied library to .gitignore: .worker-image/, build/, dist/, node_modules/, .contextual/, and contextual-worker/.
4. Create the Worker
Save the Worker's configuration in config.json. It must be a JSON object. The TypeScript adapter also checks it against configSchema when the Worker starts:
{ "greeting": "Hello from a managed Worker" }
Create the Worker with the managed HTTP template:
ctxl workers create hello-managed \
--size small \
--managed managed-http-worker:0.10.0 \
--build .worker-image \
--option-from-file CONFIG=config.json \
--config-id my-config \
--pretty
The workers create command builds .worker-image, pushes the image to your organization's image host, and sets it as the template's IMAGE option. It then saves the Worker and starts deployment. Record the Worker version and image reference from the response.
5. Verify the Deployment
Open Workers > hello-managed > Deployment in Console V2. Wait until the instance is ready, then copy the Public Worker URL. Replace <worker-url> below with it:
curl --fail <worker-url>/orders/1
Expect {"message":"Hello from a managed Worker","path":"/orders/1"}.
Read the handler's log entries from the tenant log pipeline:
ctxl logs hello-managed --since 10m --config-id my-config --pretty
Expect one Request received entry for each request. Entries reach the tenant log pipeline only when the tenant has its own contextual/logs topic. The host also writes every entry to its own container output, so you can always read them there:
ctxl workers logs hello-managed -c host --config-id my-config
See Read Logs.
6. Change Configuration or Code
To change the greeting without rebuilding, edit config.json and update the option:
ctxl workers update hello-managed \
--option-from-file CONFIG=config.json \
--config-id my-config \
--pretty
To deploy a code change, remove the previous package output, repeat steps 2 and 3, then update with the new build. The package command refuses an output directory that already exists:
rm -rf .worker-image
ctxl workers update hello-managed \
--build .worker-image \
--config-id my-config \
--pretty
The update keeps the template selection and the options you do not supply. Raise the version in worker.json and in your code for each release, so logs and diagnostics identify it: the default export in TypeScript, Cargo.toml in Rust, and the Worker name and version in Go and Python. The name and version in your code must match worker.json, or the Worker doesn't start.
7. Remove the Test Worker
ctxl records delete native-object:worker/hello-managed --config-id my-config
The records delete command deletes the Worker immediately, without a confirmation prompt.
Next Steps
- Process events or run on a schedule with another template. See Templates and Options.
- Read and write records, process files, and call AI. See Platform Capabilities.
- Give a coding agent this page, the capabilities page, and the copied adapter library or, for TypeScript,
worker-types.ts. See Build with a Coding Agent.