Skip to main content
coreydaley.dev

Catching your app's outbound webhooks with MessagePit

Every app I’ve worked on eventually grows outbound webhooks. Order created, payment failed, user deleted: POST a JSON blob to a URL someone configured. Testing that locally has always meant a throwaway receiver you’ll delete next week, a tunnel to someone else’s request bin, or squinting at debug logs. Each of those either ships your payloads to a server you don’t control or makes you build something you’ll throw away.

MessagePit, my fork of Ralph Slooten’s Mailpit, already catches email and Twilio SMS without anything leaving your laptop. As of today it catches webhooks too. (Shipping it also broke CI in a way that had nothing to do with Go. More on that at the end.)

One Port, Any Request

MessagePit now starts a dedicated HTTP server on port 8026, next door to the UI on 8025. It accepts every request on any path and any method, stores it, and shows it in a new Webhooks tab.

docker run \
  -p 127.0.0.1:1025:1025 \
  -p 127.0.0.1:1775:1775 \
  -p 127.0.0.1:8025:8025 \
  -p 127.0.0.1:8026:8026 \
  ghcr.io/coreydaley/messagepit

That’s SMTP on 1025, the Twilio-compatible SMS endpoint on 1775, the UI and API on 8025, and the new capture server on 8026. All four are bound to loopback on purpose. The security section below explains why.

Point your app’s webhook URL at the capture server. Pick any path you like:

curl -X POST http://localhost:8026/hooks/orders \
  -H "Content-Type: application/json" \
  -H "X-Signature: sha256=abc123" \
  -d '{"event":"order.created","id":42}'

Open http://localhost:8025/webhooks and the request is already there. The list shows a colored method badge, the path, content type, body size, and a snippet of the body. The detail view splits the request into a summary, the parsed query parameters, every header, and the body. The body is pretty-printed when the content type contains json, so application/vnd.api+json gets formatted too.

Updates are live. The capture server writes to the same SQLite database and broadcasts on the same WebSocket bus Mailpit uses for email. A request appears in every open browser tab the moment your app sends it, along with an unread count.

The --webhook flag controls the bind address. Pass --webhook "" to turn the server off, or --webhook <ip>:<port> to move it. With Docker, put the flag after the image name.

The Whole Server Is One Handler

The capture side is small enough to read in one sitting. Trimmed slightly:

const maxBodySize = 10 * 1024 * 1024 // 10MB

func CaptureHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Methods", "*")
    w.Header().Set("Access-Control-Allow-Headers", "*")

    if r.Method == http.MethodOptions {
        w.WriteHeader(http.StatusNoContent)
        return
    }

    body, _ := io.ReadAll(io.LimitReader(r.Body, maxBodySize))

    contentType := r.Header.Get("Content-Type")
    if i := strings.Index(contentType, ";"); i != -1 {
        contentType = strings.TrimSpace(contentType[:i])
    }

    sourceIP, _, _ := net.SplitHostPort(r.RemoteAddr)

    headers := make(map[string][]string, len(r.Header))
    maps.Copy(headers, r.Header)

    if _, err := storage.StoreWebhook(r.Method, r.URL.Path, r.URL.RawQuery,
        headers, body, contentType, sourceIP); err != nil {
        http.Error(w, "internal server error", http.StatusInternalServerError)
        return
    }

    w.WriteHeader(http.StatusOK)
}

It’s mounted on / of a plain http.ServeMux, which is what makes it catch-all. Four choices are worth calling out:

  • CORS preflights are answered, not stored. An OPTIONS request gets a 204 and permissive headers, so a browser-side caller can reach the server, but preflights don’t clutter the list.
  • Bodies are capped at 10 MB, and the cap is silent. io.LimitReader truncates instead of rejecting, and the discarded ReadAll error means a partial read is stored as-is. Your app still gets a 200. The UI won’t tell you a body was cut short, because the stored size is the truncated size. For webhook payloads that’s rarely a concern, but you should know about it.
  • Content type is normalized. application/json; charset=utf-8 becomes application/json, which keeps the UI’s JSON detection and search simple.
  • The response is always an empty 200. That’s what most webhook senders want. If you need to test how your sender handles a 500 or a slow receiver, this server can’t do that.

StoreWebhook writes the row, keeps a 250-character snippet for the list view, and broadcasts a webhook event over the WebSocket. Mailpit’s storage and live-update layers did the heavy lifting here, the same way they did for SMS.

Search and the API

