<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Hamichi Field Notes]]></title><description><![CDATA[Field notes on Stripe webhooks, billing, and getting paid as an indie seller. Full guides and kits at https://hamichi.dev.]]></description><link>https://hamichidev.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6b02f4a619d3a7a58e5a7c7b/8de0287f-82ab-4df1-8f4e-fb3a6ea6de69.png</url><title>Hamichi Field Notes</title><link>https://hamichidev.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Wed, 25 Nov 2026 12:18:29 GMT</lastBuildDate><atom:link href="https://hamichidev.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Stripe signature verification fails in production: the raw body problem]]></title><description><![CDATA[Stripe signs the raw request body. If express.json() runs before the webhook route, the signature never matches. How to keep the bytes intact.]]></description><link>https://hamichidev.hashnode.dev/stripe-signature-verification-fails-in-production-the-raw-body-problem</link><guid isPermaLink="true">https://hamichidev.hashnode.dev/stripe-signature-verification-fails-in-production-the-raw-body-problem</guid><category><![CDATA[stripe]]></category><category><![CDATA[Express]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[webhooks]]></category><dc:creator><![CDATA[Hamichi]]></dc:creator><pubDate>Tue, 24 Nov 2026 13:22:58 GMT</pubDate><content:encoded><![CDATA[<p>The webhook verified on your laptop. After deploy, every signature check fails, and the secret in the dashboard is the right one.</p>
<p>Stripe signs the raw request body, not the object you get after <code>JSON.parse</code>. If your framework already parsed JSON, the bytes no longer match the signature. This is the usual way a webhook dies after deploy, because <code>express.json()</code> ran first.</p>
<h2>What Stripe actually signs</h2>
<p>The <code>Stripe-Signature</code> header is a <code>t=</code> timestamp and one or more <code>v1=</code> hex HMACs of <code>timestamp + "." + rawBody</code>. <a href="https://docs.stripe.com/webhooks">Stripe's webhook docs</a> describe the scheme, and the official libraries implement it.</p>
<p>You verify that, with a timing-safe compare, before you parse business data. You also reject timestamps older than the usual 300-second window. Without the window, anyone with a captured body can replay it later.</p>
<p>A tolerance of <code>0</code> disables the recency check. <a href="https://docs.stripe.com/webhooks">Stripe's docs say not to use it</a>. The official Node helper, <code>stripe.webhooks.constructEvent</code>, defaults to 300 seconds. Passing <code>0</code> to that helper turns the window off. Do not do that.</p>
<p>While you roll a signing secret, the header can carry several <code>v1</code> values. One match is enough. Ignore the unsigned debug entries (<code>secret</code>, <code>destination</code>, <code>payload</code>) if they appear. They are not part of the authentication.</p>
<p>If Stripe retries a delivery, it generates a new timestamp and signature for that attempt. The Event body is the same. The header is not.</p>
<p>If you already use stripe-node, the official helper is:</p>
<pre><code class="language-ts">import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const event = stripe.webhooks.constructEvent(
  rawBody, // string or Buffer. The exact bytes Stripe sent.
  signatureHeader,
  process.env.STRIPE_WEBHOOK_SECRET!,
);
</code></pre>
<p>Pass the raw body. Do not pass a parsed object, and do not pass <code>JSON.stringify</code> of that object. <code>constructEvent</code> accepts a <code>string</code> or a <code>Buffer</code>.</p>
<h2>Express: raw on the route, JSON after it</h2>
<p>Mount <code>express.raw({ type: "application/json" })</code> on the webhook route, and register that route before any global <code>app.use(express.json())</code>.</p>
<pre><code class="language-ts">import express from "express";

const app = express();

app.post(
  "/webhooks/stripe",
  express.raw({ type: "application/json" }),
  stripeWebhookRoute,
);

app.use(express.json()); // everything else
</code></pre>
<p>If <code>express.json()</code> is already registered first, adding <code>express.raw()</code> on the route will not help. The body has already been consumed and parsed.</p>
<p>The route should refuse a body that is not a <code>Buffer</code>. (<code>Buffer</code> is a <code>Uint8Array</code>, so an <code>instanceof Uint8Array</code> check also works.) If <code>express.json()</code> already ran, <code>req.body</code> is a plain object. Log that and return 500 so you find it, rather than verifying a reserialized object that will never match.</p>
<pre><code class="language-ts">import type { Request, Response } from "express";
import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export function stripeWebhookRoute(req: Request, res: Response): void {
  if (!Buffer.isBuffer(req.body)) {
    console.error("stripe webhook: body is not raw. Is express.json() running first?");
    res.status(500).json({ error: "raw_body_missing" });
    return;
  }

  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(
      req.body,
      req.header("stripe-signature") ?? "",
      process.env.STRIPE_WEBHOOK_SECRET!,
    );
  } catch {
    res.status(400).json({ error: "bad_signature" });
    return;
  }

  // handle the event, then acknowledge.
  res.status(200).json({ received: true, id: event.id });
}
</code></pre>
<p>If you cannot reorder middleware, stash the bytes in the JSON parser's <code>verify</code> hook and pass that <code>Buffer</code> to <code>constructEvent</code>. Reordering the route is the simpler fix.</p>
<h2>Next.js and NestJS</h2>
<p>In the Next.js App Router, read <code>await req.text()</code> or <code>req.arrayBuffer()</code> and pass those exact bytes to the verifier. Do not call <code>req.json()</code> first. In the Pages Router, turn off the default body parser for that API route (<code>bodyParser: false</code>) and read the raw stream.</p>
<p>In NestJS, create the app with <code>{ rawBody: true }</code> and read <code>req.rawBody</code>, which is a <code>Buffer</code>. <a href="https://docs.nestjs.com/faq/raw-body">Nest documents this</a>. Do not pass <code>bodyParser: false</code> when you rely on that flag. If <code>req.rawBody</code> is missing, fail loudly (500) so you notice the bootstrap is wrong, rather than 400-ing every event.</p>
<p>The other practical trap is verifying a test secret against live events, or the other way around. That also fails the signature. It is a different bug, and it looks identical in the logs until you print which secret you used (not the value, the name).</p>
<h2>A check you can run without a Stripe account</h2>
<p>The test below implements the HMAC Stripe describes, then proves that re-serializing JSON breaks it. The official SDK does this work for you in production. The bytes you pass it still have to be the bytes Stripe signed.</p>
<p>This sample refuses <code>toleranceSec: 0</code> instead of turning the window off, which is stricter than <code>constructEvent</code>. Save as <code>raw-body.test.ts</code> next to <code>{ "type": "module" }</code> in <code>package.json</code>. Node 22 or later:</p>
<pre><code class="language-bash">node --test --experimental-strip-types raw-body.test.ts
</code></pre>
<pre><code class="language-ts">import { createHmac, timingSafeEqual } from "node:crypto";
import test from "node:test";
import assert from "node:assert/strict";

const DEFAULT_TOLERANCE_SEC = 300;

type VerifyResult =
  | { ok: true; timestamp: number }
  | { ok: false; reason: "missing_header" | "malformed_header" | "no_v1_signature" | "bad_signature" | "timestamp_out_of_tolerance" };

function parseStripeSignatureHeader(header: string): { timestamp: number; v1: string[] } | null {
  let timestamp: number | null = null;
  const v1: string[] = [];
  for (const part of header.split(",")) {
    const eq = part.indexOf("=");
    if (eq &lt;= 0) continue;
    const key = part.slice(0, eq).trim();
    const value = part.slice(eq + 1).trim();
    if (key === "t") {
      if (timestamp !== null || !/^\d{1,12}$/.test(value)) return null;
      timestamp = Number(value);
    } else if (key === "v1") {
      v1.push(value.toLowerCase());
    }
  }
  return timestamp === null ? null : { timestamp, v1 };
}

function expectedHmac(secret: string, timestamp: number, payload: string | Uint8Array): Buffer {
  // Two updates, so a Buffer payload is not stringified in a template literal.
  return createHmac("sha256", secret).update(`${timestamp}.`).update(payload).digest();
}

function verifyStripeSignature(options: {
  payload: string | Uint8Array;
  header: string | null | undefined;
  secret: string;
  nowSec?: number;
  toleranceSec?: number;
}): VerifyResult {
  const toleranceSec = options.toleranceSec ?? DEFAULT_TOLERANCE_SEC;
  if (!Number.isFinite(toleranceSec) || toleranceSec &lt;= 0) {
    throw new RangeError("toleranceSec must be a positive number. 0 disables the replay check.");
  }
  if (!options.header) return { ok: false, reason: "missing_header" };

  const parsed = parseStripeSignatureHeader(options.header);
  if (!parsed) return { ok: false, reason: "malformed_header" };
  const candidates = parsed.v1.filter((sig) =&gt; /^[0-9a-f]{64}$/.test(sig));
  if (candidates.length === 0) return { ok: false, reason: "no_v1_signature" };

  const expected = expectedHmac(options.secret, parsed.timestamp, options.payload);
  let matched = false;
  for (const candidate of candidates) {
    const got = Buffer.from(candidate, "hex");
    if (got.length === expected.length &amp;&amp; timingSafeEqual(got, expected)) matched = true;
  }
  if (!matched) return { ok: false, reason: "bad_signature" };

  const nowSec = options.nowSec ?? Math.floor(Date.now() / 1000);
  // Same rule as stripe-node: reject deliveries older than the tolerance.
  if (nowSec - parsed.timestamp &gt; toleranceSec) {
    return { ok: false, reason: "timestamp_out_of_tolerance" };
  }
  return { ok: true, timestamp: parsed.timestamp };
}

function testHeader(secret: string, payload: string | Uint8Array, timestamp: number): string {
  const v1 = expectedHmac(secret, timestamp, payload).toString("hex");
  return `t=${timestamp},v1=${v1}`;
}

const secret = "whsec_test_secret";
const rawBody = '{"id":"evt_1","object":"event"}';
const t = 1_700_000_000;

test("a raw body matches its signature", () =&gt; {
  const header = testHeader(secret, rawBody, t);
  assert.deepEqual(verifyStripeSignature({ payload: rawBody, header, secret, nowSec: t }), {
    ok: true,
    timestamp: t,
  });
});

test("JSON.parse then JSON.stringify changes the bytes and the signature fails", () =&gt; {
  const header = testHeader(secret, rawBody, t);
  const reserialized = JSON.stringify(JSON.parse(rawBody), null, 2);
  assert.notEqual(reserialized, rawBody);
  assert.deepEqual(
    verifyStripeSignature({ payload: reserialized, header, secret, nowSec: t }),
    { ok: false, reason: "bad_signature" },
  );
});

test("a timestamp older than 300 seconds is rejected", () =&gt; {
  const header = testHeader(secret, rawBody, t);
  assert.deepEqual(
    verifyStripeSignature({ payload: rawBody, header, secret, nowSec: t + 301 }),
    { ok: false, reason: "timestamp_out_of_tolerance" },
  );
});

test("tolerance 0 is refused instead of disabling the window", () =&gt; {
  const header = testHeader(secret, rawBody, t);
  assert.throws(
    () =&gt; verifyStripeSignature({ payload: rawBody, header, secret, nowSec: t, toleranceSec: 0 }),
    RangeError,
  );
});

test("one of several v1 signatures is enough while a secret is rolling", () =&gt; {
  const oldHmac = expectedHmac("whsec_old", t, rawBody).toString("hex");
  const newHmac = expectedHmac(secret, t, rawBody).toString("hex");
  const header = `t=${t},v1=${oldHmac},v1=${newHmac}`;
  assert.equal(verifyStripeSignature({ payload: rawBody, header, secret, nowSec: t }).ok, true);
});

test("Buffer bodies verify the same way as strings", () =&gt; {
  const payload = Buffer.from(rawBody, "utf8");
  const header = testHeader(secret, payload, t);
  assert.equal(verifyStripeSignature({ payload, header, secret, nowSec: t }).ok, true);
});
</code></pre>
<p>The <a href="https://hamichidev.gumroad.com/l/qzzfdu">Hamichi Webhook Kit</a> (93 tests) takes the raw body and the signature header, and will not parse business data until the check passes. Once the body is trusted, you still have to process a retry once.</p>
<p>This note also lives at <a href="https://hamichi.dev/guides/stripe-webhook-signature-raw-body">hamichi.dev/guides/stripe-webhook-signature-raw-body</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Why Stripe sends your webhook twice (and how to process it once)]]></title><description><![CDATA[Stripe delivers events at least once, retries for up to 3 days in live mode, and can send two Event objects for one change. How to process each payment…]]></description><link>https://hamichidev.hashnode.dev/why-stripe-sends-your-webhook-twice-and-how-to-process-it-once</link><guid isPermaLink="true">https://hamichidev.hashnode.dev/why-stripe-sends-your-webhook-twice-and-how-to-process-it-once</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[stripe]]></category><category><![CDATA[webhooks]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Hamichi]]></dc:creator><pubDate>Sun, 22 Nov 2026 14:12:16 GMT</pubDate><content:encoded><![CDATA[<p>Stripe will send you the same event twice. Your endpoint timed out. You returned a 5xx. The process died after the work but before the <code>200</code>.</p>
<p>In live mode, <a href="https://docs.stripe.com/webhooks">Stripe retries for up to three days</a>, with exponential backoff. In a sandbox, it retries three times over a few hours. Stripe does not promise a single delivery, or a tidy order. The second POST is not a bug in Stripe. It is the contract.</p>
<h2>Count event ids first</h2>
<p>The unique key for a delivery is <code>event.id</code>. Store it atomically before you grant anything. The second delivery should return <code>200</code> and do nothing.</p>
<p>A flag you read and then write is not enough. Two requests can both think they are first. A unique constraint, or a <code>SET key NX</code> lease, is what stops a double license.</p>
<p>Return 200 for a duplicate. A 500 makes Stripe retry a delivery you already handled.</p>
<h2>One change can still be two Event objects</h2>
<p>Deduping only on <code>event.id</code> is necessary, and not sufficient. Creating a subscription can produce <code>customer.subscription.created</code>, <code>invoice.created</code>, <code>invoice.paid</code>, and <code>charge.created</code>. A Checkout payment can arrive as <code>checkout.session.completed</code> and later as <code>checkout.session.async_payment_succeeded</code>. Those are different Event objects. Key fulfillment by the Checkout Session id, or by the invoice or subscription you actually fulfill.</p>
<h2>Do not sort by <code>created</code> and call it order</h2>
<p><a href="https://docs.stripe.com/webhooks#event-ordering">Stripe does not guarantee event order</a>. Snapshot events record <code>created</code> in seconds. Two distinct events can share a timestamp. If you apply whichever update has the later <code>created</code>, a tie is a guess. Re-fetch the Checkout Session or the subscription and trust the live object. Acknowledge stale and tied events so Stripe stops retrying.</p>
<p>Return a 2xx quickly enough to avoid a timeout, but only after the claim is stored. Slow work, such as sending the email, can happen after that, as long as a retry cannot grant twice.</p>
<h2>A handler you can run</h2>
<p>Save this as <code>sent-twice.test.ts</code> next to a <code>package.json</code> that contains <code>{ "type": "module" }</code>. It needs Node 22 or later.</p>
<pre><code class="language-bash">node --test --experimental-strip-types sent-twice.test.ts
</code></pre>
<pre><code class="language-ts">import test from "node:test";
import assert from "node:assert/strict";

