An unvalidated webhook payload can crash your handlers or corrupt your database. A typical failure: a CRM changes its payload without a version bump and starts sending null instead of an empty array, and your code throws when it calls .map() on it. This tutorial shows how to validate webhook payloads with Zod in Express, so bad data gets a clean 400 response before it reaches your code.
Quick answer: Describe the expected payload as a Zod schema, then add a small Express middleware that runs schema.safeParseAsync(req.body). If parsing fails, return 400 with the list of issues; if it succeeds, replace req.body with the parsed data and call next().
- Install
express,zodand the TypeScript tools. - Define a schema such as
UserSignupSchemainschemas.ts. - Write a
validateBody(schema)middleware inmiddleware.ts. - Add it to the webhook route before the handler.
- Send a bad payload with curl and check the 400 response lists each field.
In this guide
- Before You Start
- What You Will Build
- Step 1: Set Up the Express and Zod Project
- Why Manual Checks Fall Short
- Step 2: Build the Zod Schema for the Webhook
- Step 3: Create the Validation Middleware
- Step 4: Add the Middleware to Your Webhook Route
- Test It: Send a Bad Payload and a Good One
- Handle Optional Fields and Type Coercion
- Verify the Signature Before You Validate
- If It Still Doesn’t Work
- Webhook Validation FAQ
- Next Steps

