Skip to content
Latchkey

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

Run this faster and cheaper on Latchkey managed runners. Start free →