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.
// 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
}
}];
```text
> **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.
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](../security-best-practices/01-set-a-unique-encryption-key-and-back-it-up.md) | [Use the HTTP Request Node as a Universal Connector](../integration-patterns/01-use-the-http-request-node-as-a-universal-connector.md)
I build production n8n and Cloudflare automation for teams — the same engineering behind HarperFlow. Fixed-price, escrow-protected, US-based.