惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 【当耐特】
Latest news
Latest news
IT之家
IT之家
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
L
LangChain Blog
腾讯CDC
J
Java Code Geeks
GbyAI
GbyAI
美团技术团队
V
Visual Studio Blog
Apple Machine Learning Research
Apple Machine Learning Research
Recorded Future
Recorded Future
U
Unit 42
Jina AI
Jina AI
月光博客
月光博客
罗磊的独立博客
I
InfoQ
有赞技术团队
有赞技术团队
B
Blog RSS Feed
The Register - Security
The Register - Security
WordPress大学
WordPress大学
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
MongoDB | Blog
MongoDB | Blog
NISL@THU
NISL@THU
S
Security Archives - TechRepublic
雷峰网
雷峰网
O
OpenAI News
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Y
Y Combinator Blog
G
GRAHAM CLULEY
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
L
LINUX DO - 热门话题
H
Help Net Security
www.infosecurity-magazine.com
www.infosecurity-magazine.com
S
Securelist
P
Proofpoint News Feed
C
Cybersecurity and Infrastructure Security Agency CISA
博客园 - 叶小钗
Security Latest
Security Latest
A
About on SuperTechFans
G
Google Developers Blog
T
Troy Hunt's Blog
小众软件
小众软件
H
Hacker News: Front Page
C
Cisco Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
L
LINUX DO - 最新话题
大猫的无限游戏
大猫的无限游戏
Webroot Blog
Webroot Blog

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution Node.js Cluster Mode: Scaling the Event Loop Across CPU Cores Postgres Partial Indexes: Stopping Soft Deletes from Ruining Your Query Performance Request Coalescing with the Singleflight Pattern: Stop Drowning Your Database on Every Cache Miss The Bulkhead Pattern: Why One Slow Endpoint Should Not Drown Your Whole Service Node.js AsyncLocalStorage: End-to-End Request Context Without the Propagation Hell Postgres Deadlocks: Logging the Victim, Reproducing the Race, and Fixing the Lock Order Your Node.js HTTP Client Is the Bottleneck: Connection Pool Tuning That Works Optimistic Locking in Postgres: Stop Losing Data to Race Conditions Postgres Read Replicas: Stop Serving Stale Data to Your Users Cursor Pagination: Why Offset Queries Explode at Scale and How to Fix Them Node.js Worker Threads: 60 Lines That Stop a CSV Upload from Timing Out Every Other Request Reliable Webhook Delivery: Architecture for Outbound HTTP You Can Trust Request Timeouts and Deadline Propagation: Stop the Chain of Slowness Advanced Security Practices in Node.js Graceful Shutdown in Node.js: The 40 Lines That Stop 502s During Deploys Finding Node.js Memory Leaks with Heap Snapshots Idempotency Keys in 30 Lines: Stop Your Webhook From Charging Customers Twice Backpressure In Node.js: The Fix For Slow-Motion Queue Meltdowns Retries Done Right: Jitter, Budgets, and the Stampede You Did Not See Coming The Cache Stampede: Why Your "Just Add Redis" Layer Crashes Postgres at 3 a.m. Postgres SKIP LOCKED: An 80-Line Job Queue You Can Run Without Redis Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right The N+1 Query Problem: We Found 23 In One Codebase And Killed Every One I Tried 5 AI Coding Tools for a Month. Here Is What I Actually Use CI/CD From Zero to Production in 30 Minutes With GitHub Actions Node.js vs Bun vs Deno: Which Runtime Should You Pick in 2025? Kubernetes Resource Requests And Limits: The Numbers That Decide If Your Cluster Is Stable The Three Pillars of Observability Are A Myth: What Actually Matters In Production pnpm Vs npm Vs yarn Vs Bun For Monorepos: Which One Earns The Migration In 2024 JSONB Indexing In Postgres: GIN Vs Expression Indexes, And When Each Is The Right Choice A Code Review Checklist That Ends The Same Three Arguments Every Sprint gRPC Vs REST In 2024: When The Switch Pays For Itself React Suspense For Data Fetching: The Pattern That Replaces Half Your Loading State Code The Five-Stage Rollout: How To Ship A Risky Change Without Holding Your Breath GitHub Actions In A Monorepo: Caching, Path Filters, And Secret Boundaries That Actually Work The Blameless Postmortem That Actually Improves Things: A Template And Six Hard-Won Rules Recursive CTEs In Postgres: How To Query A Tree Without N Round Trips Node.js Streams: When They Actually Help, And When They Just Add Complexity Playwright Vs Cypress In 2024: The Honest Comparison Of Which One Earns The Test Time React Server Components: The Mental Model That Makes The "use client" Boundary Obvious Pod Disruption Budgets: The K8s Object That Keeps Your Service Up During Cluster Maintenance Postgres LISTEN/NOTIFY: The Pub/Sub You Already Have And Are Not Using Chaos Engineering Starter Kit: The Five Drills That Don't Need Netflix-Scale Spec-Driven API Development With OpenAPI: How To Stop Drifting From Your Docs Saga Pattern vs Two-Phase Commit: Distributed Transactions Without The Lies Kubernetes Autoscaling Beyond CPU: The Custom-Metric HPA Pattern That Actually Works Postgres Partitioning For Time-Series: The Boring Setup That Saves Your Database Distributed Locks With Redis: An Honest Look At Redlock And When You Don't Need It HTTP/2 vs HTTP/3: What Actually Changes For Your App, And What Doesn't Image Optimization For The Web In 2023: srcset, AVIF, And The Lighthouse Score You Actually Want Kafka vs RabbitMQ: A Decision Tree That Doesn't Hate You UUID vs Bigint Primary Keys In Postgres: The Index Math That Decides For You Flame Graphs: How To Find The Slow Function In 30 Seconds Without Profiling Theatre Postgres Streaming Vs. Logical Replication: Which One Solves Your Actual Problem ESLint Rules That Earn Their Keep: The Twelve I Enable On Every Project Pre-Commit Hooks That Pay For Themselves: Husky, lint-staged, And The Five Rules That Stick Zero-Downtime Database Migrations: The Six-Step Pattern That Rules Them All Circuit Breakers In Node.js: 50 Lines That Stop A Failing Dependency From Taking Down Your Service Postgres VACUUM Is Not Magic: How Your Hot Table Bloats To 80GB And How To Fix It Kubernetes Liveness And Readiness Probes: The Difference That Causes Half Your Outages Rate Limiting In Production: A Token Bucket In 30 Lines Of Redis The Outbox Pattern: How To Stop Losing Events When Postgres And Kafka Disagree Load Testing With k6: The Three Scenarios That Find Real Bugs (Not Synthetic Numbers) Postgres Row-Level Security For Multi-Tenant Apps: The Pattern That Stops You From Leaking Data Rebase vs. Merge: The Team Policy That Ends The Argument Forever OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident Feature Flags That Pay Rent: The 4 Flag Types And When To Delete Each ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong Connection Pooling Without the Cargo Cult: pgbouncer in 100 Lines of Config JSONB Is Not a Schema: When To Reach For It in Postgres, And When To Stop Bash Strict Mode: The Three Lines That Stop Your Deploy Script From Lying To You
API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database
The Practica · 2026-05-19 · via The Practical Developer

