Fixing Razorpay Webhook Signature Verification Failed in Next.js (App Router) & Node.js
Solve Razorpay x-razorpay-signature HMAC-SHA256 verification mismatches in Next.js 14/15 App Router and Express. Preserve exact UTF-8 raw body bytes and prevent timing attacks.
Razorpay signs every webhook request by computing an HMAC-SHA256 digest over the exact raw HTTP request body bytes using your Webhook Secret, sending the hex digest in the x-razorpay-signature header. Verification fails in Next.js App Router and Express whenever you parse the JSON first (via await req.json() or express.json()) and re-serialize it with JSON.stringify(body), because V8 key ordering, whitespace formatting, or Unicode escaping alters the byte stream. Always read the raw string via await req.text() in Next.js App Router (or express.raw({ type: 'application/json' }) in Express) before computing the HMAC-SHA256 digest.
Verified Root Causes in Production Environments
- Re-stringifying Parsed JSON Objects: Calling JSON.stringify(await req.json()) alters floating-point formatting, escaped slashes, or whitespace compared to Razorpay's raw Go/PHP payload serializer.
- Confusing API Key Secret with Webhook Secret: Using RAZORPAY_KEY_SECRET (from Settings -> API Keys) instead of RAZORPAY_WEBHOOK_SECRET (configured independently per webhook URL in Settings -> Webhooks).
- Edge Runtime Crypto Incompatibility: Running the route handler on the Edge runtime without Node.js crypto.timingSafeEqual support.
1. Why JSON.stringify(await req.json()) Breaks HMAC-SHA256 Digests
Cryptographic hash functions like SHA-256 exhibit the avalanche effect: changing a single byte—such as stripping a trailing newline, unescaping a forward slash in a URL (\/ vs /), or changing 100.00 to 100—produces a completely different 64-character hexadecimal signature.
In older Next.js Pages Router tutorials, developers had to export config = { api: { bodyParser: false } } and manually concatenate stream chunks using the micro or raw-body package. In the Next.js 14 and 15 App Router (app/api/webhooks/razorpay/route.ts), the standard Web Fetch Request object exposes await req.text(), which returns the exact unmutated UTF-8 payload string in a single line.
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
// Force Node.js runtime for native crypto module performance
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function POST(req: NextRequest) {
try {
// 1. Read the EXACT raw UTF-8 string before any JSON parsing
const rawBody = await req.text();
const signatureHeader = req.headers.get('x-razorpay-signature');
const webhookSecret = process.env.RAZORPAY_WEBHOOK_SECRET;
if (!signatureHeader || !webhookSecret) {
return NextResponse.json(
{ error: 'Missing x-razorpay-signature header or webhook secret' },
{ status: 400 }
);
}
// 2. Compute HMAC-SHA256 over the raw body bytes
const expectedSignature = crypto
.createHmac('sha256', webhookSecret)
.update(rawBody, 'utf8')
.digest('hex');
// 3. Constant-time comparison to prevent timing attacks
const sigBuffer = Buffer.from(signatureHeader, 'utf8');
const expectedBuffer = Buffer.from(expectedSignature, 'utf8');
if (
sigBuffer.length !== expectedBuffer.length ||
!crypto.timingSafeEqual(sigBuffer, expectedBuffer)
) {
console.error('[Razorpay Webhook] Invalid HMAC signature mismatch');
return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
}
// 4. Safely parse JSON ONLY after cryptographic verification succeeds
const event = JSON.parse(rawBody);
const eventId = req.headers.get('x-razorpay-event-id');
if (event.event === 'payment.captured' || event.event === 'order.paid') {
const paymentEntity = event.payload.payment.entity;
console.log(`Verified Razorpay payment ${paymentEntity.id} (Event: ${eventId})`);
// Fulfill container deployment or credit wallet idempotently using eventId
}
// Always respond with 200 OK within 5 seconds so Razorpay does not disable the webhook
return NextResponse.json({ received: true, eventId }, { status: 200 });
} catch (err) {
console.error('[Razorpay Webhook Error]:', err);
return NextResponse.json({ error: 'Webhook handler failed' }, { status: 500 });
}
}2. Fixing Razorpay Signature Verification in Express.js Microservices
If your backend runs as a standalone Express.js container on Vexlo Cloud or Docker Compose, mounting app.use(express.json()) globally at the top of server.ts consumes the incoming request stream and replaces req.body with a parsed JavaScript object before your webhook route executes.
Either mount your Razorpay webhook route with express.raw({ type: 'application/json' }) BEFORE app.use(express.json()), or use the verify callback option inside express.json() to attach the raw Buffer to req.rawBody.
import express, { Request, Response } from 'express';
import crypto from 'crypto';
const app = express();
// Capture raw body buffer alongside JSON parsing
app.use(
express.json({
verify: (req: Request & { rawBody?: Buffer }, _res, buf) => {
req.rawBody = buf;
},
})
);
app.post('/webhooks/razorpay', (req: Request & { rawBody?: Buffer }, res: Response) => {
const signature = req.headers['x-razorpay-signature'] as string;
const secret = process.env.RAZORPAY_WEBHOOK_SECRET!;
if (!req.rawBody || !signature) {
return res.status(400).json({ error: 'Missing rawBody or signature' });
}
const expected = crypto
.createHmac('sha256', secret)
.update(req.rawBody)
.digest('hex');
if (expected !== signature) {
return res.status(401).json({ error: 'Signature mismatch' });
}
res.status(200).json({ status: 'ok' });
});3. Local Testing & Replay Verification With Signed cURL Commands
You do not need to deploy to staging every time you test webhook signature logic. You can generate a valid x-razorpay-signature header locally in Bash using openssl dgst -sha256 -hmac and fire a test payload directly against localhost:3000.
#!/usr/bin/env bash
SECRET="my_test_webhook_secret_123"
PAYLOAD='{"entity":"event","account_id":"acc_123","event":"payment.captured","payload":{"payment":{"entity":{"id":"pay_Test999","amount":14900,"currency":"INR"}}}}'
# Generate exact HMAC-SHA256 hex digest
SIGNATURE=$(printf "%s" "$PAYLOAD" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $2}')
curl -i -X POST http://localhost:3000/api/webhooks/razorpay \
-H "Content-Type: application/json" \
-H "x-razorpay-signature: $SIGNATURE" \
-H "x-razorpay-event-id: evt_test_001" \
--data-raw "$PAYLOAD"Pre-Deployment Verification Checklist
- Use await req.text() in Next.js App Router instead of JSON.stringify(await req.json()).
- Verify RAZORPAY_WEBHOOK_SECRET matches the secret set inside Razorpay Dashboard -> Settings -> Webhooks (NOT your API Key Secret).
- Deduplicate incoming webhooks using the x-razorpay-event-id header in PostgreSQL or Redis.
- Return HTTP 200 within 5 seconds before running slow container provisioning or email jobs.
Deploy on Vexlo Cloud in 60s (₹149/mo UPI)
Automated Docker & Nixpacks builds, managed PostgreSQL/Redis, and AI Deployment Doctor. Instant INR UPI for India or USD/EUR/GBP across 17 global currencies.
Frequently Asked Questions
Is the Razorpay Webhook Secret the same as my Razorpay API Key Secret?
No. Razorpay uses two different secrets: your API Key Secret is used to verify checkout callbacks (razorpay_order_id + '|' + razorpay_payment_id), whereas the Webhook Secret is defined separately when you create a webhook endpoint in the Razorpay Dashboard.
Why does Razorpay disable my webhook endpoint automatically in production?
If your webhook route returns a non-2xx HTTP status code or takes longer than 5-10 seconds to respond across consecutive retries over 24 hours, Razorpay automatically disables the webhook. Always verify the signature, push the job to Redis/BullMQ, and return 200 OK immediately.
How do I prevent duplicate order fulfillment when Razorpay retries a webhook?
Read the x-razorpay-event-id HTTP header sent by Razorpay and store it as a unique key in your database before processing the event.