Before You Trust a Midtrans Webhook in Next.js: Verify the Signature, Ignore Duplicates, Reply Fast
A Midtrans notification is just an HTTP POST. Anyone can send one that looks the same. This is the short checklist I use in a Next.js App Router handler: verify the signature, make the handler idempotent by order ID, and return 200 quickly.
A payment webhook looks trustworthy because it arrives at your endpoint with the right fields:
order_id , transaction_status , gross_amount , and a signature_key .That is not enough. A webhook is an HTTP POST. If your handler updates an order as soon as it sees
transaction_status: "settlement" , a forged or repeated notification can mark an unpaid order as paid, or process the same payment twice.I ran into this pattern while working with Next.js and Midtrans. The fix is not complicated, but it has to happen in the right order: verify first, then decide if this notification is new, then do the work — and reply fast.
1. Verify the signature before you trust anything
Midtrans includes a
signature_key in every notification. According to the official docs, it is:SHA512(order_id + status_code + gross_amount + serverkey)That means only someone who knows your Server Key can build a matching signature. Your job is to rebuild it with the values from the notification and compare. If it does not match, disregard the notification. Do not update the order.
Two details matter here:
- Use
gross_amountexactly as sent, for example"10000.00". Do not convert it withNumber()first — that can change the string and break the hash.
- Compare in a timing-safe way, not with a plain
===on a secret-derived value if you can avoid it.
Here is a short Next.js App Router example. It is a starting pattern, not a complete order system. Replace the in-memory set with a real database check before production.
// app/api/midtrans/webhook/route.tsimport { createHash, timingSafeEqual } from "node:crypto";
// Placeholder only. In a real app, use a database unique key on order_id.// An in-memory Set resets on every deploy and does not work across instances.const processed = new Set<string>();
function isValidSignature(body: any, serverKey: string) { const expected = createHash("sha512") .update(`${body.order_id}${body.status_code}${body.gross_amount}${serverKey}`) .digest("hex");
const received = Buffer.from(body.signature_key ?? "", "utf8"); const expectedBuf = Buffer.from(expected, "utf8"); if (received.length !== expectedBuf.length) return false; return timingSafeEqual(received, expectedBuf);}
export async function POST(req: Request) { const rawBody = await req.text(); // Log the raw body while debugging. In production, log order_id/status only, // and never log your Server Key. console.log("midtrans webhook raw:", rawBody);
let body: any; try { body = JSON.parse(rawBody); } catch { return Response.json({ received: true }, { status: 200 }); }
const serverKey = process.env.MIDTRANS_SERVER_KEY; if (!serverKey) { console.error("MIDTRANS_SERVER_KEY is not set"); return Response.json({ error: "server misconfigured" }, { status: 500 }); }
if (!isValidSignature(body, serverKey)) { console.warn("invalid signature for order:", body.order_id); // Return 200 and do nothing. A 500 would only make Midtrans retry // a notification you will never accept. return Response.json({ received: true }, { status: 200 }); }
// 2. Idempotency: same order, same event -> do not process twice. const key = `${body.order_id}:${body.transaction_status}`; if (processed.has(key)) { return Response.json({ received: true }, { status: 200 }); } processed.add(key);
// 3. Only treat it as paid when all three checks pass. const isPaid = body.status_code === "200" && body.fraud_status === "accept" && (body.transaction_status === "settlement" || body.transaction_status === "capture");
if (isPaid) { // TODO: update the order in your database here. // Keep this handler fast. Queue emails, fulfillment, // and other slow work instead of doing it inline. console.log("paid:", body.order_id, body.gross_amount); }
return Response.json({ received: true }, { status: 200 });}Set the key as an environment variable, for example:
MIDTRANS_SERVER_KEY=YOUR_SERVER_KEYNever put the real Server Key in client-side code, a public repo, or a screenshot.
2. Expect duplicates — and out-of-order notifications
Midtrans docs say to implement notifications in an idempotent way: in rare cases, the same transaction event can be sent twice. Using
order_id as the key is the simple way to track entries.The same docs also warn that notifications can arrive out of order — a
settlement notification can arrive before the pending one. So do not assume the latest notification you receive is the latest state, and do not let a later pending overwrite a settlement .If a notification looks odd or you are unsure about the current state, confirm it with the Midtrans GET Status API instead of guessing from the webhook alone. That response comes directly from Midtrans.
3. Reply 200 fast, and keep the raw body
Midtrans recommends keeping the response time under 5 seconds, with a 30-second HTTP timeout. The retry behaviour also depends on your status code:
2xx means no retry, while 500 , 503 , and 400 / 404 trigger different retry counts.That is why the handler above does as little as possible before replying. Verify, check for duplicates, record the paid state, and return
200 . Move slow work to a queue or a background job.Logging the raw body helps for the same reason. When a signature fails, you want to see exactly what arrived — the exact
gross_amount string, the exact status_code , and the exact signature_key — not a version your code already cleaned up. Keep raw-body logging for debugging, and trim it down once the handler is stable.Checklist before production
- [] HTTPS endpoint, no redirect, no self-signed certificate.
- [] Server Key only in a server-side environment variable. Never in the browser.
- [] Signature checked before any order update.
- [] Success requires all three:
status_codeis"200",fraud_statusis"accept", andtransaction_statusis"settlement"or"capture".
- [] Idempotency by
order_idin the database, not only in memory.
- [] Handler returns
200quickly; slow work is queued.
- [] Unknown JSON fields are ignored, so new Midtrans fields do not break parsing.
- [] Tested with dummy values locally, then in Midtrans Sandbox before going live.
This pattern does not make payments simple. It makes the webhook part boring in a good way: fake notifications get ignored, duplicates do not double-process, and a slow email job cannot cause a retry storm.
What do you use for idempotency in your webhook handler — a unique database constraint, a processed-events table, or something else? What broke for you the first time a duplicate arrived?
References
- Midtrans, Handle Notifications: https://docs.midtrans.com/reference/handle-notifications
- AWS Builder Center, Your Guide to Builder Center: https://builder.aws.com/content/2zcHXEQEQkxFslPN4dT0Qm2CSJA/your-guide-to-builder-center
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article