Updated Nov 30, 20266 min read

How to Let an AI Agent Add a Webhook Endpoint to Your AWS Backend

What a webhook endpoint needs beyond the handler, which cloud changes an agent would otherwise have to make by hand on AWS, and how to let it add the endpoint, the signing secret, the queue and the dedupe table in one change you can review and run locally.

Illustration for How to Let an AI Agent Add a Webhook Endpoint to Your AWS Backend

An AI coding agent can write a webhook handler in a minute. The endpoint around it needs a signing secret kept out of the repository, a queue behind it and a table that recognises duplicate deliveries, plus the secret entry, queue and permissions on AWS.

This guide shows what the endpoint needs and how to let an agent add all of it as a diff you can read.

What does a webhook endpoint need besides the handler?

PieceWhat it does
Raw bodyThe signature covers the exact bytes the provider sent, so the endpoint reads the body before any JSON parsing
Signature checkAn HMAC of the body compared with the header in constant time, as in the GitHub guide to validating deliveries
Fast responseReturn 2xx quickly, since providers such as Stripe retry events that are not acknowledged
QueueThe event is published and processed by a subscriber with retries and a dead-letter queue
DedupeA unique event identifier makes a redelivery a no-op
SecretThe signing secret is stored per environment and is not in the repository. Production values stay out of the agent context. Local values set for development are readable on the machine that runs encore run

The comparison has to be constant time, which in Node.js is crypto.timingSafeEqual, and it only works on buffers of equal length, so the length is checked first.

What would the agent have to change on AWS by hand?

On an ECS service the same feature touches more than the repository. A secret has to be created in Secrets Manager and referenced from the task definition, the execution role needs permission to read it, an SQS queue and a dead-letter queue have to exist with a redrive policy, and the task role needs permission to send and receive on them. Each of those is a console action, a CLI call or a Terraform change, which means either giving the agent credentials that can create IAM policies or splitting the work so a person finishes it.

The agent is also guessing at the shape of each resource, and a policy that is too broad or a secret value pasted into the wrong place is hard to spot in a pull request when the infrastructure change lives outside the code diff.

How does Encore let an agent ship the endpoint safely?

Encore

Encore is the safe way for AI agents to ship backend changes to your cloud: the endpoint, the secret declaration, the topic and the subscription are application code that the agent writes and runs locally, and the deploy to your own AWS account creates the Secrets Manager entry and the SNS topic with its SQS queues, as the AWS infrastructure docs describe. Encore provisions an IAM role for the service, or a service account on GCP. The agent works without cloud credentials, and the secret value is set by a person with encore secret set, so the production value is not in the repository. Local values set for development are readable on the machine that runs encore run.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create hooks --example=ts/hello-world$ cd hooks && mkdir -p webhooks/migrations

A prompt such as "Add a POST endpoint at /webhooks/payments that verifies an HMAC-SHA256 signature in the X-Signature header, publishes the event to a topic and processes it once in a subscriber" is enough for the agent to produce this. The webhooks folder also needs an encore.service.ts that exports new Service("webhooks"):

