Skip to content
Back to blog
  • Next.js
  • Validation
  • APIs

Validate at the boundary

Server-side schemas and honest response states turn a route handler into a dependable contract instead of a hopeful parser.

5 min read

A browser form is a useful interface, but it is not a security or correctness boundary. A request can be sent without the form, with modified fields or with a content type the UI never produces. The route handler is the first place where the application can make a server-side decision about the shape and meaning of that request. That is why validation belongs at the boundary, before the request reaches persistence or an external service.

Parse, do not just inspect

With a Next.js route handler, Zod can describe the accepted input and return a parsed value. The parsed value is more useful than a collection of ad hoc checks: downstream code receives the contract the schema established, while invalid input gets a deliberate response. The schema should be shaped around what the operation needs, not around every value a client happens to send.

ts
import { NextResponse } from "next/server";
import { z } from "zod";

const contactSchema = z.object({
  name: z.string().trim().min(2).max(80),
  email: z.email(),
  message: z.string().trim().min(20).max(5000),
  website: z.string().max(0).optional(),
});

export async function POST(request: Request) {
  const input = contactSchema.safeParse(await request.json());

  if (!input.success) {
    return NextResponse.json(
      { ok: false, outcome: "invalid" },
      { status: 400 },
    );
  }

  const saved = await saveContactMessage(input.data);
  return NextResponse.json({ ok: true, outcome: saved ? "saved" : "error" });
}

The example is intentionally small. In a production route, parsing is one step in a larger sequence: the handler can apply spam checks and rate limits, persist the message, then attempt a notification. Each step should have an outcome that matches what actually happened. A generic success response after a failed insert makes the API look healthy while losing the user’s message; accepting an empty honeypot value without checking it removes an important signal.

It is worth keeping this sequence visible in the handler instead of hiding it behind a single catch-all helper. A caller needs to know whether it should correct a form, wait and try again, or stop because the server rejected the operation. The server needs the same clarity when it is logging failures. Small, named outcomes make it possible to test those branches without pretending that every failure is equivalent.

Saved is not the same as notified

This portfolio’s contact endpoint follows that distinction. The response vocabulary separates configuration, validation, rate limiting, rejection and internal errors. When a message is saved, notification status is reported separately as sent, failed or not configured. That is a small contract detail with a large effect on trust: the UI can tell a visitor that the message was stored even when an owner notification did not leave the system.

An honest response describes the state the server can prove, not the state the user hoped would happen.

Make invalid states boring

Boundary validation is also a way to keep the rest of the code boring. Once the handler has a parsed name, email and message, the persistence layer does not need to repeat every client assumption. It can still enforce database constraints, because defense in depth is valuable, but it is no longer responsible for interpreting arbitrary JSON. The notification layer receives a saved record or an explicit failure rather than an uncertain object.

  • Validate JSON on the server even when the client already validates it.
  • Trim and constrain user-controlled strings before persistence.
  • Use the parsed value rather than the original untrusted payload.
  • Return status codes and outcome fields that distinguish invalid, rejected, saved and failed work.
  • Keep notification state separate from persistence state.

A response is part of the interface

That contract also gives the client a stable way to recover. It can keep the visitor's message visible after a rejected submission, ask for correction after invalid input, or explain that a saved message is awaiting notification. None of those states needs to be guessed from a generic status code or an empty response body.

The route handler is an interface for the frontend, even though it is not visual. Its response should be designed with the same care as a form: predictable states, clear language and no implication that an unperformed action succeeded. When the server validates at the boundary and reports its real outcome, the client can stay simple and accessible. It only needs to render the contract instead of reconstructing the server’s internal story.

The rule generalises beyond contact forms. File uploads, authentication, webhooks and AI requests all cross a trust boundary. Parse there, persist deliberately and report what is known. The result is not merely safer input handling; it is an API that tells the truth.