Integration Guides · 7 MIN

How to integrate Razorpay in Next.js with the App Router (2026)

Razorpay in Next.js App Router, step by step. Order and verify route handlers, a Checkout button, and a webhook that reads the raw body so signatures match.

By NactorePublished 19 Nov 2026All articles

To integrate Razorpay in Next.js, add three App Router route handlers (create order, verify payment, webhook), a client component that opens Razorpay Checkout, and one helper file for the HMAC checks. Read the webhook body with req.text(), never req.json(), or the signature will not match. This guide gives every file, tested on Next.js 16.

Key takeaways
  • Keep the Key Secret and webhook secret in server-only environment variables, never with a NEXT_PUBLIC_ prefix.
  • The order route returns the Key ID to the browser, so the frontend needs no hardcoded key.
  • Route handlers that use node:crypto should declare export const runtime = "nodejs".
  • Most "signature verification failed" errors come from parsing the webhook body before hashing it.
  • We built this with next build, ran it with next start, and checked every route against a local mock of Razorpay before publishing.
  • Nactore is a technology and growth company that builds, ships, ranks and grows products, and we run Razorpay checkouts in production.

How does Razorpay work with Next.js?

Razorpay works with Next.js as a server-first flow. A route handler creates the order with your secret, the browser opens Checkout for that order, and a second route handler verifies the signed result. A webhook route then confirms payment server to server. Secrets never reach the client bundle.

FileRuns onJob
lib/razorpay.jsServerCreate orders, check signatures
app/api/razorpay/order/route.jsServerPrice and create the order
app/api/razorpay/verify/route.jsServerVerify the Checkout result
app/api/razorpay/webhook/route.jsServerHandle order.paid
app/pay/PayButton.jsxBrowserOpen Checkout

Put test keys in .env.local and keep that file out of git.

RAZORPAY_KEY_ID=rzp_test_xxxxxxxx
RAZORPAY_KEY_SECRET=your_test_key_secret
RAZORPAY_WEBHOOK_SECRET=your_webhook_secret

Step 1: Write the server helpers

Order creation is one POST to the Orders API with Basic auth. The amount is in paise.

// lib/razorpay.js
import crypto from "node:crypto";

const API = process.env.RAZORPAY_API_BASE ?? "https://api.razorpay.com";

export async function createOrder(amountPaise, receipt) {
  const auth = Buffer.from(
    `${process.env.RAZORPAY_KEY_ID}:${process.env.RAZORPAY_KEY_SECRET}`
  ).toString("base64");
  const res = await fetch(`${API}/v1/orders`, {
    method: "POST",
    headers: { Authorization: `Basic ${auth}`, "Content-Type": "application/json" },
    body: JSON.stringify({ amount: amountPaise, currency: "INR", receipt }),
    cache: "no-store",
  });
  if (!res.ok) throw new Error(`Razorpay ${res.status}: ${await res.text()}`);
  return res.json();
}

const hmacHex = (secret, message) =>
  crypto.createHmac("sha256", secret).update(message).digest("hex");

function safeEqual(expected, received) {
  const a = Buffer.from(expected);
  const b = Buffer.from(String(received ?? ""));
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

export const paymentSignatureOk = (orderId, paymentId, signature) =>
  safeEqual(hmacHex(process.env.RAZORPAY_KEY_SECRET, `${orderId}|${paymentId}`), signature);

export const webhookSignatureOk = (rawBody, signature) =>
  safeEqual(hmacHex(process.env.RAZORPAY_WEBHOOK_SECRET, rawBody), signature);

crypto.timingSafeEqual throws if the two buffers differ in length, which is why safeEqual checks length first. Your orders need storage. This stand-in keeps the example runnable, and each function maps to one database call.

// lib/store.js
// In-memory stand-in so the example runs. Replace each function with your database.
// recordEvent must be an insert on a UNIQUE column that returns false on conflict.
const orders = new Map();
const events = new Set();

export const saveOrder = async (o) => orders.set(o.razorpayOrderId, o);
export const findOrder = async (id) => orders.get(id);
export const markPaid = async (id, paymentId) => {
  const o = orders.get(id);
  if (o) Object.assign(o, { status: "paid", paymentId });
};
export const recordEvent = async (eventId) => {
  if (events.has(eventId)) return false;
  events.add(eventId);
  return true;
};

Step 2: Add the order and verify routes

// app/api/razorpay/order/route.js
import { createOrder } from "@/lib/razorpay";
import { saveOrder } from "@/lib/store";

export const runtime = "nodejs";
const PRICE_PAISE = 49900; // Rs 499, decided on the server

export async function POST() {
  const receipt = `rcpt-${Date.now()}`;
  const rz = await createOrder(PRICE_PAISE, receipt);
  await saveOrder({ razorpayOrderId: rz.id, amount: rz.amount, status: "created" });
  return Response.json({
    key: process.env.RAZORPAY_KEY_ID,
    order_id: rz.id,
    amount: rz.amount,
    currency: rz.currency,
  });
}

The verify route looks the order up in your store and signs with that ID, as Razorpay's integration guide advises.

// app/api/razorpay/verify/route.js
import { paymentSignatureOk } from "@/lib/razorpay";
import { findOrder, markPaid } from "@/lib/store";

export const runtime = "nodejs";

export async function POST(req) {
  const { razorpay_order_id, razorpay_payment_id, razorpay_signature } = await req.json();
  const order = await findOrder(razorpay_order_id);
  if (!order) return Response.json({ ok: false }, { status: 404 });
  const ok = paymentSignatureOk(order.razorpayOrderId, razorpay_payment_id, razorpay_signature);
  if (ok) await markPaid(order.razorpayOrderId, razorpay_payment_id);
  return Response.json({ ok }, { status: ok ? 200 : 400 });
}

Step 3: Build the pay button

// app/pay/PayButton.jsx
"use client";
import Script from "next/script";

export default function PayButton() {
  async function pay() {
    const o = await fetch("/api/razorpay/order", { method: "POST" }).then((r) => r.json());
    new window.Razorpay({
      key: o.key,
      order_id: o.order_id,
      amount: o.amount,
      currency: o.currency,
      name: "Your company",
      handler: async (resp) => {
        const v = await fetch("/api/razorpay/verify", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(resp),
        }).then((r) => r.json());
        window.location.href = v.ok ? "/thanks" : "/payment-failed";
      },
    }).open();
  }

  return (
    <>
      <Script src="https://checkout.razorpay.com/v1/checkout.js" strategy="lazyOnload" />
      <button onClick={pay}>Pay Rs 499</button>
    </>
  );
}