// webhooks/webhooks.ts import { api } from "encore.dev/api"; import { secret } from "encore.dev/config"; import { Subscription, Topic } from "encore.dev/pubsub"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { createHmac, timingSafeEqual } from "node:crypto"; const signingSecret = secret("PaymentsWebhookSecret"); const db = new SQLDatabase("webhooks", { migrations: "./migrations" }); interface PaymentEvent { id: string; type: string; payload: string; } const received = new Topic<PaymentEvent>("payment-events", { deliveryGuarantee: "at-least-once", }); async function readBody(req: AsyncIterable<Buffer | string>): Promise<Buffer> { const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(Buffer.from(chunk)); return Buffer.concat(chunks); } function validSignature(body: Buffer, header: string | undefined): boolean { if (!header?.startsWith("sha256=")) return false; const expected = createHmac("sha256", signingSecret()).update(body).digest(); const given = Buffer.from(header.slice("sha256=".length), "hex"); return given.length === expected.length && timingSafeEqual(given, expected); } export const payments = api.raw( { expose: true, method: "POST", path: "/webhooks/payments" }, async (req, resp) => { const body = await readBody(req); if (!validSignature(body, req.headers["x-signature"] as string | undefined)) { resp.writeHead(401); resp.end("invalid signature"); return; } let event: { id?: string; type?: string }; try { event = JSON.parse(body.toString("utf8")); } catch { resp.writeHead(400); resp.end("invalid json"); return; } if (!event.id || !event.type) { resp.writeHead(400); resp.end("id and type are required"); return; } await received.publish({ id: event.id, type: event.type, payload: body.toString("utf8") }); resp.writeHead(202); resp.end("accepted"); }, ); const _process = new Subscription(received, "process-payment-event", { handler: async (event) => { // A redelivery finds the identifier already stored and does nothing. const stored = await db.queryRow<{ id: string }>` INSERT INTO webhook_events (id, type, payload) VALUES (${event.id}, ${event.type}, ${event.payload}::jsonb) ON CONFLICT (id) DO NOTHING RETURNING id`; if (!stored) return; // Apply the business change here, in the same handler. }, retryPolicy: { minBackoff: "10s", maxBackoff: "5m", maxRetries: 5 }, });
-- webhooks/migrations/1_create_webhook_events.up.sql CREATE TABLE webhook_events ( id TEXT PRIMARY KEY, type TEXT NOT NULL, payload JSONB NOT NULL, received_at TIMESTAMPTZ NOT NULL DEFAULT now() );

The secret is set once per environment, with encore secret set --type dev,local PaymentsWebhookSecret for development and encore secret set --type prod PaymentsWebhookSecret for production, and a cloud deploy fails until every declared secret has a value. encore run starts Postgres locally and runs the topic in process, so a signed curl request exercises the whole path on a laptop. The raw endpoint docs cover the request and response objects, the secrets docs cover environment types, and the Pub/Sub docs cover retries and the dead-letter queue.

To deploy, follow Connect your cloud account and push, and the secret entry, the queues and the database appear in your account. With the infrastructure declared in the same files the agent edits, adding a second provider's webhook later is one more raw endpoint and one more subscription in a single change.

Best fit: Teams that want an AI coding agent to add webhook receivers to a backend on AWS without giving it cloud credentials, and with every change visible in the pull request.

What should you review in the agent's diff?

Check that the signature is computed over the raw body and compared in constant time, that the endpoint returns before doing slow work, and that the subscriber records the event identifier before it changes anything. Confirm that the secret is read through secret() and that no value appears in the code, tests or fixtures. Look at the retry policy and decide what should happen to an event that exhausts it, since it lands in the dead-letter queue and waits for a person. Finally, check the provider's documentation for the exact header name and signature format, because they differ between providers and the sample above uses a sha256= prefix.

Frequently asked questions

Can an AI coding agent safely add a webhook endpoint to an AWS backend?

Yes, when the endpoint, its signing secret and its queue are declared in application code and the agent never holds cloud credentials. With Encore the agent edits the repository and runs it locally, you review one diff, and the deploy to your AWS account creates the secret entry, the queue and the permissions.

How do you verify a webhook signature?

Compute an HMAC of the raw request body with the shared signing secret, using SHA-256 for most providers, and compare it with the signature header using a constant-time comparison. The body must be the unparsed bytes, since parsing and re-serializing the JSON changes them.

Why should a webhook endpoint put the event on a queue?

Providers expect a 2xx response within a short time and retry when they do not get one, so slow work in the request causes duplicate deliveries. Verifying the signature, publishing the event and returning 202 keeps the response fast, and a subscriber with its own retry policy does the work.

How do you handle duplicate webhook deliveries?

Store the provider's event identifier with a unique constraint and insert it with ON CONFLICT DO NOTHING before applying the change. If the insert returns no row, the event was already processed and the handler returns without doing anything.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders