AhaSend

Test email webhooks locally with the AhaSend CLI

Test email webhooks locally: AhaSend's CLI forwards live events to localhost, with no tunnel or public URL. Set it up, verify events and test bounces.

Farhad Hedayatifard
Farhad Hedayatifard
Guides
On this page

If you send email with AhaSend, one command forwards live email webhook events to localhost. So you can test email webhooks locally, with no tunnel and no public URL. This is the command:

ahasend webhooks listen --forward-to http://localhost:3000/webhook

The CLI forwards AhaSend's email events, such as deliveries, bounces and opens. It does not forward webhooks from other providers. If you know stripe listen from Stripe, this works the same way.

This post walks through one full test: set up, listen, verify and trigger. For every flag, see our docs page Test Webhooks Locally with the CLI.

Set up the CLI

You do these two steps once.

1. Install the CLI. On macOS and Linux, use Homebrew:

brew install ahasend/tap/ahasend

On Windows, use Scoop, npm or the PowerShell script. The install guide shows each way to install the CLI.

2. Log in. In your AhaSend account, create an API key with these scopes:

  • webhooks:read:all, webhooks:write:all and webhooks:delete:all, to manage the webhook.
  • messages:read:all, to get email events. Without this scope, the listener gets no deliveries, bounces, opens or clicks.

Then run this command. It asks for the API key and your account ID:

ahasend auth login

For more about the setup, such as profiles for production and staging, read the AhaSend CLI docs.

Test email webhooks locally

Start the listener, with the URL of your local server:

ahasend webhooks listen --forward-to http://localhost:3000/webhook

The CLI connects to AhaSend over a WebSocket. The events come in over this connection, so AhaSend does not need a public URL to reach your machine. When the connection starts, the CLI prints a banner. The banner shows the webhook ID, the forwarding secret and the forwarding URL.

Without --webhook-id, AhaSend makes a temporary webhook named DevMode webhook for <API key label>. ahasend webhooks list does not show this webhook, but the banner shows its ID. When you stop the listener, the CLI deletes the temporary webhook. For this, the API key needs the webhooks:delete:all scope. If the delete fails, the CLI prints the webhook ID and the command that deletes it.

To listen through a webhook that you made yourself, add --webhook-id. That webhook must be enabled. While you listen, its own URL also keeps getting its events:

ahasend webhooks update YOUR_WEBHOOK_ID --enabled
ahasend webhooks listen --webhook-id YOUR_WEBHOOK_ID --forward-to http://localhost:3000/webhook

How forwarding works

The CLI sends each event to your server as an HTTP POST with a JSON body. The body is exactly what AhaSend sent, with no changes. Each request has the three Standard Webhooks headers: webhook-id, webhook-timestamp and webhook-signature.

The CLI sends events one at a time, in the order they arrive. If your server is slow, the events wait in a queue. The queue holds up to 100 events and up to 32 MiB of data. If an event does not fit, the CLI does not forward it and tells you.

Does your local server use HTTPS with a self-signed certificate? Then add --skip-verify. It skips the certificate check for your server only. The CLI always checks the connection to AhaSend.

Verify a forwarded event

Before the CLI forwards an event, it signs the event again. For this, it makes a new secret on each run: the forwarding secret. The banner shows it on the line Forwarding secret (signs forwarded events).

Follow these rules when you verify an event:

  • Use the forwarding secret of this run, not the webhook's own secret.
  • Use the full secret, as printed, as the raw UTF-8 HMAC key. Do not base64-decode it.
  • Verify the raw request body before you parse the JSON.

Some Standard Webhooks libraries base64-decode the secret by default. So use their raw-key mode. This handler uses Node.js, Express and the standardwebhooks package:

import express from "express";
import { Webhook } from "standardwebhooks";

// The forwarding secret that the banner printed for this run
const wh = new Webhook(process.env.AHASEND_FORWARDING_SECRET, { format: "raw" });

const app = express();