A few hours after the first commit I added server-side search and pagination for both SMS and webhooks. Once a test suite fires hundreds of webhooks, scrolling stops working as a strategy.

Search is a LIKE match across the method, path, query string, content type, source IP, and body snippet, with the newest results first. Both the list and search endpoints take start and limit (the default limit is 50):

curl "http://localhost:8025/api/v1/webhooks/search?query=order.created&start=0&limit=20"

The rest of the API follows the shape of Mailpit’s email API:

MethodPathDescription
GET/api/v1/webhooksList captured requests (paginated)
GET/api/v1/webhooks/searchSearch captured requests
GET/api/v1/webhook/{id}Get one request (and mark it read, as Mailpit does for email)
DELETE/api/v1/webhook/{id}Delete one request
DELETE/api/v1/webhooksDelete everything

That last endpoint is what makes this useful in tests. Clear the bin, trigger the behavior, then assert against the list:

curl -s -X DELETE http://localhost:8025/api/v1/webhooks

./trigger-order-flow.sh   # whatever makes your app send the webhook

curl -s http://localhost:8025/api/v1/webhooks \
  | jq -e '.total == 1 and .messages[0].Path == "/hooks/orders"'

That’s an integration test of your webhook sender against a real HTTP receiver, with no mocked client. It holds up as long as those tests run serially. If they run in parallel against one MessagePit, give each test its own path and filter on it rather than wiping the whole bin.

There’s one limit to know about. Search only sees the first 250 characters of the body, because that’s what the snippet column holds, so a field buried deep in a large payload won’t match. Headers aren’t searched either.

Replay, With Caveats

The detail view has a Replay panel. Paste a URL, click the button, and the captured request is sent again with the same method and body. That’s handy when you’re building the receiving side too: capture a real payload once, then fire it at your handler as often as you like.

The replay is a fetch() from your browser, not a request from the server, and that has two consequences:

  • Only the method, Content-Type, and body are sent. The original headers are not, including any signature header.
  • The target has to accept a cross-origin request from the MessagePit UI. If it doesn’t send CORS headers, the browser blocks the response.

That’s fine for a quick “does my handler parse this?” loop. To test signature verification, copy the headers from the detail view and use curl.

The full reference is on the webhook capture docs page.

A Security Note

The capture port has no authentication. MessagePit’s optional basic auth protects the UI and API on 8025, but the server on 8026 accepts anything from anyone who can reach it.

That’s why the docker run above binds to 127.0.0.1. A bare -p 8026:8026 publishes the port on every interface, so even on a laptop the capture server is reachable from whatever network you’re on: office Wi-Fi, a hotel, a shared dev cluster. The server itself listens on all interfaces by default too, so the same applies when you run the binary directly.

Then there’s Access-Control-Allow-Origin: *. Combined with no auth, it means any web page open in your browser can POST to localhost:8026 and put whatever it likes in your bin. The UI renders captured bodies and headers as escaped text, not HTML, so a planted payload shows up as text in the list rather than running as script. Still, treat the contents of the Webhooks tab as untrusted input, the same as anything else that arrives over HTTP.

Finally, whatever your app sends, whether tokens in headers or customer data in payloads, now sits in a SQLite file. That’s fine for test data, and it’s one more reason to keep real data out of your dev environment.

The Bug That Wasn’t in the Code

The feature passed every test on my machine. In CI, every webhook test failed with no such table.

The new schema migration, internal/storage/schemas/3.0.0.sql, existed on disk but had never been committed. My global gitignore excludes *.sql, so git status never listed the file. Nothing on my machine noticed, because //go:embed schemas/* embedded it straight from the working tree.

The fix took two commits: force-add the file, then add a negation to the repo’s .gitignore so it can’t happen again:

!internal/storage/schemas/*.sql

A repo-level negation overrides a global exclude, so anyone who clones the repo is now protected, whatever their personal ignore rules say. The broader lesson is about //go:embed: it builds from whatever is on disk, not from what’s tracked, so “it builds locally” says nothing about whether the files are in git. CI caught it, which is CI’s job.

Built With a Pair

As with the rest of the fork, I built this with Claude Code as the pair, covering the capture server, the storage layer, the Vue views, and the tests. Each of these commits carries a Co-Authored-By: Claude Sonnet 4.6 trailer. The feature commit alone adds 23 tests across the storage layer, the capture handler, and the API.

What does your app send to the outside world that you’ve never actually looked at, and would you be comfortable with it sitting in a SQLite file?

Related posts