DEV Community

NextGen Fusion
NextGen Fusion

Posted on Originally published at nextgenfusiontech.com on

Fix Razorpay Webhook Signature Verification in Next.js

If Razorpay webhook signature verification fails in Node.js or Next.js, the cause is almost always one of two things: your code signs a parsed and re-serialised body instead of the exact raw body Razorpay sent, or it uses the wrong secret (often the API key secret instead of the webhook secret). Read the body as raw text before any JSON parsing, compute the HMAC with the secret saved on that webhook in the Razorpay Dashboard, and compare it with the X-Razorpay-Signature header.

Work through the steps in order and test after each change.

How the signature works

When a webhook has a secret, Razorpay uses it to create a hash signature for each payload and sends it in the X-Razorpay-Signature header. Razorpay's documentation says the signature is calculated using HMAC with SHA256, with your webhook secret as the key and the webhook request body as the message (Validate and test webhooks). The same page has a clear warning: pass the raw webhook request body and "do not parse or cast the webhook request body".

The official Node SDK does exactly this in validateWebhookSignature: it converts the body to a string, runs crypto.createHmac('sha256', secret).update(body).digest('hex') and checks that the result equals the signature (razorpay-node source). If a single byte of the body differs from what Razorpay signed, the result is different and verification fails.

Step 1: make sure you are hashing the raw body

This is the cause in most Node and Next.js projects. A framework parses the JSON body for you, and the code then does JSON.stringify(req.body) to get a string to hash. Re-serialising an object is not guaranteed to give back the same bytes: spacing, escaping of characters and number formatting can all change. Razorpay asks for the raw body for this reason.

Fix it in the place your framework reads the body.

Next.js App Router (Route Handlers). The Next.js docs show a webhook Route Handler that reads the payload with await request.text() (Next.js Route Handlers: webhooks). Read the text once, verify it, then parse it yourself:

// app/api/razorpay/webhook/route.ts
import crypto from 'node:crypto';

export async function POST(request: Request) {
  const body = await request.text(); // raw body, not request.json()
  const signature = request.headers.get('x-razorpay-signature') ?? '';
  const secret = process.env.RAZORPAY_WEBHOOK_SECRET ?? '';

  const expected = crypto.createHmac('sha256', secret).update(body).digest('hex');
  const a = Buffer.from(expected);
  const b = Buffer.from(signature);
  if (!secret || a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
    return new Response('Invalid signature', { status: 400 });
  }

  const event = JSON.parse(body);
  // check x-razorpay-event-id for duplicates, store or queue the work, reply quickly
  return new Response('OK', { status: 200 });
}

Enter fullscreen mode Exit fullscreen mode

Do not call request.json() before request.text(): the body can only be read once.

Next.js Pages Router (API Routes). The body parser is on by default, so req.body is already an object. The Next.js docs say you can set bodyParser to false to consume the body as a stream, and give verifying the raw body of a webhook as a use case (Next.js API Routes: custom config):

// pages/api/razorpay/webhook.js
export const config = { api: { bodyParser: false } };

async function readRawBody(req) {
  const chunks = [];
  for await (const chunk of req) chunks.push(chunk);
  return Buffer.concat(chunks).toString('utf8');
}

Enter fullscreen mode Exit fullscreen mode

Then verify await readRawBody(req) exactly as in the App Router example.

Express. Express exposes express.raw, which comes from the body-parser package (Express source). The body-parser README says the raw parser gives you the body as a Buffer and only looks at requests whose Content-Type matches its type option, and that option defaults to application/octet-stream (body-parser README). So set the type to JSON, and register the webhook route before any global express.json() so that nothing parses the body first:

app.post('/razorpay/webhook', express.raw({ type: 'application/json' }), handler);
app.use(express.json()); // the rest of your API

Enter fullscreen mode Exit fullscreen mode

Inside handler, req.body is a Buffer; hash it directly, and parse it with JSON.parse(req.body.toString('utf8')) only after the check passes.

Step 2: use the webhook secret, not the API key secret

Razorpay has two kinds of secret, and they are easy to mix up. The secret you type when you create a webhook is used to validate that the webhook is from Razorpay, and Razorpay notes that "the webhook secret does not need to be the Razorpay API key secret" (Set up and edit webhooks). If your code reads RAZORPAY_KEY_SECRET for webhook checks while the webhook was saved with a different secret, every request fails.

To check or change it: log in to the Dashboard, go to Accounts & Settings , click Webhooks under Website and app settings , select the webhook and click Edit. The Webhook Setup pop-up lets you change the Webhook URL, Secret, Alert Email and Active Events; click Save Webhook afterwards. Put the same value in your environment variable.

Step 3: check the environment variable really loads