Step 4: Add the webhook route

// app/api/razorpay/webhook/route.js
import { webhookSignatureOk } from "@/lib/razorpay";
import { markPaid, recordEvent } from "@/lib/store";

export const runtime = "nodejs";

export async function POST(req) {
  const raw = await req.text(); // raw string, never req.json() before verifying
  if (!webhookSignatureOk(raw, req.headers.get("x-razorpay-signature"))) {
    return new Response("invalid signature", { status: 400 });
  }
  const isNew = await recordEvent(req.headers.get("x-razorpay-event-id") ?? "");
  if (!isNew) return new Response(null, { status: 200 }); // duplicate delivery

  const event = JSON.parse(raw);
  if (event.event === "order.paid") {
    const { order, payment } = event.payload;
    await markPaid(order.entity.id, payment.entity.id);
  }
  return new Response(null, { status: 200 });
}

In the Razorpay Dashboard, point the webhook at https://yourdomain.com/api/razorpay/webhook, set the secret and subscribe to order.paid.

Why does Razorpay signature verification fail?

Razorpay signature verification fails when the bytes you hash differ from the bytes Razorpay signed, or when you hash with the wrong secret. In Next.js the common cause is calling req.json() and then JSON.stringify on the result, which changes spacing and key order. Hash the string from req.text().

SymptomCauseFix
Every webhook failsBody parsed then re-stringifiedHash await req.text()
Every webhook failsKey Secret used instead of webhook secretUse RAZORPAY_WEBHOOK_SECRET
Old retries fail after rotationRetries are signed with the old secretAccept both secrets for a while
Verify route always 400Order ID taken from a different orderUse the ID from your store
timingSafeEqual throwsBuffers of different lengthCompare lengths first

The Node example on Razorpay's webhook validation page passes JSON.stringify(webhookBody), while the same page says not to parse or cast the body. Follow the warning, not the example. When we tested this route, a re-stringified copy of a valid payload was rejected and the raw string passed.

Pro tip

Test with Razorpay's UPI ID success@razorpay in test mode, then send the same webhook twice. The second delivery should change nothing in your database.

Frequently asked questions

Can I use the Edge runtime for Razorpay routes?

This code uses node:crypto, so it declares the Node.js runtime. The Edge runtime would need the Web Crypto API instead. Node is the simpler choice for payment routes.

Should the Razorpay Key ID be a NEXT_PUBLIC variable?

It can be, since the Key ID is public. Returning it from the order route keeps all payment config on the server and in one place.

How do I test Razorpay webhooks on localhost?

Razorpay cannot reach localhost. Run a tunnel to your dev server and use that public URL as the test webhook.

Do I still need the webhook if the verify route works?

Yes. The verify route depends on the browser finishing. The webhook confirms payments when the tab closes mid-flow.

When to get help

For the same flow in Python, read how to integrate Razorpay in Django. If your checkout drops payments or your records drift from Razorpay's, tell us what you see or look at what we build. Nactore is one partner that builds, ships, ranks and grows, measured on your growth.

Want to apply this to your business?

Book a free 30-minute call. We will tell you what we would do first.