The checkout endpoint had run in production for eight months without a single schema-related incident. Then a partner integration changed their payload format silently. Instead of quantity: 2, they sent quantity: "2". Instead of metadata: null or an object, they sent metadata: undefined. The route handler used req.body.quantity * req.body.price, which in JavaScript evaluates "2" * 19.99 to 39.98 correctly. But the ORM insert mapped metadata: undefined to DEFAULT in SQL, which for that column meant null. A downstream reporting job that expected metadata to be either a valid object or absent entirely choked on the batch insert, threw an unhandled rejection, and the worker restarted in a loop. Two hours of dirty data cleanup. One line of validation would have caught it in 2 milliseconds.

This post is not an introduction to Zod. It is a production-grade validation layer for Express (or Fastify, or Hono) that stops malformed, mistyped, and malicious input before it touches your business logic or your database. We will build the schema, the middleware, the custom refinements, and the error response format that clients actually understand.

Why JSON parsing is not validation

express.json() does one thing: it turns a JSON string into a JavaScript object. It has no opinion on whether userId is a UUID, whether email contains an @, or whether quantity is a positive integer. Worse, every property is implicitly optional from TypeScript’s perspective if you cast the body:

app.post('/orders', async (req, res) => {
  const body = req.body as CreateOrderBody; // TypeScript trusts you. The runtime does not.
  const total = body.quantity * body.price; // NaN if either is a string that is not numeric
});

