Lemon Squeezy Webhook "Invalid Signature"? A Fix Checklist for Next.js and Express
Your Lemon Squeezy webhook arrives, but your check of the X-Signature header fails every time. In almost every public report of this, the code hashes something other than the exact bytes Lemon Squeezy sent. The usual culprit is JSON.stringify(req.body) after a JSON parser has already run. This checklist goes from the most common cause to the rarest, with working code for the Next.js App Router, the Next.js Pages Router and Express.
How the signature works
From the Lemon Squeezy docs:
- When you create a webhook, you choose a signing secret (normally a random string of 6 to 40 characters).
- Lemon Squeezy uses the secret to make "a hash of the payload" and sends it in the
X-Signatureheader. The hash is an HMAC-SHA256 hex digest. - You compute the same HMAC over the payload and compare.
- The request also carries
Content-Type: application/jsonand anX-Event-Nameheader.
So three things must match exactly: the bytes you hash, the secret, and the algorithm and encoding.
Sources: Signing Requests, Webhook Requests.
☐ 1. Are you hashing the raw body, not a re-serialised object?
This is the cause in most Stack Overflow questions about it. The broken pattern looks like this:
app.post('/webhook', express.json(), (req, res) => {
const digest = crypto.createHmac('sha256', secret)
.update(JSON.stringify(req.body)) // ✗ not the bytes that were signed
.digest('hex');
JSON.stringify of a parsed object doesn't give back the original text. Whitespace, key order and character escaping can all change. For example, JSON.stringify doesn't escape forward slashes, so a body that contains https:\/\/... comes back as https://.... Any changed byte gives a different HMAC.
Fix: read the body as raw text or bytes, verify it, then JSON.parse that same string.
☐ 2. Read the raw body correctly for your framework
Next.js App Router (app/api/webhooks/lemonsqueezy/route.ts)
import crypto from "node:crypto";
export const runtime = "nodejs";
export async function POST(request: Request) {
const secret = process.env.LEMONSQUEEZY_WEBHOOK_SECRET;
if (!secret) return new Response("Webhook secret not set", { status: 500 });
const rawBody = await request.text(); // read once, as text
const header = request.headers.get("x-signature") ?? "";
const expected = Buffer.from(
crypto.createHmac("sha256", secret).update(rawBody).digest("hex"), "hex");
const given = Buffer.from(header, "hex");
if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) {
return new Response("Invalid signature", { status: 401 });
}
const event = JSON.parse(rawBody); // parse the same string
// ... handle event.meta.event_name
return new Response("OK", { status: 200 });
}
Don't call request.json() before request.text(). The body can only be read once. Lemon Squeezy's own Next.js guide uses this same await request.text() approach, and Next.js notes that Route Handlers don't need any bodyParser configuration.
Sources: Receive Lemon Squeezy Webhooks in Next.js, Next.js route.js reference.
Next.js Pages Router (pages/api/...)
API routes parse the body automatically. The Next.js docs say you can set bodyParser to false to consume the body as a stream, and they name webhook verification as one use case:
export const config = { api: { bodyParser: false } };
export default async function handler(req, res) {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
const rawBody = Buffer.concat(chunks);
// verify rawBody exactly as above, then JSON.parse(rawBody.toString("utf8"))
}
Source: Next.js API Routes, custom config.
Express
Use express.raw on the webhook route. It "parses incoming request payloads into a Buffer". Register that route before any global app.use(express.json()), so the JSON parser doesn't consume the body first:
app.post('/webhooks/lemonsqueezy',
express.raw({ type: 'application/json' }),
(req, res) => {
const expected = Buffer.from(
crypto.createHmac('sha256', process.env.LEMONSQUEEZY_WEBHOOK_SECRET)
.update(req.body).digest('hex'), 'hex');
const given = Buffer.from(req.get('X-Signature') || '', 'hex');
if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) {
return res.status(401).send('Invalid signature');
}
const event = JSON.parse(req.body.toString('utf8'));
res.sendStatus(200);
});
app.use(express.json()); // the rest of your API
If you must keep a global express.json(), its verify(req, res, buf) option gives you "a Buffer of the raw request body". Save buf on req there and hash that.
Source: Express 5.x API, express.raw / express.json.
☐ 3. Is it the right secret?
- Use the signing secret you typed when creating that webhook in Settings › Webhooks. Your API key won't work.
- Lemon Squeezy keeps test-mode and live-mode webhooks separate: "a test mode webhook will only be triggered for test mode data and vice versa". If you set up a live webhook with a new secret, update the environment variable for that deployment.
- Check that the variable is actually loaded where the code runs. On many hosts, a changed environment variable only takes effect after a redeploy (Note: this depends on the host; check your host's docs). If the secret is
undefined,createHmacthrows before you get to compare anything. - Watch for a stray space or newline when you paste the secret into an
.envfile or a hosting dashboard.
Sources: Webhooks, Simulate Webhook Events.
☐ 4. Is it HMAC, and is the comparison sane?
- HMAC-SHA256, not plain SHA-256. One Stack Overflow case (C#) hashed payload + secret with plain SHA-256. It has to be an HMAC keyed with the secret.
- Hex. The header is a hex digest. Compare hex with hex: decode both from hex as above, or compare the two hex strings as UTF-8 buffers like the docs example does. Don't compare base64 with hex.
timingSafeEqualthrows on different lengths. Node's docs: "An error is thrown if a and b have different byte lengths." Check the lengths first (as in the code above), so a missing or short header returns 401 instead of a 500.
Source: Node.js crypto.timingSafeEqual.
☐ 5. Is something between Lemon Squeezy and your code changing the body?
If steps 1–4 are right and it still fails, look at what sits in front of the handler: a proxy, a serverless adapter, middleware that logs and re-writes the body, or a framework that decodes the body before your code sees it.
Note: in GitHub issue lmsqueezy/lemonsqueezy.js#115, one user testing with Express, Next.js and SolidStart reported that the text body they received had lost the backslashes in escaped URLs (\/), which broke the check. They worked around it by putting the backslashes back. A contributor to the repository advised reading the raw body as bytes instead. We haven't been able to verify which setups cause this. Treat it as a last resort, and prefer fixing the raw-body reading.
Source: lmsqueezy/lemonsqueezy.js issue #115.
☐ 6. Debug without leaking secrets
- Log the length of the raw body, the received header and your computed hex digest. Never log the secret.
- Use the webhook log in Lemon Squeezy. The docs say recent webhooks are logged on the webhooks settings page with "the full payloads of each request", and you can resend them from there.
- In test mode you can simulate events for a test order or subscription from the Lemon Squeezy admin, for example
subscription_createdororder_created.
Sources: Webhooks, Simulate Webhook Events.
☐ 7. After it passes: retries and duplicates
The docs say to return a 200 to show the webhook was captured. Any other status is retried "up to three more times using an exponential backoff strategy (e.g. 5 secs, 25 secs, 125 secs)". That has two consequences:
- Return a non-200 only when you really want a retry, for example when your database is down.
- Expect the same event more than once, and make the handler safe to repeat. Record an id or a hash of each raw body you've processed, and skip repeats.
Source: Webhook Requests.
Symptom table
| Symptom | Most likely cause | Step |
|---|---|---|
| Fails on every event, locally and in production | Hashing JSON.stringify(req.body) |
1, 2 |
| Works locally, fails after deploy | Secret not set or different in that environment | 3 |
| Works in test mode, fails in live mode | Live webhook has its own secret | 3 |
| 500 error instead of 401 | timingSafeEqual length error, or createHmac with an undefined secret |
3, 4 |
| Fails only for some events | Body changed in transit; escaped characters | 5 |
| Same order processed twice | Retries or resends without de-duplication | 7 |
If you're building subscriptions with license keys on Lemon Squeezy
If your app sells licensed software through Lemon Squeezy, Rindstack is a Next.js 15 starter with this webhook path already wired up. Its product page lists:
- A webhook handler that verifies
X-Signature(HMAC-SHA256 over the raw body). - Skipping of duplicate deliveries, and late out-of-order events that don't overwrite newer state.
- Lemon Squeezy hosted checkout with your user id attached.
- License keys issued by the webhook, with per-plan device limits, verify/deactivate APIs and a grace period after cancellation.
- A Chrome extension (MV3) example that unlocks with the key.
- English, Chinese and Japanese UI.
It costs $99 one-time (Personal) or $199 (Team).
Its listed limits:
- No Stripe, teams, blog, transactional email or admin panel.
- Lemon Squeezy was mocked in its tests, and the starter hasn't yet been run against a live Lemon Squeezy store. Its guide asks you to do one test-mode purchase before launch.
- The Vercel deployment guide hasn't been deployed by its author.
Sources
- Lemon Squeezy Docs, Webhooks: https://docs.lemonsqueezy.com/help/webhooks
- Lemon Squeezy Docs, Signing Requests: https://docs.lemonsqueezy.com/help/webhooks/signing-requests
- Lemon Squeezy Docs, Webhook Requests: https://docs.lemonsqueezy.com/help/webhooks/webhook-requests
- Lemon Squeezy Docs, Simulate Webhook Events: https://docs.lemonsqueezy.com/help/webhooks/simulate-webhook-events
- Lemon Squeezy Guides, Receive Lemon Squeezy Webhooks in Next.js: https://docs.lemonsqueezy.com/guides/tutorials/webhooks-nextjs
- Next.js Docs, route.js: https://nextjs.org/docs/app/api-reference/file-conventions/route
- Next.js Docs, API Routes: https://nextjs.org/docs/pages/building-your-application/routing/api-routes
- Express 5.x API, express(): https://expressjs.com/en/5x/api/express/
- Node.js Docs, crypto.timingSafeEqual: https://nodejs.org/api/crypto.html
- GitHub, lmsqueezy/lemonsqueezy.js issue #115: https://github.com/lmsqueezy/lemonsqueezy.js/issues/115
Note: code samples follow the current docs listed above. Framework defaults change between versions, so check the docs for the version you use.