Skip to content

Anyone can send you a fake webhook: verify Shopify's HMAC

From the work/ 15 min read

Shopify signs every webhook with an HMAC of the raw body. Skip the check and anyone who finds your URL can fake an order. Tested Node code for Express and Next.js.

  • Shopify
  • Shopify apps
  • Node.js
  • Security
In this article (8)
  1. Why an unverified webhook is a risk
  2. How Shopify signs a webhook (HMAC-SHA256 of the body, base64)
  3. Verifying in Node with the raw body
  4. Constant-time comparison against timing attacks
  5. What to return when the signature does not match
  6. Common mistakes
  7. Frequently asked questions
  8. Checklist

To verify a Shopify webhook, compute an HMAC-SHA256 of the raw request body with your app's client secret, base64-encode it, and compare it in constant time with the X-Shopify-Hmac-Sha256 header. If it matches, queue the work and return 200. If it is different or missing, return 401 and process nothing.

This guide covers exactly what Shopify signs, why the body has to reach your function untouched, how to do it in Express and in a Next.js route handler, and what to return in each case. We ran all of the code on Node 22, with tests that send real signed requests using a test secret.

Why an unverified webhook is a risk

A webhook endpoint is a public URL that accepts a POST from anyone. Shopify calls it when something happens in the store, but nothing stops someone else from sending a JSON payload of the same shape to the same URL. If your code trusts whatever arrives, that forged payload can create an order that never existed and trigger its shipment, wipe data with a fake customers/redact, or flood your queue with junk.

Hiding the URL does not help: it shows up in the app configuration and in logs. Neither does CORS, which only browsers enforce, as we explain in why CORS does not protect your API. What tells a Shopify delivery apart from a forged one is the signature, and Shopify's guide to verifying webhook deliveries is direct about it: verify the signature before processing, and reject any delivery whose signature does not match.

How Shopify signs a webhook (HMAC-SHA256 of the body, base64)

Every HTTPS delivery carries a base64-encoded HMAC-SHA256 signature in the X-Shopify-Hmac-Sha256 header, generated with your app's client secret and the raw request body. An HMAC mixes a secret into a message: without the secret you cannot produce the right signature, and if a single byte of the message changes, the signature changes completely. You hold the same secret, so you compute the signature yourself and compare it with the one that arrived.

The secret is the client secret in the Dev Dashboard, under Apps → your app → Settings → Credentials, not your Admin API access token. Shopify's guide to managing your app credentials says to treat it like a password and never ship it in client-side code. The signature only exists on HTTPS deliveries: Google Cloud Pub/Sub and Amazon EventBridge deliveries don't need it.

Other headers travel with the signature. These are the ones listed in the webhooks delivery structure:

HeaderWhat it holdsWhat you use it for
X-Shopify-Hmac-Sha256The base64 HMAC signature; HTTPS onlyProving the delivery came from Shopify
X-Shopify-TopicThe topic, for example products/updateDeciding which job to queue
X-Shopify-Shop-DomainThe store's myshopify.com domainKnowing which store it is for
X-Shopify-API-VersionThe API version used to serialize the payloadReading the fields correctly
X-Shopify-Webhook-IdA unique key per deliverySpotting duplicates
X-Shopify-Event-IdAn ID shared by every delivery from the same merchant actionCorrelating deliveries across subscriptions
X-Shopify-Triggered-AtWhen Shopify triggered the deliveryLogging and ordering
X-Shopify-Name (optional)The name you gave the subscriptionTelling subscriptions apart

Shopify asks you to treat these names as case-insensitive, because HTTP/2 often lowercases them. That is why the code below reads x-shopify-hmac-sha256.

how a Shopify webhook gets verifiedShopify signs every deliveryX-Shopify-Hmac-Sha256 = base64(HMAC-SHA256(client secret, raw body))POST over HTTPS to your endpoint1 read the raw bodyexpress.raw() or arrayBuffer()2 compute your own HMACHMAC-SHA256, client secret, base643 compare in constant timesame length + timingSafeEqualmatchX-Shopify-Webhook-Id seen: 200new: queue it, 200 within 5 sno match or missing401 Unauthorized, nothing processedno valid signature, no processingShopify waits 5 s for a 200; if it fails, it retries 8 times over 4 hours