app.post("/webhook", express.raw({ type: "*/*" }), (req, res) => {
  try {
    // Verify the raw body before you parse it
    const event = wh.verify(req.body.toString("utf8"), {
      "webhook-id": req.get("webhook-id"),
      "webhook-timestamp": req.get("webhook-timestamp"),
      "webhook-signature": req.get("webhook-signature"),
    });
    console.log("Verified:", event.type);
    res.sendStatus(200);
  } catch (err) {
    res.sendStatus(400);
  }
});

app.listen(3000);

Here is the same handler in Go, with NewWebhookRaw:

package main

import (
    "io"
    "log"
    "net/http"
    "os"

    standardwebhooks "github.com/standard-webhooks/standard-webhooks/libraries/go"
)

func main() {
    // The forwarding secret that the banner printed for this run
    wh, err := standardwebhooks.NewWebhookRaw([]byte(os.Getenv("AHASEND_FORWARDING_SECRET")))
    if err != nil {
        log.Fatal(err)
    }

    http.HandleFunc("/webhook", func(w http.ResponseWriter, r *http.Request) {
        // Verify the raw body before you parse it
        body, err := io.ReadAll(io.LimitReader(r.Body, 30_000_000))
        if err != nil || wh.Verify(body, r.Header) != nil {
            w.WriteHeader(http.StatusBadRequest)
            return
        }
        log.Printf("Verified: %s", body)
        w.WriteHeader(http.StatusOK)
    })

    log.Fatal(http.ListenAndServe(":3000", nil))
}

Both handlers answer 200 for a valid event and 400 for all other requests. Before you start your server, set AHASEND_FORWARDING_SECRET to the secret from the banner. In production, use the same code with your webhook's own secret. Signature verification has examples in more languages.

Trigger test events

You do not have to send a real email to see an event. Keep the listener running and open a second terminal. Then ask AhaSend for test events, with the webhook ID from the banner:

ahasend webhooks trigger YOUR_WEBHOOK_ID --events message.reception,message.bounced

You can also trigger opens and clicks, with message.opened and message.clicked.

To see only some event types, add --events when you start the listener, such as --events message.delivered,message.bounced. The CLI then does not show or forward the other events.

Contact events, such as contact.created, need an account with the marketing features.

Test a bounce with a sandbox send

Test events show you what an event looks like. A sandbox send goes one step further. AhaSend accepts and checks a real email, but does not deliver it. Then AhaSend sends the events of the result that you choose:

ahasend messages send --sandbox --sandbox-result bounce \
  --from [email protected] \
  --to [email protected] \
  --subject "Bounce test" \
  --text "Testing my bounce handler"

Put your verified domain in --from. The other results are deliver, defer, fail and suppress. A sandbox send does not use your monthly email credits. For this step, the API key also needs the messages:send:all scope.

A sandbox send makes no opens or clicks, because nobody reads the email. To test opens and clicks, trigger those events. Sandbox mode lists each result and the event it sends.

What happens when no listener runs

When you listen with --webhook-id, AhaSend turns on streaming for that webhook. Streaming stays on after you stop the CLI. AhaSend then keeps up to the last 100 events for the next listener. If 5 minutes pass with no new event, AhaSend drops the kept events.

The next ahasend webhooks listen --webhook-id for the same webhook shows the kept events first. Each kept event is marked REPLAY. So if you restart the listener in time, you get the events that you missed.

If an event arrives when 100 events are already kept, AhaSend drops the kept events and turns off streaming. Your webhook keeps sending events to its own URL. If the CLI could not delete a temporary webhook, for example because the computer shut down while it ran, AhaSend deletes it at this point.

What the CLI does not do

  • It does not reconnect. If the connection drops, the CLI stops with exit code 7. Start it again. If you listened through your own webhook, add --webhook-id to get the kept events.
  • It does not resend a forwarded request. If a request fails, or your server answers with a status outside 2xx, the CLI logs it and continues.
  • It makes a new secret on each run. Give your server the new secret each time.

Next steps

When you finish, press Ctrl+C. The CLI deletes the temporary webhook, so there is nothing to clean up.

Read more:

Webhooks and the sandbox are on every AhaSend plan, the free plan included. Start for Free.