A correct secret in the Dashboard does not help if your server reads an empty or old value. Check these:

  • the variable exists on the server or hosting platform you deploy to, not only in your local .env file;
  • you redeployed or restarted after changing it, so the running process has the new value;
  • the value has no extra spaces, quotes or a trailing newline copied with it;
  • the webhook in the Dashboard belongs to the same mode (test or live) as the events you are testing.

Log secret.length once during debugging, never the secret itself, and remove the log afterwards.

Step 4: read the right header

Node.js lower-cases header names in req.headers (Node.js http docs), so read req.headers['x-razorpay-signature'], not req.headers['X-Razorpay-Signature'], which is always undefined. In a Route Handler, request.headers.get() is case-insensitive. If the header is missing completely, check that the webhook has a secret set: Razorpay only signs the payload when a secret is set.

Step 5: look for anything that changes the request on the way

If your code is right and it still fails only in production, something between Razorpay and your code may change the body. Look at proxies, API gateways or middleware that decode and re-encode JSON, add or strip characters, or redirect the request. A redirect (for example from http:// to https://, or between www and non-www) can drop or change a POST body, so put the final address in the webhook URL. Razorpay also requires public URLs: you cannot save a localhost address as a webhook (Set up and edit webhooks).

Step 6: remember the old secret for retries

Razorpay says that if you have changed your webhook secret, you must use the old secret to validate retries of older requests, because the new secret causes a signature mismatch (Validate and test webhooks). So after a secret change, a few failures from retried events are expected. If you need those events, keep the old secret available for a short time and try both.

Step 7: test it, and re-enable a disabled webhook

Set up the webhook in test mode with a staging address and send test events to it; Razorpay's docs describe this flow, including tunnelling tools for an application running on localhost (Validate and test webhooks). Watch your server log for the result of the check.

Then check the webhook's state. Razorpay expects a 2XX response within 5 seconds. Any other status code or a timeout counts as a failure, failed webhooks are retried with exponential back-off for 24 hours, and if failures continue for 24 hours the webhook is disabled. You then have to enable it again from the Dashboard after fixing the error (Set up and edit webhooks). Check its status after the fix.

Step 8: make the handler safe after it passes

  • Compare signatures with crypto.timingSafeEqual, which the Node.js docs describe as suitable for comparing HMAC digests. It throws if the two buffers have different lengths, so check the lengths first, as in the example above (Node.js crypto docs).
  • Razorpay says the same event can arrive more than once and recommends identifying duplicates with the x-razorpay-event-id header, which is unique per event. Store it and skip events you have already processed.
  • Razorpay also notes that webhooks may not arrive in the order the events happened, so do not assume payment.captured always comes after payment.authorized.
  • Reply quickly. Do slow work, such as sending emails or calling other APIs, after you have stored the event, so you stay inside the 5-second window.

When to call a developer

Call a developer if you have confirmed the raw body, the webhook secret, the loaded environment variable and the header name, and verification still fails; or if test-mode events pass but live ones fail. The cause is then usually in hosting or architecture: an edge layer or proxy rewriting requests, a serverless platform setting, a shared middleware stack that parses every request, or more than one webhook pointing at the same endpoint with different secrets. Our Next.js development services include payment and webhook integrations, and our API integration services cover server-to-server connections with other platforms.

If you run WooCommerce rather than a custom Node app, see Razorpay payment successful but WooCommerce order pending. For choosing a gateway in the first place, read WooCommerce payment gateways for India.

Frequently asked questions

Why does Razorpay's Node example use JSON.stringify?

The Node snippet on Razorpay's validation page passes JSON.stringify(webhookBody), but the same page says the body must be the raw request body and must not be parsed or cast. Follow the rule, not the shortcut: give the function the raw string or buffer you received.

Is the webhook secret the same as my API key secret?

Not necessarily. Razorpay states that the webhook secret does not need to be the API key secret. Use the value saved on that webhook, and keep it out of client-side code.

Can I use request.json() in a Next.js Route Handler and stringify it again?

No. The re-serialised string may not match the bytes Razorpay signed. Use request.text(), verify, then call JSON.parse on the same text.

Will Razorpay keep sending events while my check is failing?

Yes, for a while. Failed webhooks are retried with exponential back-off for 24 hours, and the webhook is disabled if the failures continue for that long. Fix the check, then confirm the webhook is still enabled.

Should I return an error when the signature does not match?

Yes. Return a non-2XX status, such as 400, and do not act on the payload. Log the event ID and the failure so you can find the cause.

Stuck on a webhook that will not verify, or a payment flow that loses events? Message us on WhatsApp at +91 73482 28167 and you get a fixed written quote within one working day.

Top comments (0)