Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 55 ยท Webhooks

Verifying Webhook Signatures

Verify the X-Shopify-Hmac-Sha256 header correctly: use the raw body, compute a base64 HMAC-SHA256, compare in constant time and reject forgeries. Includes a runnable verifier.

A webhook endpoint is a public URL. Anyone who learns it can send a POST that claims "order 1001 was paid" or "this shop uninstalled your app". If your code believes such a request, a stranger controls your data. Shopify solves this by signing every delivery: it computes a keyed hash over the request body and sends the result in a header. If you can reproduce that hash, the request came from Shopify and nobody changed it on the way.

In this lesson you will learn what exactly is signed, how to verify it in plain Node.js, which mistakes make a valid request fail (or a forged one pass), and how the app template does it for you. The general ideas of signed events are explained in Webhooks and Signature Verification; here we apply them to Shopify. If you have not seen how subscriptions and deliveries work yet, read Webhooks in Shopify first.

What Shopify sends

Every HTTPS delivery carries headers that describe it. The ones you will use most:

Header Meaning
X-Shopify-Hmac-Sha256 The signature, base64 encoded
X-Shopify-Topic What happened, for example orders/paid or app/uninstalled
X-Shopify-Shop-Domain The shop that triggered it, such as example.myshopify.com
X-Shopify-API-Version The API version used to shape the payload
X-Shopify-Webhook-Id An id for this webhook delivery (used for de-duplication, see Reliable Webhook Handlers)

The signature is an HMAC-SHA256 of the raw request body, using your app's client secret as the key, and then encoded with base64 (not hexadecimal). The client secret is the one value from your app's settings in the Dev Dashboard (older screens call it the API secret key). It is not the access token a merchant's shop gave you.

sequenceDiagram
    participant S as Shopify
    participant A as Your endpoint
    S->>S: HMAC-SHA256(client secret, raw body) then base64
    S->>A: POST body + X-Shopify-Hmac-Sha256
    A->>A: Recompute from the raw bytes you received
    A->>A: Compare in constant time
    alt Equal
        A-->>S: 200 OK (then process)
    else Different
        A-->>S: 401 Unauthorized
    end

You never see the secret on the wire; you only prove you know it.

Note what is not in the signature scheme: there is no signed timestamp. A captured request would stay valid forever. That is why Shopify gives every delivery an id, and why a good handler remembers the ids it has already seen.

Computing the signature

Node's built-in crypto module has everything you need. This stand-in uses a fake secret and a small body, and shows the signature changing when the body changes. The code is an ordinary Node program; the only thing "pretend" is the secret and the payload.

Node.js Sign a body the way Shopify does

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A base64 HMAC-SHA256 is always 44 characters long and ends with =. If your computed value is 64 characters of 0-9a-f, you used hex by mistake and will never match.

Why the raw body matters

The HMAC covers bytes, not "the JSON". Web frameworks usually parse JSON for you, and then the original bytes are gone. If you call JSON.stringify(parsedBody) and hash that, you may produce different spacing, different escape sequences or a different key order, and a perfectly genuine delivery fails verification.

This is the single most common webhook bug. The cure is to read the body as text or a buffer before any parser touches it, verify, and only then parse.

Node.js A complete verifier and the re-serialization trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Run it and compare cases 1 and 6. The data is identical, but the second body has no spaces, so the bytes (and the HMAC) differ. Verification must use exactly what arrived.

Constant-time comparison

Comparing two strings with === stops at the first different character. In theory, an attacker who can measure response times very precisely could learn a correct signature one character at a time. crypto.timingSafeEqual takes the same time wherever the difference is. It throws if the two buffers have different lengths, which is why the code above checks the length first and returns early. Decoding both sides from base64 into buffers also avoids trouble with different but equivalent base64 spellings.

In the app template: authenticate.webhook

You rarely write this by hand. The React Router app template ships a helper that reads the raw body, verifies the signature with your client secret, and hands you the parsed payload. This is real platform-style code and is read-only here; the lesson's stand-ins above show what happens inside the helper.

