Asia/Kolkata
Posts

AES-256-GCM Secret Storage and Webhook Queues in Next.js

November 26, 2026

Two Backend Rules From Building PostLine

When I built PostLine, a mail API on Next.js, Postgres, and Prisma, two backend tasks had zero room for shortcuts. First, I had to store user SMTP passwords safely. You cannot hash an SMTP pass with bcrypt because the mail client needs the plain text to log in to their mail host. Second, billing webhooks from Razorpay could not time out when the database got busy.

1. Lock Secrets at Rest With AES-256-GCM

Unlike older CBC modes, AES-256-GCM locks both read access and data trust. It tags every block with a short check tag. If someone changes even one byte in Postgres, the code sees the edit and stops at once. Create a fresh 12-byte random IV for each write. Store iv:authTag:ciphertext in one field:

2. Hash API Keys With SHA-256

User passwords need slow hashes like bcrypt. Long random API keys do not. A fast SHA-256 hash lets your edge route check Authorization: Bearer pl_live_... in one fast lookup, while keeping raw keys out of Postgres: Show the raw key once when the user makes it. Save only a short prefix for the UI and the SHA-256 hash in your database.

3. Put Webhooks in a Queue First

Gateways like Razorpay and Stripe want a 200 OK reply in a few seconds. Running plan updates, quota resets, and welcome emails inline inside that route invites slow timeouts and repeat events. Instead, check the HMAC tag with crypto.timingSafeEqual, save the raw event into a WebhookQueue table with a unique event ID, and send 200 OK right back: Separating the check step from the work step keeps billing safe. If an email call or query blips later, a worker can retry that job cleanly without losing a single charge update.