WebhookVerifier on the raw request body.
Use a send-only key from Credentials → Add → API Key v2 with messages:send:{your-domain}. Use messages:send:all when sending from many domains. For management tasks such as creating a webhook, use a separate full key from Account Settings → API Keys with the needed scopes. See send-only credentials and authentication.
Keep credentials on the server. Use sandbox mode for tests. Reuse a stable, business-event idempotency key only with the exact same payload; use different keys for sandbox and live sends. Check every recipient’s status and return a failure when any item is error; HTTP 202 alone does not mean every recipient was accepted.
For webhooks, verify the raw request bytes using the full secret as the raw UTF-8 HMAC key, including its aha-whsec- or aha-rsec- prefix. Never base64-decode the secret. The AhaSend SDK verifiers handle this. These examples use a 30,000,000-byte webhook body limit; a hosting platform may impose a smaller limit. Acknowledge verified unknown event types with 2xx. See verification and retry policy.
Prerequisites
- Bun installed
- An AhaSend account with a verified sending domain
- An API key with the
messages:send:{your-domain}scope (messages:send:allfor sending from many domains), and your account ID
Install the SDK
Try a Sandbox Send
Run this short SDK check locally before adding the longer server integration below. Use a verified sender, a send-only API key, and your account ID. It sends to a reserved test address withsandbox: true, so no email is delivered.
In the server project directory, add .env to .gitignore, then create .env with AHASEND_API_KEY, AHASEND_ACCOUNT_ID, and AHASEND_FROM (an address on your verified domain). Keep these values out of browser code and AI prompts. Use Bun. Save this as quick-send.mjs:
quick-send.mjs
bun run quick-send.mjs from that directory. The output lists each recipient status; queued or scheduled means accepted for sandbox processing. The process exits with a failure if the request or any recipient fails. Continue below for the full integration.
Configure Environment Variables
Add your credentials to.env. Bun loads it automatically, no dotenv needed:
.env
Create the Client
Create the client once at module scope and reuse it across requests:src/lib/ahasend.ts
Send an Email from an Elysia Route
Elysia validates and types the body for you when you attach at.Object schema:
src/index.ts
onRequest rather than in the handler because Elysia parses the body and runs the t.Object schema before the handler executes: a check inside the handler would let an unauthenticated caller push a full 30 MB body through the JSON parser and read back a validation error describing your schema. onRequest runs before route matching, so it is the only hook that rejects the request ahead of parsing. It matches on the path rather than on the route, which is why the path is a single constant shared with .post() — a guard that names the path separately silently stops protecting the endpoint the day the route is renamed or the instance gains a prefix.
Keep the onError handler too. Elysia’s default error response returns the thrown error’s message to the caller and logs nothing, so an unexpected failure would hand internal detail to whoever made the request — including on the webhook route, which anyone who finds the URL can reach. Returning nothing for VALIDATION, PARSE, and NOT_FOUND leaves Elysia’s own 422, 400, and 404 responses in place, so a caller’s malformed JSON is not reported as a server fault or logged as one.
Call this route only from trusted server-side code with Authorization: Bearer <WELCOME_ENDPOINT_TOKEN>. Serve both endpoints only over HTTPS, terminating TLS at Elysia or a trusted reverse proxy. Replace the token check with your application’s normal authentication and authorization if the endpoint is user-facing, and add rate limiting and a smaller per-route body limit at your reverse proxy — maxRequestBodySize is a server-wide setting, so on its own it lets a 30 MB body reach either path. Never expose a recipient-controlled send endpoint without access control.
A 202 is multi-status: result.data carries one entry per recipient, and an individual recipient can come back status: "error" with a null id (a suppressed address, say) while the call itself succeeds, so check every entry, not just the first.
The SDK retries transient failures automatically, but a retry after a 5xx can still send twice. When a duplicate would be expensive, pass a stable key as the second argument: ahasend.messages.send(message, { idempotencyKey: "stable-business-key" }). Reuse that key only with the exact same request payload — the API matches on a hash of the body as well as the key, and answers a mismatched replay with a 422. Stored non-server-error results are replayed for 24 hours; a server error releases the key so the retry re-executes.
Add sandbox: true to the send request to validate it without delivering anything. Sandbox is a body field, so a key already spent on a sandbox send is rejected when the same key is replayed for the live send — give the two runs different keys.
Handle Webhooks
There is no Elysia-specific adapter, so use the genericWebhookVerifier, which needs the raw request body. Elysia normally parses supported content types during its parse lifecycle; set parse: "none" on this route so the underlying Request remains untouched. Bound the stream while reading it so an oversized unauthenticated body is rejected before it is fully buffered.
src/index.ts
verifier.parse() accepts the Fetch Headers object from request.headers directly, and it is asynchronous, so await it. Keep parse: "none", and keep the webhook route free of plugins or hooks that consume request.body before the handler.
Narrow the catch to AhaSendWebhookVerificationError and rethrow anything else. A rejected signature answers 400, while a bug of your own reaches onError and becomes a logged 500 that AhaSend retries. Failed deliveries are delivered with 6 attempts over about 16 minutes, and a webhook is disabled automatically after more than 100 consecutive failed attempts, so reporting your own bugs as bad signatures quietly spends that budget.
Create the webhook in your AhaSend dashboard pointing at https://your-app.com/webhooks/ahasend, and copy its secret into AHASEND_WEBHOOK_SECRET exactly as shown (including the aha-whsec- prefix).
Going Further
For substitutions, attachments and scheduled sends, use the sending guide. The Node.js SDK and Go SDK references explain client options, per-recipient results and retries. Use idempotency rules when your application retries a business operation.Troubleshooting
Webhook verification always returns 400
Webhook verification always returns 400
The most common cause on Elysia is a consumed body. Keep
{ parse: "none" } on the webhook route, do not add a body schema, and make sure no plugin or hook reads request.body first. Also confirm AHASEND_WEBHOOK_SECRET matches the dashboard value exactly (including the aha-whsec- prefix).422 validation error from Elysia instead of my handler running
422 validation error from Elysia instead of my handler running
Elysia rejects requests that fail the
t.Object body schema before your handler executes. Check the client is sending Content-Type: application/json and the field names match the schema.401 AhaSendAuthenticationError
401 AhaSendAuthenticationError
The API key is missing, malformed, or revoked. Bun loads
.env files relative to the working directory, so make sure you start the process from the project root and configure the same variable in production. Do not print any part of the key while troubleshooting.400 error mentioning the from address
400 error mentioning the from address
The
from address must belong to a verified sending domain on your account. Check domain status in the dashboard.Related Guides
- Before sending: verify a domain and create a send-only key.
- Other ways to send: REST API, SMTP, CLI quickstart, Node.js SDK and Go SDK.
- Request rules: API authentication, scopes, idempotency, errors and rate limits.
- Testing and events: sandbox mode, CLI webhook testing, event payloads, signature verification and delivery retries.
- Data and limits: retention, tracking and plans and feature availability.