TypeScript
// app/routes/webhooks.app.uninstalled.tsx  (read-only example)
import type { ActionFunctionArgs } from "react-router";
import { authenticate } from "../shopify.server";
import db from "../db.server";

export const action = async ({ request }: ActionFunctionArgs) => {
  // Throws a 401 Response if the HMAC does not match.
  const { shop, topic, session } = await authenticate.webhook(request);

  console.log(`Received ${topic} for ${shop}`);

  if (session) {
    await db.session.deleteMany({ where: { shop } });
  }
  return new Response();
};

If you build your own endpoint (for example in a different framework), verify first, then parse. In Express-style code that means a raw-body parser on this one route:

JavaScript
// read-only sketch: verify before parsing
app.post(
  "/webhooks",
  express.raw({ type: "application/json" }), // req.body stays a Buffer
  (req, res) => {
    const header = req.get("X-Shopify-Hmac-Sha256");
    const result = verifyWebhook(req.body, header); // body is the raw Buffer
    if (!result.ok) return res.status(401).end();
    const payload = JSON.parse(req.body.toString("utf8"));
    // ...enqueue the work, then answer quickly
    res.status(200).end();
  }
);

Two details: register the raw parser only for the webhook route (the rest of your app may still use express.json()), and respond with 401 for a bad signature without explaining why. An attacker gains nothing from a detailed error.

Common mistakes

  • Hashing the parsed object. Always hash the original bytes.
  • Using the wrong secret. The client secret signs webhooks. An access token or an old secret from a different app will never match. After you rotate the secret, deliveries signed with the new one need the new value on your server.
  • Comparing hex to base64. Use the same encoding on both sides, and prefer comparing decoded buffers.
  • Verifying after side effects. Never write to your database "just in case" before the check has passed.
  • Logging secrets. Log the topic, shop and webhook id, never the secret or the full signature of failed attempts in a public log.
  • Treating a valid signature as "new". A genuine delivery can be retried or duplicated. Authentication tells you who sent it, not whether you have already handled it.

Testing locally

While developing with shopify app dev, the CLI can send a sample delivery to your local endpoint with shopify app webhook trigger (read-only here; check shopify app webhook trigger --help for the current options). The sample is signed with your app's client secret, so a correct verifier accepts it and a forged curl request is refused. Write a failing request first: send the same body with a changed header and confirm you get 401.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Shopify put in the X-Shopify-Hmac-Sha256 header?

    The signature is an HMAC-SHA256 over the exact bytes of the body, keyed with your app's client secret and encoded as base64. It involves neither the access token nor a signed timestamp.
  2. 2. A genuine webhook fails verification after your framework parsed the JSON and you hashed JSON.stringify(body). What is the most likely cause?

    An HMAC is calculated over exact bytes. Re-serializing can change whitespace or ordering, so the hash no longer matches even though the data is the same.
  3. 3. Why does the verifier use crypto.timingSafeEqual instead of ===?

    A normal comparison can return earlier for a wrong first character, which may leak information through timing. A constant-time comparison avoids that. It requires buffers of equal length, so check the length first.
  4. 4. A request has a valid signature. Can you safely assume you have never processed it before?

    Authentication and uniqueness are separate concerns. Shopify does not sign a timestamp and may deliver the same webhook more than once, so keep a record of handled ids.
  5. 5. Which status should an endpoint return when the signature does not match?

    Reject unauthenticated requests with 401 and no hints. Returning the expected signature would defeat the whole check.

Summary

  • Shopify signs the raw body with HMAC-SHA256, keyed by your app's client secret, and sends it base64 encoded in X-Shopify-Hmac-Sha256.
  • Verify before you parse or act: hash the original bytes, never JSON.stringify of a parsed object.
  • Compare decoded buffers with crypto.timingSafeEqual, after checking that their lengths are equal.
  • In the app template, authenticate.webhook(request) does this and throws a 401 for bad signatures.
  • The signature does not include a timestamp, so a valid delivery can still be a duplicate; de-duplicate separately.

Next: Reliable Webhook Handlers