Tips > Data, APIs & Webhooks

Validate Webhook Payloads with JSON Schema Before Processing

Never trust incoming webhook data.

Never trust incoming webhook data. Use a Code node immediately after the Webhook node to validate the payload against a JSON Schema. This catches malformed requests early, prevents downstream errors from missing or wrong-typed fields, and gives callers clear error messages.

Real-world example: A partner system sends product update events. Before updating your database, validate that the payload contains the required fields with correct types.

How do you validate a webhook payload against a JSON Schema?

// Code node: "Validate Payload"
const Ajv = require('ajv');
const ajv = new Ajv({ allErrors: true });

const schema = {
  type: 'object',
  required: ['product_id', 'name', 'price', 'currency'],
  properties: {
    product_id: { type: 'string', minLength: 1 },
    name: { type: 'string', minLength: 1, maxLength: 255 },
    price: { type: 'number', minimum: 0 },
    currency: { type: 'string', enum: ['USD', 'EUR', 'GBP'] },
    description: { type: 'string', maxLength: 5000 },
    tags: {
      type: 'array',
      items: { type: 'string' },
      maxItems: 20
    }
  },
  additionalProperties: false
};

const validate = ajv.compile(schema);
const payload = $input.first().json.body;

if (!validate(payload)) {
  const errors = validate.errors.map(e => `${e.instancePath} ${e.message}`);
  return [{
    json: {
      valid: false,
      errors,
      statusCode: 400
    }
  }];
}

return [{
  json: {
    valid: true,
    data: payload,
    statusCode: 200
  }
}];

Note: AJV Availability

n8n's Code node runs in a Node.js sandbox. If require('ajv') is not available in your n8n installation, implement validation manually with type checks and required-field checks. The principle remains the same: validate early, reject fast.

How do you route valid and invalid payloads?

Route the output with an IF node on $json.valid. Invalid payloads get a 400 response via the Respond to Webhook node; valid payloads continue to the business logic.

Related: Set a Unique Encryption Key and Back It Up · Use the HTTP Request Node as a Universal Connector

Showcase builds

19 complete workflows from my own projects, each with its n8n workflow JSON to import. Showcase entries link the file at the end of the article.

See the showcase builds

Keep reading

190 entries grouped by topic, from first workflow to queue mode. Free, no signup.

Browse the encyclopedia

Need it built?

I design, build and run n8n systems for clients. Every engagement starts with a $1,500 diagnostic audit, credited toward the build.

Book an introductory call