Scroll the figure sideways to see all of it

Verifying in Node with the raw body

This is the rule that breaks most often: the signature covers the exact bytes that arrived, not the object you get after parsing them. Once a middleware like express.json() has turned the body into an object, rebuilding it with JSON.stringify does not give you the same bytes back. In our test the body lost three spaces, and the ID, which is above Number.MAX_SAFE_INTEGER, got rounded. The result: a different signature.

same JSON, different bytes, different HMACwhat arrived: the raw body{"id": 820982911946154508, "email": "jon@example.com"}54 bytes · SxC0VGL6QEViUkUL42BJevF1PyxQ1J7zIzFu77aieIs=JSON.stringify(JSON.parse(body))what your code rebuilds{"id":820982911946154500,"email":"jon@example.com"}51 bytes · OVKTpO1rdZWUzfBQ19+QbZVS0hFMn4o7uI9wzlu4arw=· spaces gone: 3 bytes shorter· the id is above Number.MAX_SAFE_INTEGER, so JavaScript rounds itverify the bytes that arrived, not the objectillustrative example, signed with the test secret test_secret_do_not_use

Scroll the figure sideways to see all of it

This is the verification function, verify.mjs, with no dependencies:

import { createHmac, timingSafeEqual } from "node:crypto";

export function verifyShopifyWebhook(rawBody, hmacHeader, secret) {
  if (!secret || typeof hmacHeader !== "string") return false;
  if (typeof rawBody !== "string" && !Buffer.isBuffer(rawBody)) return false;

  const expected = Buffer.from(createHmac("sha256", secret).update(rawBody).digest("base64"));
  const received = Buffer.from(hmacHeader);

  return expected.length === received.length && timingSafeEqual(expected, received);
}
  1. No secret, or no header, returns false. The first check matters more than it looks: if the environment variable is empty and you compute the HMAC with an empty key, anyone can sign with that same empty key.
  2. A body that is neither a Buffer nor a string returns false. That is what req.body holds when express.raw() did not handle the request (Express leaves it undefined) or when express.json() got there first (an object).
  3. expected is your signature: HMAC-SHA256 of the raw body with the client secret, in base64, just like Shopify's.
  4. received is the header exactly as it arrived, as bytes.
  5. It compares the length first and then the bytes, with timingSafeEqual. That order matters, as the next section shows.

With Express

In Express 5, express.raw() puts the body in req.body as a Buffer, but only for requests whose Content-Type matches its type option (by default, application/octet-stream), per the Express API reference. That is why it sits on the webhook route only, with type: "application/json". This is server.mjs:

import express from "express";
import { verifyShopifyWebhook } from "./verify.mjs";
import { enqueueWebhook } from "./webhook-queue.mjs";

const secrets = [process.env.SHOPIFY_API_SECRET, process.env.SHOPIFY_API_SECRET_OLD].filter(Boolean);

export const app = express();

app.post("/webhooks/shopify", express.raw({ type: "application/json" }), async (req, res) => {
  const hmac = req.get("x-shopify-hmac-sha256");
  if (!secrets.some((secret) => verifyShopifyWebhook(req.body, hmac, secret))) {
    return res.status(401).send("invalid hmac");
  }

  await enqueueWebhook({
    id: req.get("x-shopify-webhook-id"),
    topic: req.get("x-shopify-topic"),
    shop: req.get("x-shopify-shop-domain"),
    body: req.body.toString("utf8"),
  });
  res.sendStatus(200);
});

