Building REST APIs with Proper Validation and Error Handling
Validate once at the boundary, throw typed errors, and return one consistent error shape everywhere.
- rest
- validation
- zod
- express
- error-handling
On this page ยท 16 sections
Most API bugs that reach production are boundary bugs: a missing field that becomes undefined three functions deep, a string where a number was expected, an error that returns a 200 with an HTML stack trace. Two habits remove most of them: validate everything at the edge and return one consistent error shape from everywhere. This guide builds both in an Express API with TypeScript and Zod.
It targets Express 5, which forwards errors from async handlers automatically, and Zod 4. Notes for Express 4 are included where behavior differs.
The architecture
- 1Validate
body, query, params: 400 or 422 on failure
- 2Route handler
typed, trusted data
- 3Service layer
business rules, throws AppError
- 4Error handler
one place maps errors to responses
Every layer has one job. Validation never contains business rules, handlers never format errors by hand, and the error handler is the only place that decides status codes and response shapes.
Common mistakes
- Validating inside handlers with scattered
ifstatements, so some routes forget. - Trusting
req.bodytypes (as User) without checking them. - Returning different error shapes from different routes.
- Using
200for failures, or500for client mistakes. - Leaking stack traces, SQL errors or file paths in responses.
- Unbounded pagination (
limit=1000000). - Forgetting a handler for unknown routes (404) and for malformed JSON.
Setup
npm install express zodnpm install -D typescript @types/express @types/node jest ts-jest supertest @types/jest @types/supertestStep 1: Define an error type
Throw typed errors from anywhere. The error handler turns them into responses.
// src/errors.tsexport class AppError extends Error { constructor( public readonly status: number, public readonly code: string, message: string, public readonly details?: unknown, ) { super(message); this.name = "AppError"; } static badRequest(message: string, details?: unknown) { return new AppError(400, "BAD_REQUEST", message, details); } static unauthorized(message = "Authentication required") { return new AppError(401, "UNAUTHORIZED", message); } static forbidden(message = "You do not have access to this resource") { return new AppError(403, "FORBIDDEN", message); } static notFound(resource = "Resource") { return new AppError(404, "NOT_FOUND", `${resource} not found`); } static conflict(message: string) { return new AppError(409, "CONFLICT", message); }}The code is for programs (clients can switch on it); the message is for people.
Step 2: Write schemas
A schema describes the data and, through z.infer, its TypeScript type:
// src/users/user.schemas.tsimport { z } from "zod";export const createUserBody = z.object({ email: z.email(), name: z.string().trim().min(1).max(100), password: z.string().min(8).max(128), role: z.enum(["user", "admin"]).default("user"),});export const userIdParams = z.object({ id: z.uuid(),});export const listUsersQuery = z.object({ page: z.coerce.number().int().min(1).default(1), limit: z.coerce.number().int().min(1).max(100).default(20), search: z.string().trim().max(100).optional(),});export type CreateUserBody = z.infer<typeof createUserBody>;export type ListUsersQuery = z.infer<typeof listUsersQuery>;Notice the details: limit has a maximum, query strings are coerced from text to numbers, and strings are trimmed. (In Zod 3 the string helpers are written z.string().email() and z.string().uuid().)
Step 3: A reusable validation middleware
Validate each part of the request and attach the parsed, typed result. In Express 5, req.query is a read-only getter, so do not assign to it. Store parsed values on a dedicated property instead:
// src/middleware/validate.tsimport type { NextFunction, Request, Response } from "express";import { ZodError, type ZodType } from "zod";import { AppError } from "../errors";interface Schemas { body?: ZodType; query?: ZodType; params?: ZodType;}declare module "express-serve-static-core" { interface Request { validated?: { body?: unknown; query?: unknown; params?: unknown }; }}export const validate = (schemas: Schemas) => (req: Request, _res: Response, next: NextFunction) => { try { req.validated = { body: schemas.body?.parse(req.body), query: schemas.query?.parse(req.query), params: schemas.params?.parse(req.params), }; next(); } catch (err) { if (err instanceof ZodError) { return next( new AppError(422, "VALIDATION_ERROR", "Request validation failed", formatZodIssues(err)), ); } next(err); } };function formatZodIssues(err: ZodError) { return err.issues.map((i) => ({ path: i.path.join("."), message: i.message, }));}A tiny helper keeps handlers typed without casts everywhere:
// src/middleware/validated.tsimport type { Request } from "express";import type { z, ZodType } from "zod";export const validatedBody = <T extends ZodType>(req: Request, _schema: T) => req.validated!.body as z.infer<T>;export const validatedQuery = <T extends ZodType>(req: Request, _schema: T) => req.validated!.query as z.infer<T>;export const validatedParams = <T extends ZodType>(req: Request, _schema: T) => req.validated!.params as z.infer<T>;Step 4: Routes and handlers
// src/users/user.routes.tsimport { Router } from "express";import { validate } from "../middleware/validate";import { validatedBody, validatedParams, validatedQuery } from "../middleware/validated";import { createUserBody, listUsersQuery, userIdParams } from "./user.schemas";import { UserService } from "./user.service";export function userRoutes(service: UserService) { const router = Router(); router.get("/", validate({ query: listUsersQuery }), async (req, res) => { const query = validatedQuery(req, listUsersQuery); const result = await service.list(query); res.json(result); }); router.get("/:id", validate({ params: userIdParams }), async (req, res) => { const { id } = validatedParams(req, userIdParams); res.json(await service.getById(id)); // throws AppError.notFound if missing }); router.post("/", validate({ body: createUserBody }), async (req, res) => { const body = validatedBody(req, createUserBody); const user = await service.create(body); res.status(201).location(`/users/${user.id}`).json(user); }); return router;}The handlers contain no validation and no error formatting. In Express 5, a rejected promise from an async handler is passed to the error middleware automatically. In Express 4 wrap handlers so rejections are forwarded:
export const asyncHandler = (fn: (req: Request, res: Response, next: NextFunction) => Promise<unknown>) => (req: Request, res: Response, next: NextFunction) => void fn(req, res, next).catch(next);Step 5: Business errors in the service layer
Throw typed errors where the rule is enforced:
// src/users/user.service.tsimport { AppError } from "../errors";import type { CreateUserBody, ListUsersQuery } from "./user.schemas";export class UserService { constructor(private repo: UserRepository) {} async getById(id: string) { const user = await this.repo.findById(id); if (!user) throw AppError.notFound("User"); return user; } async create(input: CreateUserBody) { if (await this.repo.findByEmail(input.email)) { throw AppError.conflict("A user with this email already exists"); } return this.repo.insert(input); // hash the password here before storing } async list(query: ListUsersQuery) { const { page, limit, search } = query; const [items, total] = await this.repo.list({ offset: (page - 1) * limit, limit, search }); return { items, page, limit, total, totalPages: Math.ceil(total / limit) }; }}When two requests race to create the same email, the check above is not enough on its own. Back it with a unique index in the database and translate the database's unique-violation error into the same conflict error.
Step 6: One error handler
All error-to-response mapping lives here. Define the response shape once:
// src/middleware/error-handler.tsimport type { NextFunction, Request, Response } from "express";import { AppError } from "../errors";interface ErrorBody { error: { code: string; message: string; details?: unknown; requestId?: string; };}export function notFoundHandler(_req: Request, _res: Response, next: NextFunction) { next(AppError.notFound("Route"));}export function errorHandler(err: unknown, req: Request, res: Response, _next: NextFunction) { const requestId = req.header("x-request-id"); // Malformed JSON from express.json() if (err instanceof SyntaxError && "body" in err) { return res.status(400).json(body("BAD_JSON", "Request body is not valid JSON", undefined, requestId)); } if (err instanceof AppError) { return res.status(err.status).json(body(err.code, err.message, err.details, requestId)); } // Unexpected: log everything, tell the client almost nothing. console.error({ requestId, err }); res.status(500).json(body("INTERNAL_ERROR", "Something went wrong", undefined, requestId));}const body = (code: string, message: string, details?: unknown, requestId?: string): ErrorBody => ({ error: { code, message, ...(details ? { details } : {}), ...(requestId ? { requestId } : {}) },});Wire everything together. Order matters: parsers first, routes next, then the 404 handler, then the error handler last.
// src/app.tsimport express from "express";import { errorHandler, notFoundHandler } from "./middleware/error-handler";import { userRoutes } from "./users/user.routes";export function createApp(deps: { userService: import("./users/user.service").UserService }) { const app = express(); app.use(express.json({ limit: "100kb" })); app.get("/health", (_req, res) => res.json({ status: "ok" })); app.use("/users", userRoutes(deps.userService)); app.use(notFoundHandler); app.use(errorHandler); return app;}A failed validation now looks the same on every route:
{ "error": { "code": "VALIDATION_ERROR", "message": "Request validation failed", "details": [ { "path": "email", "message": "Invalid email address" }, { "path": "password", "message": "Too small: expected string to have >=8 characters" } ] }}Clients can show field errors next to inputs and branch on code, without parsing prose.
Status code cheat sheet
| Situation | Status |
|---|---|
| Created a resource | 201 (plus a Location header) |
| Success with no body | 204 |
| Malformed JSON | 400 |
| Valid JSON, invalid fields | 422 (or 400, but be consistent) |
| Not signed in | 401 |
| Signed in, not allowed | 403 |
| Missing resource or unknown route | 404 |
| Duplicate or conflicting state | 409 |
| Too many requests | 429 |
| Unexpected server failure | 500 |
Security considerations
- Never echo raw database or library error messages to clients.
- Limit body size (
express.json({ limit })) and string lengths in schemas. - Strip or reject unknown fields.
z.objectremoves unknown keys by default; use.strict()when you want to reject them. - Return the same error for "user not found" and "wrong password" on login endpoints.
- Do not log passwords, tokens or full request bodies that may contain secrets.
Performance considerations
Schema parsing is fast, but avoid re-creating schemas inside request handlers. Define them once at module level, as above. For large payloads, set sensible size limits so an attacker cannot make you parse megabytes of JSON.
Testing
Test the contract, not the internals:
// src/users/user.routes.test.tsimport request from "supertest";import { createApp } from "../app";import { fakeUserService } from "../test/fakes";const app = createApp({ userService: fakeUserService() });describe("POST /users", () => { it("returns 422 with field details for invalid input", async () => { const res = await request(app).post("/users").send({ email: "nope", password: "short" }); expect(res.status).toBe(422); expect(res.body.error.code).toBe("VALIDATION_ERROR"); expect(res.body.error.details).toEqual( expect.arrayContaining([expect.objectContaining({ path: "email" })]), ); }); it("returns 400 for malformed JSON", async () => { const res = await request(app).post("/users").set("Content-Type", "application/json").send("{bad"); expect(res.status).toBe(400); expect(res.body.error.code).toBe("BAD_JSON"); }); it("returns 201 and a Location header on success", async () => { const res = await request(app).post("/users").send({ email: "a@example.com", name: "Ada", password: "correct-horse" }); expect(res.status).toBe(201); expect(res.headers.location).toMatch(/^\/users\//); });});describe("unknown routes", () => { it("returns the standard error shape", async () => { const res = await request(app).get("/nope"); expect(res.status).toBe(404); expect(res.body.error.code).toBe("NOT_FOUND"); });});Add a test that throws an unexpected Error from a service and asserts the response is the generic 500 without internal details.
Troubleshooting
| Symptom | Likely cause |
|---|---|
req.body is undefined | express.json() registered after the route, or missing Content-Type: application/json |
Cannot set property query of #<IncomingMessage> | Assigning to req.query in Express 5; use a separate property |
| Async errors crash the process | Express 4 without an async wrapper |
| Error handler never runs | It has fewer than four parameters, or is registered before the routes |
| Numbers arrive as strings | Query/params need z.coerce |
| 500 for a client mistake | A thrown plain Error instead of an AppError |
Best practices
- Validate all three sources: body, query and params.
- Keep schemas next to the feature that owns them and infer types from them.
- Throw typed errors and handle them in one place.
- Use one error shape and one validation status code across the API.
- Log with a request id and return that id to the client so you can find the failure later.
- Document the error format in your OpenAPI spec so clients can rely on it.
Conclusion
Validation at the edge and a single error pipeline turn an API from a pile of special cases into a predictable system. Handlers receive typed, trusted data; services throw meaningful errors; clients always get the same shape back. Once this skeleton is in place, adding a new endpoint is mostly writing a schema and a service method.
Frequently asked questions
+Where should request validation happen in an Express API?
At the edge, in middleware that runs before the handler. Validate body, query and params against a schema, reject bad input with a 400 or 422, and let handlers work with typed, trusted data.
+Why use Zod instead of manual checks?
A schema is both runtime validation and a TypeScript type. With z.infer you get the type for free, so the validated data and its static type can never drift apart.
+Do I still need try/catch in async Express handlers?
Not in Express 5, which forwards rejected promises from async handlers to the error-handling middleware. In Express 4 you need a wrapper or a try/catch that calls next(err).
+Should validation errors return 400 or 422?
Both are used. 400 means the request is malformed; 422 means the request was well-formed but semantically invalid. Pick one convention and apply it consistently across the API.
+What should an error response look like?
A consistent JSON shape with a stable machine-readable code, a human-readable message and optional field-level details. Many APIs follow the Problem Details format (RFC 9457).
+How do I avoid leaking internal errors to clients?
Map known errors to specific status codes and messages, log the full error server-side, and return a generic message for anything unexpected.
+How do I validate query parameters that arrive as strings?
Use coercion in the schema, for example z.coerce.number() for page and limit, with sensible defaults and maximums so clients cannot request unbounded results.