The as keyword tells TypeScript “I guarantee this shape.” The runtime guarantees nothing. A missing field becomes undefined. A wrong type stays the wrong type. A string where you expected a number stays a string until some arithmetic operation silently coerces it or produces NaN.

The fix is not “add manual if-checks everywhere.” That leads to 400-line route handlers and inconsistent error messages. The fix is a single source of truth at the boundary: a schema that describes exactly what the API accepts, with types, constraints, and transforms, enforced before the handler runs.

The schema: stricter than TypeScript

Here is the Zod schema for a checkout endpoint. It is stricter than the TypeScript interface because it enforces runtime rules that TypeScript cannot express.

import { z } from 'zod';

const OrderItemSchema = z.object({
  sku: z.string().min(1).max(64),
  quantity: z.number().int().positive().max(10_000),
  price: z.number().positive().max(1_000_000),
});

const CreateOrderSchema = z.object({
  userId: z.string().uuid(),
  email: z.string().email().max(254),
  items: z.array(OrderItemSchema).min(1).max(50),
  shippingAddress: z.object({
    line1: z.string().min(1).max(128),
    line2: z.string().max(128).optional(),
    city: z.string().min(1).max(64),
    country: z.string().length(2), // ISO-3166 alpha-2
    postalCode: z.string().min(3).max(16),
  }),
  metadata: z.record(z.string(), z.unknown()).optional(),
  couponCode: z.string().max(32).optional(),
});

type CreateOrderBody = z.infer<typeof CreateOrderSchema>;

Note the difference between the TypeScript type and the Zod schema. The type says quantity is a number. The schema says it is an integer, positive, and no larger than 10,000. The type says userId is a string. The schema says it must be a valid UUID. The type says email is a string. The schema says it must contain an @ and a domain, and fit in 254 characters.

The z.infer<typeof CreateOrderSchema> line is the critical integration point. You never write the TypeScript type by hand. You derive it from the schema. If the schema changes, the type changes automatically. There is no drift between what TypeScript thinks the shape is and what the runtime actually validates.

The middleware: one line per route

The goal is to validate once, early, and fail with a structured error that the client can parse without regex.

import type { Request, Response, NextFunction } from 'express';

function validateBody<T>(schema: z.ZodType<T>) {
  return (req: Request, res: Response, next: NextFunction) => {
    const result = schema.safeParse(req.body);
    if (!result.success) {
      return res.status(400).json({
        error: 'ValidationError',
        message: 'Request body does not match the expected schema',
        details: result.error.issues.map((issue) => ({
          path: issue.path.join('.'),
          code: issue.code,
          message: issue.message,
        })),
      });
    }
    req.body = result.data; // Replace the raw body with the parsed, typed object
    next();
  };
}

The middleware uses safeParse instead of parse so that validation errors do not throw exceptions. It formats Zod’s ZodIssue array into a flat, client-friendly structure. It replaces req.body with the parsed data, which means transforms (like string-to-number coercion) are applied and the handler downstream sees the clean value.

Usage is one line:

app.post('/orders', validateBody(CreateOrderSchema), async (req, res) => {
  const body: CreateOrderBody = req.body; // Fully typed, fully validated
  // ... business logic
});

