Payments & Auth - 4 min read
Preventing NEXT_PUBLIC Secret Leaks & Unsigned Payment Webhooks in Next.js
Stop query-string entitlement spoofing and verify raw-body HMAC webhook signatures safely in Next.js App Router.
Never grant paid access from /success?status=succeeded
Redirect query strings exist only to show friendly confirmation copy to the buyer. Any visitor can type ?status=succeeded into their browser bar.
Unlock digital files, credits, or SaaS seats exclusively inside a cryptographically verified webhook handler or through your Merchant of Record's built-in entitlement emails.
Verify HMAC signatures against raw unparsed bytes
Re-serializing parsed JSON with JSON.stringify alters key whitespace and breaks signature verification. Read raw bytes via await request.text() and compare digests with crypto.timingSafeEqual.
import crypto from "node:crypto";
export async function POST(request: Request) {
const rawBody = await request.text();
const signature = request.headers.get("x-webhook-signature") ?? "";
const expected = crypto
.createHmac("sha256", process.env.WEBHOOK_SECRET!)
.update(rawBody, "utf8")
.digest("hex");
const valid =
signature.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
if (!valid) return new Response("Invalid signature", { status: 401 });
return new Response("OK", { status: 200 });
}