app.use(express.json());
  1. secrets holds the current secret and, while you rotate, the previous one. filter(Boolean) drops the ones that are not set, so with none set every delivery gets a 401.
  2. express.raw() only runs on this route, so here req.body is the original Buffer. req.get() reads headers case-insensitively.
  3. If no secret validates the signature, it returns 401 and leaves without touching the body.
  4. enqueueWebhook stores the delivery ID, the topic, the shop and the body. If it throws, Express 5 sends the rejected promise to its error handler, Shopify gets a 500 and retries. Otherwise res.sendStatus(200) acknowledges the delivery.
  5. app.use(express.json()) comes after the webhook route, so the rest of your API still gets parsed JSON.

With a Next.js route handler

In the App Router, a route handler gets a standard Web Request. The route handler docs include a webhook example that reads the body with request.text() and point out that, unlike Pages Router API Routes, there is no bodyParser to configure. Save the function above as lib/verify-shopify-webhook.js, the queue as lib/webhook-queue.js, and create app/api/webhooks/shopify/route.js:

import { verifyShopifyWebhook } from "@/lib/verify-shopify-webhook";
import { enqueueWebhook } from "@/lib/webhook-queue";

const secrets = [process.env.SHOPIFY_API_SECRET, process.env.SHOPIFY_API_SECRET_OLD].filter(Boolean);

export async function POST(request) {
  const rawBody = Buffer.from(await request.arrayBuffer());
  const hmac = request.headers.get("x-shopify-hmac-sha256");
  if (!secrets.some((secret) => verifyShopifyWebhook(rawBody, hmac, secret))) {
    return new Response("invalid hmac", { status: 401 });
  }

  await enqueueWebhook({
    id: request.headers.get("x-shopify-webhook-id"),
    topic: request.headers.get("x-shopify-topic"),
    shop: request.headers.get("x-shopify-shop-domain"),
    body: rawBody.toString("utf8"),
  });
  return new Response(null, { status: 200 });
}
  1. Both imports use the Next.js @/ alias; if your project does not have it, use a relative path.
  2. Buffer.from(await request.arrayBuffer()) reads the body once, as bytes. Do not call request.json() first: it consumes the body and leaves you with only the object.
  3. An invalid or missing signature gets a 401. The rest matches Express: queue the job and return 200.

With valid UTF-8 JSON, request.text() works too; with an invalid byte, text() replaces it and the signature stops matching (we tested it), so we read bytes. Buffer and node:crypto are available in the nodejs runtime, the default according to the Next.js route segment config.

If you would rather use a library: with Shopify's React Router template, authenticate.webhook(request) verifies the signature before your code runs, and @shopify/shopify-api ships shopify.webhooks.validate(), which takes the raw body as a string. We did not install it for this article.

Constant-time comparison against timing attacks

Comparing two strings with === can stop at the first character that differs. In theory, someone who measures how long your endpoint takes to answer could guess the signature one character at a time. You don't need to decide whether that attack is practical against you, because avoiding it takes one line: per the Node.js crypto docs, timingSafeEqual compares the bytes with a constant-time algorithm, does not leak timing information that would let an attacker guess one of the values, and is suitable for comparing HMAC digests.

The same docs warn about two things. First, timingSafeEqual throws when the two buffers have different byte lengths. This is length.mjs:

import { timingSafeEqual } from "node:crypto";

try {
  timingSafeEqual(Buffer.from("SxC0VGL6QEViUkUL42BJevF1PyxQ1J7zIzFu77aieIs="), Buffer.from("abc"));
} catch (err) {
  console.log(err.name, err.code);
  console.log(err.message);
}

And this is its output:

RangeError ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH
Input buffers must have the same byte length
  1. The first buffer is a real 44-character signature; the second is a three-character header.
  2. timingSafeEqual does not return false: it throws a RangeError with the code ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH.
  3. Inside an Express route, an uncaught exception like that turns into a 500 instead of a 401.

Checking the length first gives nothing useful away: a base64 HMAC-SHA256 signature is always 44 characters (32 bytes). The second warning is that timingSafeEqual does not make the surrounding code timing-safe, which is why our function only returns early when something is missing or the length is wrong, never based on the signature's content.

The manual example in Shopify's docs passes the decoded signature straight to timingSafeEqual, with no length check. We ran it as published on Express 5.3.0, and it did not start: app.post('*', ...) fails with TypeError: Missing parameter name at index 1: *, because Express 5 no longer accepts an unnamed wildcard. With the path changed to '/*splat', it returned 200 and 401 as expected, but 500 when the header was missing or had a different length. That 500 lets nobody in, but it is not the answer the App Store asks for.

What to return when the signature does not match

On an invalid or missing signature, return 401 Unauthorized and process nothing: no database writes, no queue, no logging the full body. That is what Shopify's manual example does, and for App Store apps it is mandatory on compliance webhooks: the privacy law compliance page says that if one of them arrives with an invalid HMAC, the app must return 401 Unauthorized. Those are customers/data_request, customers/redact and shop/redact, and your app must be subscribed to all three and verify them before you submit it for review. Note that the library example returns 400, not 401.

On a valid signature, answer fast. Per Shopify's docs, any response outside the 200 range, 3XX included, counts as an error; there is a one-second connection timeout and a five-second timeout for the whole request. With no response or an error, Shopify retries 8 times over the next 4 hours. After 8 consecutive failures, it deletes the subscription if you created it through the Admin API, and sends warning emails to the app's emergency developer email address.

what to answer to each webhookdeliveryanswerthenvalid HMAC, new id200the queue processes it latervalid HMAC, id already seen200skip it, already handledinvalid or missing HMAC401touch nothingyour queue throws500Shopify retriesno answer within 5 stimeoutcounts as a failure8 failures in a row—subscription deleted (Admin API)a 200 only after verifying and queueing8 retries over 4 hours; a 3XX also counts as an error

Scroll the figure sideways to see all of it

Answering fast means not doing the work inside the request: verify, queue, respond. Shopify suggests exactly that, together with a reconciliation job that periodically fetches anything you missed. The queue in our example is the minimum needed for testing, webhook-queue.mjs:

// shortcut: in memory and in one process; in production, a table with the webhook id as its primary key.
const seen = new Set();
export const jobs = [];

export async function enqueueWebhook(job) {
  if (seen.has(job.id)) return false;
  seen.add(job.id);
  jobs.push(job);
  return true;
}
  1. The comment says it: it lives in memory, in a single process. In production, use a table with the delivery ID as its primary key.
  2. seen keeps the X-Shopify-Webhook-Id values already received: Shopify warns that the same delivery can arrive more than once, for example after a network timeout or a retry.
  3. If the ID is already there, nothing is queued and the endpoint still returns 200, as Shopify asks. If it is new, it is recorded and queued.

Deduplicate on X-Shopify-Webhook-Id, not X-Shopify-Event-Id: with two subscriptions to the same topic, each delivery has its own Webhook-Id and both share the Event-Id. And if the worker reading the queue charges cards, decrements stock or sends emails, make it idempotent. It is the same idea we use for idempotency keys that stop double charges, with the webhook ID playing the part of the key.

To try it locally without Shopify, start the server with SHOPIFY_API_SECRET=test_secret_do_not_use node start.mjs (a start.mjs that only calls app.listen(8798)) and, in another bash terminal (Git Bash works on Windows), run bash curl.sh:

SECRET=test_secret_do_not_use # placeholder: never paste your real client secret into a script
BODY='{"id": 820982911946154508, "email": "jon@example.com"}'
HMAC=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" -binary | base64)
send() { curl -s -o /dev/null -w "$1: %{http_code}" http://localhost:8798/webhooks/shopify -H "content-type: application/json" -H "x-shopify-webhook-id: $1" -H "x-shopify-hmac-sha256: $2" -d "$3"; echo; }

send wh-1 "$HMAC" "$BODY"
send wh-1 "$HMAC" "$BODY"
send wh-2 "$HMAC" '{"id": 820982911946154508, "email": "eve@example.com"}'
send wh-3 "not-a-signature" "$BODY"

This is the output we got:

wh-1: 200
wh-1: 200
wh-2: 401
wh-3: 401
  1. HMAC is the signature from openssl dgst -sha256 -hmac in binary, then base64, the way Shopify computes it. For this body it matches the one Node computes.
  2. The first delivery gets 200 and is queued. The second repeats the ID wh-1: 200, but it is not queued again (the tests check that, not this output).
  3. The third changes the email and keeps the signature; the fourth carries a made-up signature. Both get 401.

On top of that, 26 tests with Node's built-in test runner passed: ten on the function (including the rebuilt body, the empty secret and the different-length header), eight against Express with signed HTTP requests, seven against the route handler called with a Node 22 Request, and one on Shopify's example.

Common mistakes

  • Parsing before verifying. A global app.use(express.json()) ahead of the route, or a request.json() in Next.js, leaves you without the original bytes. JSON.stringify does not rebuild them: in our test it dropped spaces and rounded an ID.
  • Comparing without a length check. timingSafeEqual throws on different lengths, and a missing header breaks Buffer.from. Your endpoint answers 500 instead of 401.
  • Computing the HMAC with an empty secret. If the environment variable is missing and your code signs with "", anyone can sign the same way. Always reject when there is no secret.
  • Doing the work before answering. Shopify gives up after five seconds, counts that as a failure and retries, so the same webhook arrives again while the first one is still running.
  • Returning 200 for everything "so Shopify stops retrying". If your queue failed, that 200 loses the event. A 500 is the right answer: Shopify retries it.
  • Validating only with the new secret during rotation. While you rotate, Shopify signs with your oldest unrevoked secret. Accept both until you revoke the old one.
  • Forgetting the size limit. express.raw() accepts 100 KB by default. If your payloads can be bigger, raise limit; otherwise Express rejects the request and Shopify counts it as a failure.

Frequently asked questions

Do I need to verify the HMAC if I use Shopify's app template?

Not by hand. With the React Router template, authenticate.webhook(request) verifies the signature before your code runs. If you wrote your own server in Express, Next.js or another framework, verification is on you.

Which secret do I use for the HMAC?

Your app's client secret, in the Dev Dashboard under Settings, in the Credentials section. Not the client ID and not an access token, or the signature will not match. Keep it in an environment variable or a secrets manager, never in the repository.

What happens to webhooks when I rotate the client secret?

Per Shopify's credentials guide, as long as the old secret is not revoked, Shopify keeps signing with it. Accept both (in our code, SHOPIFY_API_SECRET and SHOPIFY_API_SECRET_OLD) and drop the old one only after revoking it. Shopify adds that it can take up to an hour before it signs with the new one.

Why does the same webhook arrive twice?

Shopify can repeat a delivery after a network timeout or a retry, and with two subscriptions to the same topic you get one delivery per subscription. Deduplicate on X-Shopify-Webhook-Id and make the worker that reads the queue idempotent.

Checklist

  • The webhook route gets the raw body: express.raw() on that route only, or arrayBuffer() in Next.js.
  • You compute HMAC-SHA256 of the raw body with the client secret, base64-encoded.
  • You check the length first, then compare with timingSafeEqual; with no secret or no header it fails without throwing.
  • Invalid or missing signature: 401, nothing processed.
  • Valid signature: you queue the job and return 200 within five seconds.
  • You deduplicate on X-Shopify-Webhook-Id in a shared store, and the queue worker is idempotent.
  • When rotating the client secret, you accept the old and the new one until the old one is revoked.
  • If you list on the App Store, all three compliance webhooks verify the HMAC and return 401 when it fails.

With the signature checked, a webhook stops being a URL anyone can call and becomes a message from Shopify. The next step is processing it well: with a Postgres job queue using SKIP LOCKED and an idempotent worker, as in idempotency keys for payments. If you are still deciding whether your integration needs its own app, start with when a custom Shopify app is the right call.

Saw this on Instagram? Comment HMAC on the Reel and I'll send you the guide.

Written by

Luis Morales

Luis Morales

Frontend and Shopify developer, EcomLabs

@luismoralesdev on Instagram

Published November 3, 2026

← Blog