If the partner integration sends quantity: "2", the middleware responds with a 400 before the handler runs. The error details tell the client exactly which field failed and why:

{
  "error": "ValidationError",
  "message": "Request body does not match the expected schema",
  "details": [
    { "path": "items.0.quantity", "code": "invalid_type", "message": "Expected number, received string" }
  ]
}

Query and parameter validation

Body validation is the obvious place to start, but most injection and routing bugs come from query strings and URL parameters. They are strings by definition, and developers often parse them with parseInt(req.query.page) which returns NaN on bad input and does not surface an error to the client.

const ListOrdersQuerySchema = z.object({
  page: z.coerce.number().int().positive().default(1),
  limit: z.coerce.number().int().positive().max(100).default(20),
  status: z.enum(['pending', 'paid', 'shipped', 'cancelled']).optional(),
  sort: z.enum(['createdAt', 'total']).default('createdAt'),
  userId: z.string().uuid().optional(),
});

The z.coerce.number() transform is the key detail. It takes whatever string arrives from the query parameter and attempts to coerce it to a number. If the client sends ?page=abc, coercion fails and Zod reports invalid_type with a 400. If they send ?page=2, they get the number 2. The default values mean the handler never sees undefined for optional fields; it sees 1 and 20.

A similar helper for query validation:

function validateQuery<T>(schema: z.ZodType<T>) {
  return (req: Request, res: Response, next: NextFunction) => {
    const result = schema.safeParse(req.query);
    if (!result.success) {
      return res.status(400).json({
        error: 'ValidationError',
        message: 'Query parameters do not match the expected schema',
        details: result.error.issues.map((issue) => ({
          path: issue.path.join('.'),
          code: issue.code,
          message: issue.message,
        })),
      });
    }
    req.query = result.data as any;
    next();
  };
}

Custom refinements for business logic

Zod’s built-in checks cover type, length, and format. Business rules need custom refinements: a coupon that is only valid on Tuesdays, a shipping address that must be domestic for same-day delivery, an order total that cannot exceed $50,000.

const BusinessOrderSchema = CreateOrderSchema.superRefine((data, ctx) => {
  const total = data.items.reduce((sum, item) => sum + item.quantity * item.price, 0);

  if (total > 50_000) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: `Order total ${total} exceeds maximum allowed value of 50000`,
      path: ['items'],
    });
  }

  const domesticCountries = ['US', 'CA', 'MX'];
  if (data.couponCode?.startsWith('SAME_DAY') && !domesticCountries.includes(data.shippingAddress.country)) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: 'Same-day coupon is only valid for domestic shipping',
      path: ['couponCode'],
    });
  }
});

superRefine runs after the base schema passes, so you know items is an array of valid objects before you compute the total. The ctx.addIssue API attaches errors to specific paths, so the client sees items or couponCode as the failing field, not a generic top-level error.

This is where validation becomes more than type safety. It is business-rule enforcement at the boundary. The database never sees an order over $50,000 because the API rejects it in the middleware layer.

A reusable factory for all routes

Copy-pasting validateBody, validateQuery, and validateParams into every route file gets old. A small factory cleans it up:

import { z } from 'zod';
import type { Request, Response, NextFunction } from 'express';

export function createValidator<TBody, TQuery, TParams>(schemas: {
  body?: z.ZodType<TBody>;
  query?: z.ZodType<TQuery>;
  params?: z.ZodType<TParams>;
}) {
  return (req: Request, res: Response, next: NextFunction) => {
    const errors: Array<{ path: string; code: string; message: string }> = [];

    if (schemas.body) {
      const result = schemas.body.safeParse(req.body);
      if (!result.success) {
        errors.push(...result.error.issues.map((i) => ({
          path: `body.${i.path.join('.')}`,
          code: i.code,
          message: i.message,
        })));
      } else {
        req.body = result.data;
      }
    }

    if (schemas.query) {
      const result = schemas.query.safeParse(req.query);
      if (!result.success) {
        errors.push(...result.error.issues.map((i) => ({
          path: `query.${i.path.join('.')}`,
          code: i.code,
          message: i.message,
        })));
      } else {
        req.query = result.data as any;
      }
    }

    if (schemas.params) {
      const result = schemas.params.safeParse(req.params);
      if (!result.success) {
        errors.push(...result.error.issues.map((i) => ({
          path: `params.${i.path.join('.')}`,
          code: i.code,
          message: i.message,
        })));
      } else {
        req.params = result.data as any;
      }
    }

    if (errors.length > 0) {
      return res.status(400).json({
        error: 'ValidationError',
        message: 'Request does not match the expected schema',
        details: errors,
      });
    }

    next();
  };
}