Before You Start
- Node.js 18 or newer (Express 5 needs it; a current LTS release is best).
- Zod 4 and Express 5.
npm installgives you both today. The schema syntax below is Zod 4; Zod 3 tutorials use different method names. - Two terminal windows, one for the server and one for curl. The tutorial takes about 25 minutes.
- Your provider’s sample payload (most dashboards show one) to model your real schema on.
What You Will Build
tsconfig.json– TypeScript settings.schemas.ts– the Zod schema for a user signup webhook.middleware.ts– the reusablevalidateBodymiddleware.server.ts– the Express app with the protected/webhooks/signuproute.
Step 1: Set Up the Express and Zod Project
Run these commands in your terminal. They install Express and Zod, plus TypeScript and tsx, which runs TypeScript files directly without a build step:
mkdir express-zod-webhooks
cd express-zod-webhooks
npm init -y
npm install express zod
npm install --save-dev typescript @types/node @types/express tsxThis installs Zod 4 and Express 5, which is what the code below is written for. Next, create a tsconfig.json file in the project folder:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}Then create server.ts with a basic Express server. You will add the webhook route to it in Step 4:
import express from 'express';
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});Why Manual Checks Fall Short
You can never trust req.body in a webhook. The quick fix is an inline check that the fields exist before you use them, like this (an illustration only; you do not need to save it):
app.post('/webhooks/user-signup', (req, res) => {
const { email, id, profile } = req.body;
if (!email || !id || !profile || !profile.firstName) {
return res.status(400).send('Missing required fields');
}
console.log(`Processing signup for ${email}`);
res.sendStatus(200);
});That is fine for three fields, but it does not scale. It does not check types, so a number in the email field passes. It gets messy with nested objects, and you repeat the same boilerplate on every endpoint. Once you handle events from several providers, manual checks are hard to keep correct.
Step 2: Build the Zod Schema for the Webhook
Instead of manual checks, define a schema with Zod. The schema is a contract: if the incoming payload does not match it, you reject the request. Create a schemas.ts file for a typical user signup webhook:
import { z } from 'zod';
export const UserSignupSchema = z.object({
event: z.literal('user.signup'),
timestamp: z.iso.datetime(),
data: z.object({
userId: z.uuid(),
email: z.email(),
plan: z.enum(['free', 'pro', 'enterprise']),
metadata: z.record(z.string(), z.string()).optional()
})
});
export type UserSignupPayload = z.infer<typeof UserSignupSchema>;In Zod 4 the string formats are top-level functions (z.email(), z.uuid(), z.iso.datetime()); the older z.string().email() style still works but is deprecated, and z.record() now needs both a key and a value schema.
This schema checks the whole structure before your handler runs:
eventmust be exactly"user.signup".timestampmust be a valid ISO 8601 date-time string.userIdmust be a UUID andemailmust look like an email address.planmust be one of the three listed options.
Step 3: Create the Validation Middleware
Next you need a reusable Express middleware. It takes a Zod schema, checks req.body against it and sends a clear error if anything is wrong. Create a middleware.ts file:
import { Request, Response, NextFunction } from 'express';
import { ZodType, ZodError } from 'zod';
export const validateBody = (schema: ZodType) => {
return async (req: Request, res: Response, next: NextFunction) => {
const result = await schema.safeParseAsync(req.body);
if (!result.success) {
return res.status(400).json({
error: 'Validation failed',
details: formatZodErrors(result.error)
});
}
req.body = result.data;
next();
};
};
function formatZodErrors(error: ZodError) {
return error.issues.map(issue => ({ field: issue.path.join('.'), message: issue.message }));
}safeParseAsync is used instead of parseAsync so a validation failure is returned as a value rather than thrown as an exception. The result has either success: true with the parsed data, or success: false with the issues.
The middleware also sets req.body = result.data. That way any default values or type conversions defined in the schema reach your route handler.
Step 4: Add the Middleware to Your Webhook Route
Now connect the schema and the middleware to the webhook route. Replace the contents of server.ts with this:
import express from 'express';
import { validateBody } from './middleware.js';
import { UserSignupSchema } from './schemas.js';
const app = express();
app.use(express.json());
app.post('/webhooks/signup', validateBody(UserSignupSchema), (req, res) => {
const payload = req.body;
console.log(`Successfully processed signup for user: ${payload.data.email}`);
res.status(200).json({ received: true });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});Start the server in watch mode with tsx, so it restarts when you save a file:
npx tsx watch server.tsYou should see Server running on port 3000.
Test It: Send a Bad Payload and a Good One
Open a second terminal and send a payload with an invalid UUID, an invalid email and an unknown plan:
curl -X POST http://localhost:3000/webhooks/signup -H "Content-Type: application/json" -d '{ "event": "user.signup", "timestamp": "2023-10-27T14:20:00Z", "data": { "userId": "not-a-uuid", "email": "bad-email-format", "plan": "premium" } }'The middleware stops this before it reaches the route. The server answers 400 Bad Request with a JSON body that lists every field that failed:
{
"error": "Validation failed",
"details": [
{
"field": "data.userId",
"message": "Invalid UUID"
},
{
"field": "data.email",
"message": "Invalid email address"
},
{
"field": "data.plan",
"message": "Invalid option: expected one of \"free\"|\"pro\"|\"enterprise\""
}
]
}Now send a valid payload to confirm the happy path:
curl -X POST http://localhost:3000/webhooks/signup -H "Content-Type: application/json" -d '{ "event": "user.signup", "timestamp": "2023-10-27T14:20:00Z", "data": { "userId": "3f0c7a9e-8b1d-4c2e-9f4a-6d5b2e1c0a7f", "email": "ada@example.com", "plan": "pro" } }'This returns {"received":true}, and the server terminal logs Successfully processed signup for user: ada@example.com.
Rejecting bad data this way keeps it out of your logs and database, and the 400 shows up in the provider’s delivery log with the reason. Do not count on a 400 to stop retries: many providers retry any non-2xx response, as the guide to building a webhook retry system with exponential backoff shows from the sender’s side. Log rejected payloads so you notice when a provider changes its format.
Handle Optional Fields and Type Coercion
Webhooks often leave out optional fields or send numbers and dates as strings. Zod handles both without extra parsing code. This separate example schema accepts an optional phone number and turns a timestamp string into a real JavaScript Date. If you add it to schemas.ts, leave out its import line, which is already at the top:
import { z } from 'zod';
export const FlexibleWebhookSchema = z.object({
id: z.string(),
processedAt: z.coerce.date(),
phoneNumber: z.string().optional().nullable()
});z.coerce.date() passes the incoming value through the native Date constructor, so a valid timestamp string arrives in req.body as a Date object. The .optional().nullable() chain means the schema still passes if the service sends null, an empty string or leaves the key out entirely.
Verify the Signature Before You Validate
Checking the payload’s shape is only half the job. You also need to confirm the request really came from your provider, which usually means checking a cryptographic signature in the headers. Verify the signature before parsing the schema, so you do not spend work on payloads from unknown senders. To get real signed payloads on your machine, test webhooks locally with Cloudflare Tunnels.
Here is how to stack signature verification and Zod validation on one route. verifySignature is your own HMAC check in a crypto.ts file; the tutorial on how to verify webhook signatures with HMAC in Node.js shows how to write it:
import express, { Request, Response, NextFunction } from 'express';
import { validateBody } from './middleware.js';
import { UserSignupSchema } from './schemas.js';
import { verifySignature } from './crypto.js'; // Your custom signature check
const app = express();
// express.raw() leaves req.body as a Buffer, so we parse it ourselves once the signature is verified
const parseJsonBody = (req: Request, res: Response, next: NextFunction) => {
try {
req.body = JSON.parse(req.body.toString('utf8'));
next();
} catch {
res.status(400).json({ error: 'Invalid JSON' });
}
};
app.post(
'/webhooks/signup',
express.raw({ type: 'application/json' }), // Need raw body for signature verification
verifySignature,
parseJsonBody,
validateBody(UserSignupSchema),
(req, res) => {
res.sendStatus(200);
}
);This setup only parses payloads whose signature checks out. Stacking express.json() after express.raw() does not work: once one body parser has read the request, the next one skips it, which is why the code parses the Buffer itself. For the same reason, do not register a global express.json() ahead of this route. To stop the same event being processed twice, also store each event ID and skip repeats.
If It Still Doesn’t Work
- Every request fails with
Invalid input: expected object, received undefined: the body was not parsed, usually because the request had noContent-Type: application/jsonheader. Keep the-Hflag in curl and check the provider sends JSON. - Real timestamps fail even though they look valid:
z.iso.datetime()rejects time zone offsets such as+02:00by default. Usez.iso.datetime({ offset: true })if your provider sends them. Cannot find module './middleware.js'or aSyntaxErrorat startup: the file was started with plainnode. Start it withnpx tsx watch server.ts, which maps the.jsimports to your.tsfiles.- Validation always fails after you add the signature check: a global
express.json()still runs first, orparseJsonBodyis missing, soreq.bodyis not the parsed object. Use the route-level stack exactly as shown.
Webhook Validation FAQ
Does Zod validation slow down Express?
Not noticeably for typical webhook payloads. The cost of parsing a JSON object against a schema is small next to network and database time. Only at very high volumes on a small server would you see extra CPU use, and that is a fair price for blocking crashes and bad writes.
How do I get TypeScript types from my Zod schemas?
Use z.infer, as in the UserSignupPayload type in schemas.ts. It turns a schema into a TypeScript type, so you define the shape once and never keep a separate interface in sync by hand. Use the type in your handlers and downstream functions.
Can I use Zod to validate query parameters too?
Yes, write the same kind of middleware for req.query or req.params. This is useful for webhook callback URLs that pass state tokens or IDs in the query string. Remember that query values arrive as strings, so use z.coerce.number() for numeric IDs.
How should I validate nested arrays in webhook payloads?
Use z.array() with a schema for each item. For a billing webhook with line items, define a LineItemSchema first, then add lineItems: z.array(LineItemSchema) to the main schema. Each item is checked, and errors point to the exact index, such as lineItems.2.price.
Next Steps
Your Express server now rejects malformed webhook payloads with a clear 400. Model a schema on each provider’s sample payload, put signature verification in front of it, and send a 2xx quickly once a payload passes. If one valid event has to reach several services, see how to route webhooks to multiple endpoints in Node.js.

