Receive webhooks in the customer's cloud
This example builds a webhook receiver that gives every customer their own endpoint in their cloud account and stores the payloads there. Your backend reads only the events it asks for, with commands: named calls into the deployment.
Architecture diagram. Left: Your cloud, Your backend. Right: Customer cloud containing api (Worker); events (Kv).
You build:
- A public
POST /webhooks/:sourceroute that GitHub, Stripe, or an internal system posts to. - A KV store in the customer's account that keeps every event.
- Two commands,
get-eventsandget-stats, that your backend calls to read them. - Per-deployment configuration through stack inputs (values set per deployment, not in code): a signing secret from you and a callback URL from the customer's admin.
Source: examples/webhook-api-ts.
When this fits
Use it when webhook payloads carry customer data that should stay in the customer's environment. It also fits senders that can only reach addresses inside the customer's network.
HTTP in, commands out
Webhook senders need an ordinary URL, so the Worker has a public endpoint. Depending on the customer's network, it's reachable from the public internet or only from internal networks.
Your backend doesn't use that URL. It reads events through commands, which reach the Worker through Alien: no second admin API, inbound firewall rule, or VPN.
Stack
import * as alien from "@alienplatform/core"
const events = new alien.Kv("events").build()
const stackInputs = alien.inputs({
webhookSigningSecret: alien.secret({
providedBy: "developer",
required: true,
label: "Webhook signing secret",
description: "Shared secret used by the API to verify incoming webhook signatures.",
minLength: 16,
env: {
name: "WEBHOOK_SIGNING_SECRET",
targetResources: ["api"],
},
}),
deliveryCallbackUrl: alien.string({
providedBy: "deployer",
required: true,
label: "Delivery callback URL",
description: "HTTPS endpoint that receives processed webhook delivery notifications.",
placeholder: "https://hooks.example.com/alien",
format: "url",
env: {
name: "DELIVERY_CALLBACK_URL",
targetResources: ["api"],
},
}),
})
const api = new alien.Worker("api")
.code({ type: "source", src: "./", toolchain: { type: "typescript" } })
.commandsEnabled(true)
.publicEndpoint("api")
.link(events)
.permissions("execution")
.build()
export default new alien.Stack("webhook-api")
.inputs(stackInputs)
.add(events, "frozen")
.add(api, "live")
.permissions({
profiles: {
execution: {
"*": ["kv/data-read", "kv/data-write"],
},
},
})
.build()events is a KV store in the customer's account. It's frozen: the admin creates it during initial setup (the one-time step with their own credentials), and later releases can't delete the stored events.
The Worker is live, so every release replaces it. See Frozen and live.
The stack also declares two inputs: values that differ per deployment and don't belong in code.
| Input | Who provides it | How | Reaches the Worker as |
|---|---|---|---|
webhookSigningSecret | You, the developer | alien onboard customer-1 --secret-input webhookSigningSecret=..., or the API | WEBHOOK_SIGNING_SECRET |
deliveryCallbackUrl | The customer's admin | The deployment portal (the setup page Alien hosts for the admin) or a setup template, validated as a URL | DELIVERY_CALLBACK_URL |
- A developer input never appears on the customer's screens.
- A deployer input is a question the admin must answer before the deployment works, so keep those few.
targetResources: ["api"]sets the environment variable on theapiWorker only.
The handlers in this example don't read either variable yet. Before production shows how to use the signing secret.
Receive a webhook
app.post("/webhooks/:source", async c => {
const source = c.req.param("source")
const body = await c.req.json()
const ev = kv("events")
const event = {
source,
body,
headers: Object.fromEntries(c.req.raw.headers.entries()),
receivedAt: new Date().toISOString(),
}
const key = `${source}:${Date.now()}`
await ev.setJson(key, event)
return c.json({ received: true, key })
})One route serves every sender: the path segment names the source. Keys look like github:1729771200000, so one prefix scan finds every event from a source.
Read events back
KV scans return pages. A small helper follows the cursor across pages:
/** Iterate every key/value under a prefix, following the scan cursor across pages. */
async function* scanAll(store: Kv, prefix: string) {
let cursor: string | undefined
do {
const page = await store.scan(prefix, undefined, cursor)
for (const item of page.items) yield item
cursor = page.nextCursor
} while (cursor)
}The commands use it to return events to your backend:
command(
"get-events",
z.object({ source: z.string().optional(), limit: z.number().optional() }),
async ({ source, limit }) => {
const ev = kv("events")
const prefix = source ? `${source}:` : ""
const results: { key: string; value: unknown }[] = []
for await (const entry of scanAll(ev, prefix)) {
results.push({
key: entry.key,
value: JSON.parse(new TextDecoder().decode(entry.value)),
})
if (limit && results.length >= limit) break
}
return { events: results, count: results.length }
},
)
command("get-stats", z.object({ sources: z.array(z.string()) }), async ({ sources }) => {
const ev = kv("events")
const counts: Record<string, number> = {}
for (const source of sources) {
let count = 0
for await (const _ of scanAll(ev, `${source}:`)) count++
counts[source] = count
}
return { sources: counts }
})The Worker also serves GET /webhooks/:source/recent, which returns up to 20 events for one source, and GET /health.
Run it locally
alien init webhook-api-ts webhook-api
cd webhook-api
alien devLocally, KV is an embedded database under .alien/. Send a webhook to the URL alien dev printed:
curl -X POST <url>/webhooks/github \
-H "Content-Type: application/json" \
-d '{"action": "opened", "number": 42}'{ "received": true, "key": "github:1729771200000" }List events for that source over HTTP:
curl <url>/webhooks/github/recent{
"events": [
{
"key": "github:1729771200000",
"value": {
"source": "github",
"body": { "action": "opened", "number": 42 },
"headers": { "content-type": "application/json", "...": "..." },
"receivedAt": "2026-10-24T12:00:00.000Z"
}
}
],
"count": 1
}Then query the events as your backend would, in a second terminal:
alien dev commands invoke --deployment local-dev/default \
--command get-events --params '{"source": "github"}'
alien dev commands invoke --deployment local-dev/default \
--command get-stats --params '{"sources": ["github", "stripe"]}'{ "sources": { "github": 1, "stripe": 0 } }Test it
tests/webhook.test.ts deploys locally, posts a GitHub and a Stripe webhook, and checks that get-events keeps the two sources apart: every key in the GitHub result starts with github:, and every key in the Stripe result with stripe:.
pnpm testDeploy it for a customer
alien login
alien link
alien release
alien onboard customer-1 --allow admin@customer-1.com --secret-input webhookSigningSecret="$(openssl rand -hex 32)"The secret must be at least 16 characters, as minLength requires. Then:
- The customer's admin opens the setup link, a URL to the deployment portal, and runs the initial setup once, with their own credentials.
- The portal asks for the delivery callback URL and checks that it's a URL.
- You read the endpoint's URL from the dashboard, or from the deployment's info under
resources.api.publicEndpoints.api.url, and give it to the webhook sender.
Later releases replace the Worker without the admin. The stored events stay.
Your backend reads events with CommandsClient:
import { CommandsClient } from "@alienplatform/commands"
const commands = await CommandsClient.forDeployment({
deploymentId: customer.deploymentId,
apiKey: process.env.ALIEN_API_KEY!,
})
const { events } = await commands
.target("api")
.invoke<{ events: { key: string; value: unknown }[]; count: number }>("get-events", {
source: "github",
limit: 50,
})How it works on each platform
| Platform | api | events |
|---|---|---|
| AWS | Lambda with an HTTPS endpoint | DynamoDB table |
| Google Cloud | Cloud Run | Firestore collection |
| Azure | Container Apps | Table Storage table |
alien dev | Native process | SQLite file |
Before production
Verify signatures
The example stores any request that reaches the URL. Use the signing secret to reject forgeries. GitHub signs the raw body with HMAC SHA-256 in x-hub-signature-256:
import { createHmac, timingSafeEqual } from "node:crypto"
export function verifyGitHubSignature(rawBody: string, header: string | undefined): boolean {
if (!header) return false
const expected =
"sha256=" +
createHmac("sha256", process.env.WEBHOOK_SIGNING_SECRET!).update(rawBody).digest("hex")
if (header.length !== expected.length) return false
return timingSafeEqual(Buffer.from(header), Buffer.from(expected))
}Read the body with await c.req.text(), verify it, then JSON.parse it.
Other checks
- KV limits. A value is at most 24 KiB, and a key at most 512 bytes of
a-z A-Z 0-9 - _ : .. GitHub pull request events often exceed 24 KiB: store large bodies in Storage and keep a pointer in KV. - Valid keys. Validate
:sourceagainst a fixed list so it can't produce an invalid key. - Headers. The stored event includes every request header, signature and authorization headers too. Keep only the ones you need.
- Scan order. KV scans are unordered, so
/recentreturns up to 20 events for the source, not the 20 newest. - Key collisions. Two webhooks from one source in the same millisecond get the same key, and the second overwrites the first. Add a unique suffix, such as the sender's delivery ID.
Next
Chat with a private Postgres
A streaming Next.js chat app in the customer's cloud that answers from a private Postgres through a model served by the same cloud. No API keys, no database password in the app.
Event pipeline
One Worker that handles queue messages, new files in a bucket, and an hourly schedule inside the customer's account, with results your backend reads through commands.