type Claim = "claimed" | "duplicate";
type Grant = "granted" | "already_granted";

class EventLog {
  #ids = new Set&lt;string&gt;();
  claim(eventId: string): Claim {
    if (this.#ids.has(eventId)) return "duplicate";
    this.#ids.add(eventId);
    return "claimed";
  }
}

class FulfillmentLog {
  #sessions = new Set&lt;string&gt;();
  grant(sessionId: string): Grant {
    if (this.#sessions.has(sessionId)) return "already_granted";
    this.#sessions.add(sessionId);
    return "granted";
  }
}

type CheckoutSession = { id: string; payment_status: string };
type StripeEvent = {
  id: string;
  type: string;
  created: number;
  data: { object: CheckoutSession };
};

const FULFILL_TYPES = new Set([
  "checkout.session.completed",
  "checkout.session.async_payment_succeeded",
]);

function handleCheckoutEvent(
  event: StripeEvent,
  events: EventLog,
  fulfillments: FulfillmentLog,
): { httpStatus: number; kind: string } {
  if (events.claim(event.id) === "duplicate") {
    return { httpStatus: 200, kind: "duplicate" };
  }

  if (!FULFILL_TYPES.has(event.type)) {
    return { httpStatus: 200, kind: "ignored" };
  }

  const session = event.data.object;
  if (session.payment_status !== "paid" &amp;&amp; session.payment_status !== "no_payment_required") {
    return { httpStatus: 200, kind: "awaiting_async_payment" };
  }

  const grant = fulfillments.grant(session.id);
  return {
    httpStatus: 200,
    kind: grant === "granted" ? "fulfilled" : "already_fulfilled",
  };
}

test("the same event id is processed once and still returns 200", () =&gt; {
  const events = new EventLog();
  const fulfillments = new FulfillmentLog();
  const event: StripeEvent = {
    id: "evt_1",
    type: "checkout.session.completed",
    created: 1_700_000_000,
    data: { object: { id: "cs_1", payment_status: "paid" } },
  };

  assert.deepEqual(handleCheckoutEvent(event, events, fulfillments), {
    httpStatus: 200,
    kind: "fulfilled",
  });
  assert.deepEqual(handleCheckoutEvent(event, events, fulfillments), {
    httpStatus: 200,
    kind: "duplicate",
  });
});

test("two Event objects for the same Checkout Session grant once", () =&gt; {
  const events = new EventLog();
  const fulfillments = new FulfillmentLog();
  const session = { id: "cs_1", payment_status: "paid" };

  const completed: StripeEvent = {
    id: "evt_completed",
    type: "checkout.session.completed",
    created: 1_700_000_000,
    data: { object: session },
  };
  const asyncOk: StripeEvent = {
    id: "evt_async",
    type: "checkout.session.async_payment_succeeded",
    created: 1_700_000_000,
    data: { object: session },
  };

  assert.equal(handleCheckoutEvent(completed, events, fulfillments).kind, "fulfilled");
  assert.equal(handleCheckoutEvent(asyncOk, events, fulfillments).kind, "already_fulfilled");
});

test("event.created in seconds can tie, so it is not used as order", () =&gt; {
  const a = { id: "evt_a", created: 1_700_000_000 };
  const b = { id: "evt_b", created: 1_700_000_000 };
  assert.equal(a.created, b.created);
  assert.notEqual(a.id, b.id);
});
</code></pre>
<p>The first test is a retry of the same Event. The second is two Event objects for one Session. Both end in a single grant and a 200.</p>
<p>In Postgres, the same idea is two unique keys:</p>
<pre><code class="language-sql">CREATE TABLE stripe_event_deliveries (
  event_id TEXT PRIMARY KEY,
  received_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE checkout_fulfillments (
  session_id TEXT PRIMARY KEY,
  email TEXT,
  fulfilled_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
</code></pre>
<pre><code class="language-ts">const claimed = await db.query(
  `INSERT INTO stripe_event_deliveries (event_id) VALUES ($1)
   ON CONFLICT (event_id) DO NOTHING
   RETURNING event_id`,
  [event.id],
);
if (claimed.rowCount === 0) {
  return { httpStatus: 200, kind: "duplicate" };
}

const granted = await db.query(
  `INSERT INTO checkout_fulfillments (session_id, email) VALUES ($1, $2)
   ON CONFLICT (session_id) DO NOTHING
   RETURNING session_id`,
  [session.id, email],
);
if (granted.rowCount === 1) {
  await sendLicense(email);
}
</code></pre>
<p>Insert the event id first, then fulfill. If the process dies after the event claim and before the session insert, Stripe's retry will see a duplicate event id and skip the grant. A safer pattern is to treat the event claim as a short lease (processing, then complete), and always let the session unique key be the thing that makes the license exist only once. Your database still does the remembering.</p>
<p>If you want this already wired up, the <a href="https://hamichidev.gumroad.com/l/qzzfdu">Hamichi Webhook Kit</a> verifies the signature, records <code>event.id</code>, and keys fulfillment so a second Event object for the same Checkout Session does not grant twice. It has 93 tests, and Express, Next.js, and NestJS examples. Every Hamichi kit, including the free <a href="https://hamichidev.gumroad.com/l/mvzxua">Checkout Email Kit</a>, is in the <a href="https://hamichidev.gumroad.com/l/gkdtaa">Hamichi Payments Pack</a> for $59.</p>
<p>This note also lives at <a href="https://hamichi.dev/guides/stripe-webhook-sent-twice">hamichi.dev/guides/stripe-webhook-sent-twice</a>.</p>
]]></content:encoded></item></channel></rss>