Skip to main content
This guide shows how to send transactional email from NestJS with AhaSend, keep credentials on the server, and test a sandbox send. In NestJS the send belongs in an injectable service. The webhook needs one decision made at bootstrap: without { rawBody: true } on NestFactory.create, there is nothing left to verify the signature against. 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

  • Node.js 22 or newer
  • An AhaSend account with a verified sending domain
  • An API key with the messages:send:{yourdomain.com} scope, 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 with sandbox: 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 Node.js 22 or newer. Save this as quick-send.mjs:
quick-send.mjs
Run node --env-file=.env 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

For local development, add your credentials to an uncommitted .env file, which @nestjs/config loads. In production, inject the same variables from your platform’s secret manager:
.env
Enable the config module globally in AppModule, and register the throttler the send route uses below:
app.module.ts

Create the Client

Wrap AhaSendClient in an injectable service. Nest providers are singletons by default, so this reuses one configured client and any optional local rate limiter across requests. The SDK still creates a fresh automatic idempotency key for each logical send call and reuses it only for that call’s internal retries:
mail/ahasend.service.ts
A 202 is a multi-status response: result.data holds one entry per recipient, and an individual recipient can come back with status: "error" and a null id (a suppressed address, for example) while the call itself succeeds. Inspect every entry, not just the first.

Send an Email from a NestJS Controller

Do not expose a send-any-email route to unauthenticated clients. This example protects a backend-to-backend HTTPS route with a long random bearer token, and puts a rate limit in front of the token check so a stolen or brute-forced token cannot turn the route into an open mail relay. If your app already authenticates users, replace this guard with your existing guard and load the recipient address from your trusted user record instead of accepting an arbitrary address from the browser.
mail/internal-auth.guard.ts
Use a concrete DTO so Nest has runtime validation metadata:
mail/welcome.dto.ts
mail/mail.controller.ts
ThrottlerGuard is bound to this controller rather than registered as an APP_GUARD: a global throttler would also answer AhaSend’s webhook deliveries with 429, and more than 100 consecutive failed attempts disable the webhook. Behind a reverse proxy, enable Express’s trust proxy setting as well, or every request looks like it comes from the proxy and shares one bucket. The stable, hashed signup ID above lets a retry reuse the same idempotency key without putting a customer identifier in request metadata. Keep the payload stable for a given signup ID; reusing a key with a different payload is rejected. The send example uses sandbox: true to validate the request without delivering anything. It changes the request body, so give a sandbox send a different idempotencyKey from the live send it stands in for.

Handle Webhooks

There is no Nest-specific adapter, so use the SDK’s generic WebhookVerifier directly. It needs the raw request body, which Nest can retain for you: pass rawBody: true to NestFactory.create, and Nest exposes the unparsed bytes as req.rawBody alongside the parsed body.
main.ts
Then verify and dispatch in a controller. Constructing the verifier through ConfigService ensures .env has been loaded before the secret is read. verifier.parse() verifies the signature and timestamp before it parses the event:
mail/webhook.controller.ts
isAhaSendError identifies the failure by brand rather than instanceof, so a forged signature still becomes an opaque 400 — not a 500 that tells the sender which check failed — even when two copies of the SDK end up in the dependency tree. This minimal receiver verifies and acknowledges events without side effects. Before adding side effects, atomically record the webhook-id header with durable work (for example, an outbox row), acknowledge duplicates with a 2xx response, and process the work idempotently. Timestamp verification alone does not deduplicate a valid replay within the accepted window. Keep event.data out of your logs as you add that handling: it carries the recipient address, sender, and subject, plus the opener’s IP and user agent on open and click events. The JSON parser is capped at 30,000,000 bytes, matching the SDK verifier. This is a global parser limit; set a smaller limit at your proxy for the send route. Cap concurrent webhook work, and do not start untracked background work after responding. 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

Nest only captures the raw body when you pass { rawBody: true } to NestFactory.create, and the capture rides on Nest’s built-in body parser — passing bodyParser: false disables it just as surely. Without the raw bytes, this controller rejects the request. If you switch to the Fastify adapter, follow Nest’s Fastify raw-body setup and use Fastify’s request type instead of Express’s Request type.
Beyond a missing raw body, check that AHASEND_WEBHOOK_SECRET matches the dashboard value exactly (including the aha-whsec- prefix) and that no proxy in front of Nest rewrites the request body (which invalidates the HMAC).
The API key is missing, malformed, or revoked. config.getOrThrow fails fast at boot if the variable isn’t loaded. Verify .env sits in the project root and ConfigModule.forRoot runs before AhaSendService is instantiated.
The from address must belong to a verified sending domain on your account. Check domain status in the dashboard.