Now a route definition reads like a schema document:

app.post(
  '/orders',
  createValidator({ body: BusinessOrderSchema }),
  async (req, res) => {
    const body = req.body as z.infer<typeof BusinessOrderSchema>;
    const order = await createOrder(body);
    res.status(201).json(order);
  }
);

app.get(
  '/orders',
  createValidator({ query: ListOrdersQuerySchema }),
  async (req, res) => {
    const query = req.query as z.infer<typeof ListOrdersQuerySchema>;
    const orders = await listOrders(query);
    res.json(orders);
  }
);

Performance: validation is not free, but it is cheap

A common objection is “we cannot afford to validate every request.” In practice, Zod validation of a typical JSON body takes 0.1 to 0.5 milliseconds on a modern CPU. Compare that to a single Postgres round-trip at 2 milliseconds, a Redis call at 1 millisecond, or the time it takes to JSON.stringify a response. Validation is the cheapest operation in the request path, and it saves the most expensive ones (database writes, downstream calls, error remediation) from processing garbage.

If you are truly at the scale where 0.2ms matters, Zod supports precompilation. The zod-to-json-schema package can compile a Zod schema to a JSON Schema, and ajv can validate against it at roughly twice the speed. But measure first. Most APIs will never notice the difference.

The production checklist

Before you ship the validation layer, verify these five things.

  1. All public routes have a schema. Internal routes and health checks can skip it, but any route that accepts a body, query, or params from a client needs validation. Audit your router file; if a route is missing createValidator, that is a bug.

  2. Error responses are documented. Clients need to know that a 400 response contains { error: 'ValidationError', details: [...] }. Put it in your API documentation. If you use OpenAPI, generate the error response schema from the Zod types.

  3. Do not leak internal structure. Never return result.error.message directly from Zod. It can contain internal schema details. Always map to a controlled format like the details array above.

  4. Log validation failures at warn level. A spike in 400s is often the first sign of a broken client integration or an attempted injection attack. Log the route, the IP, and the error codes (not the full payload if it contains PII).

  5. Keep schemas close to the route. Do not define all schemas in a single schemas.ts file three directories away from the handler. Colocate the schema with the route file, or in a schemas.ts sibling file in the same directory. When the route changes, the schema is right there.

The takeaway

TypeScript is a compile-time guard. It disappears at runtime. express.json() is a transport parser. It has no opinion on shape. The gap between them is where bad input becomes data corruption, NaN bugs, and two-hour cleanup sessions.

Zod closes that gap with a schema that is both the TypeScript type and the runtime validator. One source of truth. One line of middleware per route. Custom refinements for business rules. Structured errors that clients parse without guessing.

Start with the body schemas on your write endpoints. Add query validation next. Add refinements for the invariants that should never reach the database. The first malformed payload that gets a 400 instead of a corrupted row will pay for the entire migration.

A note from Yojji

The kind of defensive API design that validates every input at the boundary, formats errors for client integrations, and keeps business rules out of the database layer is exactly the kind of engineering rigor Yojji’s teams bring to the products they build.

Yojji is an international custom software development company founded in 2016, with teams across Europe, the US, and the UK. They specialize in the JavaScript ecosystem (React, Node.js, TypeScript), cloud platforms (AWS, Azure, GCP), and full-cycle product engineering, including the API architecture and validation patterns that keep production systems stable when client behavior changes.