How to Validate a Webhook Payload With a JSON Schema
Verify the signature first, then validate the payload against a JSON schema so malformed bodies never reach business logic.
After signature verification, run the parsed body through a compiled JSON schema (for example with Ajv). Reject with 400 on a schema failure so bad input fails fast.
Steps
- Verify the HMAC signature before parsing.
- Compile a JSON schema for the event shape you expect.
- Reject with 400 when the parsed payload fails validation.
Handler
handler.js
const Ajv = require('ajv');
const validate = new Ajv().compile({
type: 'object',
required: ['action', 'number'],
properties: {
action: { type: 'string' },
number: { type: 'integer' },
},
});
function onPayload(payload) {
if (!validate(payload)) {
return { status: 400, body: validate.errors };
}
return { status: 200 };
}Gotchas
- Validate after signature verification, never before, so forged bodies are dropped first.
- Keep schemas permissive on unknown keys; senders add fields over time.
Related guides
How to Read Webhook Payloads and Event TypesRead a webhook payload correctly by routing on the event header first, then accessing the action and object f…
How to Verify a Webhook Signature With HMAC SHA-256Verify an incoming GitHub webhook by computing an HMAC SHA-256 over the raw body with your secret and compari…