Back to blog
November 14, 2026•25 views

TypeScript Type Guards for Next.js: Surviving Unknown API Responses Safely

TypeScriptNext.jsType GuardsAPI ValidationReactZodApp Router
TypeScript Type Guards for Next.js: Surviving Unknown API Responses Safely

Every Next.js app I have shipped in the last two years talks to something it does not control. A Stripe webhook. A partner CRM. A Django service a client's old agency left behind. A public API that returns a 200 with {"error": "something broke"} in the body. And every one of those endpoints will eventually send you a shape your TypeScript types never anticipated.

Here is the uncomfortable truth most tutorials skip: TypeScript types vanish at build time. When your Next.js server component does const data = await res.json(), the compiler has no idea what came back. If you typed it as User, you lied to the compiler, and it believed you. TypeScript type guards are how you stop lying.

This is the guide I wish existed when I started wiring external data into App Router route handlers. We will cover how type guards actually work, where they earn their keep in a Next.js codebase, and the pitfalls that bite experienced developers too.

What a TypeScript type guard really is

A type guard is a runtime check that tells the TypeScript compiler to narrow a value from something broad (like unknown or a union) down to something specific inside a conditional block. The official TypeScript handbook on narrowing is the canonical reference if you want the full picture.

The simplest form is built in:

function printLength(value: string | string[]) {
  if (typeof value === "string") {
    // value is string here
    return value.length;
  }
  // value is string[] here
  return value.length;
}

That is fine for primitives. The power move is the user-defined type guard, a function whose return type is a type predicate: value is SomeType. See the handbook section on user-defined type guards for the formal rules.

type User = {
  id: string;
  email: string;
  name: string;
};

function isUser(value: unknown): value is User {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    typeof (value as User).id === "string" &&
    typeof (value as User).email === "string" &&
    typeof (value as User).name === "string"
  );
}

Now if (isUser(data)) narrows data from unknown to User for the rest of the block. If it returns false, TypeScript knows the type is not User in the else branch (though with unknown that is less useful).

A cleaner version avoids the casts inside the guard by using a small helper:

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

function isUser(value: unknown): value is User {
  if (!isRecord(value)) return false;
  return (
    typeof value.id === "string" &&
    typeof value.email === "string" &&
    typeof value.name === "string"
  );
}

No as casts. The compiler follows the narrowing inside isRecord. This pattern scales beautifully once you start composing guards.

Built-in type guards you should reach for first

Before writing custom predicates, know what TypeScript narrows for free.

Check Narrows to Notes
typeof x === "string" string Works for all primitives except null
Array.isArray(x) unknown[] Best way to prove something is an array
x instanceof Date Date Fails across realms, but fine inside one runtime
"key" in x object with that key Only useful on objects, not primitives
x === null / x !== null removes null Essential after typeof x === "object"
x.kind === "error" matching union member The backbone of discriminated unions

The typeof x === "object" trap deserves a callout: typeof null is "object". If you forget the null check, your guard will happily accept null and crash on property access three lines later. I have reviewed this exact bug in production code more than once.

Where type guards matter in Next.js (App Router)

The App Router gives you several boundaries where data crosses from "untyped reality" into "typed application code." These are the seams worth guarding.

1. fetch responses in server components

fetch returns any from res.json(). In a server component, that data flows straight into your JSX. A guard here prevents a runtime crash on the page.

// app/users/[id]/page.tsx
import { notFound } from "next/navigation";
import { isUser } from "@/lib/guards";

export default async function UserPage({ params }: { params: { id: string } }) {
  const res = await fetch(`https://api.example.com/users/${params.id}`, {
    next: { revalidate: 60 },
  });

  if (!res.ok) {
    if (res.status === 404) notFound();
    throw new Error(`Upstream failed: ${res.status}`);
  }

  const data: unknown = await res.json();

  if (!isUser(data)) {
    // Fail loudly: the contract broke, do not render garbage
    throw new Error("Unexpected user payload shape");
  }

  return <h1>{data.name}</h1>;
}

Note the explicit const data: unknown. That annotation is doing real work. It stops TypeScript from inferring any and forces you to narrow before use. If you are still getting your head around how server components stream and render, my guide to RSC streaming, Suspense, and SEO is a good companion read.

Version note: In Next.js 15, params and searchParams are asynchronous, they are now Promises that you await. The example above reflects the Next.js 13/14 synchronous signature. On Next.js 15+, type the prop as params: Promise<{ id: string }> and await params before use. See the Next.js upgrade guide for details.

2. Route handlers (app/api/*/route.ts)

Your own API routes are also a boundary. The Request body is unknown. Guard it before touching it.

// app/api/subscribe/route.ts
import { NextResponse } from "next/server";
import { isRecord } from "@/lib/guards";

type SubscribeBody = { email: string; source?: string };

function isSubscribeBody(value: unknown): value is SubscribeBody {
  if (!isRecord(value)) return false;
  if (typeof value.email !== "string") return false;
  if (value.source !== undefined && typeof value.source !== "string") return false;
  return value.email.includes("@");
}

export async function POST(request: Request) {
  const body: unknown = await request.json();

  if (!isSubscribeBody(body)) {
    return NextResponse.json({ error: "Invalid body" }, { status: 400 });
  }

  // body is fully typed now
  await saveSubscriber(body.email, body.source);
  return NextResponse.json({ ok: true });
}

3. Server actions

Server actions accept arbitrary client input. Treat the FormData or argument the same way: as unknown until proven otherwise.

"use server";

import { isRecord } from "@/lib/guards";

export async function createPost(input: unknown) {
  if (!isRecord(input)) {
    return { ok: false, error: "Malformed input" } as const;
  }
  if (typeof input.title !== "string" || input.title.length < 3) {
    return { ok: false, error: "Title too short" } as const;
  }
  // ...
  return { ok: true, id: "123" } as const;
}

4. searchParams and route params

In Next.js, searchParams values are string | string[] | undefined. A guard keeps your filtering logic honest.

function isSortOrder(value: unknown): value is "asc" | "desc" {
  return value === "asc" || value === "desc";
}

export default function Page({
  searchParams,
}: {
  searchParams: { sort?: string | string[] };
}) {
  const sort = isSortOrder(searchParams.sort) ? searchParams.sort : "asc";
  // sort is "asc" | "desc" now, no casts
}

Discriminated unions for action state

If you use useActionState (formerly useFormState), guards and discriminated unions pair beautifully. This is one of the cleanest patterns I use for form handling in the App Router. useActionState is documented in the React reference.

type ActionState =
  | { status: "idle" }
  | { status: "error"; message: string }
  | { status: "success"; id: string };

function isActionError(state: ActionState): state is Extract<ActionState, { status: "error" }> {
  return state.status === "error";
}

In the component, if (isActionError(state)) gives you state.message without a nullish dance. The Extract utility type keeps the predicate precise as the union grows.

Type guards vs Zod: when to drop the hand-rolled predicate

I reach for custom guards for small, stable shapes. I reach for Zod when the shape is large, nested, or shared across services. Here is my honest comparison after shipping both.

Concern Hand-rolled type guard Zod schema
Bundle size Zero extra bytes Roughly 12-14kb gzipped (tree-shakeable; exact size varies by version)
Nested objects Tedious, error-prone Declarative, composable
Error messages You write them Automatic and detailed
Transforms/coercion Manual Built in (z.coerce, .transform)
Type inference You write the type AND the guard Single source of truth
Best fit Small DTOs, quick checks, edge cases Public APIs, form validation, complex payloads
Learning curve Low Moderate

A hybrid works well: use Zod at the outermost boundary (the fetch response) and derive the type, then use small guards for internal logic.

import { z } from "zod";

const UserSchema = z.object({
  id: z.string(),
  email: z.string().email(),
  name: z.string(),
});

export type User = z.infer<typeof UserSchema>;

const parsed = UserSchema.safeParse(data);
if (!parsed.success) {
  throw new Error("Invalid user payload");
}
const user: User = parsed.data;

Version note: In Zod 4, z.string().email() is deprecated in favor of the top-level z.email(). Both work for now, but new code should prefer z.email(). See the Zod 4 changelog.

Where does is-kit fit?

is-kit (and similar micro-libraries) gives you a set of ready-made predicates (isString, isNumber, isObject, isArray) so you do not rewrite the same typeof checks in every file. They are handy for composing guards without pulling in Zod. My take: worth it for teams that write many small guards; overkill for a single API integration. The tradeoff is one more dependency versus a hundred lines of boilerplate you would otherwise maintain.

Pitfalls that quietly break type safety

These are the ones I see in real code reviews, not textbook examples.

  • Type assertions as an escape hatch. const data = (await res.json()) as User compiles fine and gives you zero safety. If you must cast, cast to unknown first, then guard.
  • Forgetting null after typeof === "object". Already covered, but it is the number one bug.
  • Losing narrowing across await. Narrowing does not survive an await boundary if the variable can be reassigned. Capture the narrowed value in a const before awaiting.
  • Guards that return true too eagerly. A guard that only checks one property will pass malformed payloads. Check every required field.
  • Assuming the API contract. Endpoints change. A guard turns a silent data corruption into a loud, catchable error.
  • any leaking through res.json(). Always annotate as unknown.
// Unsafe
const user = (await res.json()) as User;

// Safer
const raw: unknown = await res.json();
if (!isUser(raw)) throw new Error("Bad payload");
const user = raw; // narrowed to User

The satisfies operator is also worth knowing. It validates an object literal against a type without widening it, which is great for config objects and constant maps. It does not replace runtime guards, but it catches mistakes at compile time. The TypeScript 4.9 release notes introduced it.

One adjacent risk worth flagging: if you are letting AI coding assistants generate imports and types, they sometimes invent packages that do not exist. I keep a short CI verification checklist for hallucinated dependencies that pairs well with the boundary discipline in this post.

A small library of reusable guards

Once you write a few, factor them into lib/guards.ts. A minimal starter:

export function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

export function isString(value: unknown): value is string {
  return typeof value === "string";
}

export function isNonEmptyString(value: unknown): value is string {
  return isString(value) && value.trim().length > 0;
}

export function isArrayOf<T>(
  value: unknown,
  guard: (item: unknown) => item is T
): value is T[] {
  return Array.isArray(value) && value.every(guard);
}

That generic isArrayOf is the workhorse. isArrayOf(data.items, isUser) narrows data.items to User[] in one line. Compose guards like Lego bricks and your boundary code stays readable.

If your app also exposes tools to AI agents, the same discipline applies to tool schemas: they drift, and unvalidated inputs break automation. My post on versioning and testing AI agent tool definitions shows how to keep those contracts honest.

Wrapping up

TypeScript type guards are not glamorous. They are three or four lines of defensive code that turn a mysterious production crash into a clear, catchable error. In a Next.js app that touches external APIs, server actions, and user-supplied params, they are the difference between trusting your types and merely hoping.

Start small: add an isRecord helper, annotate your next res.json() as unknown, and write one guard for the shape you care about most. You will feel the difference the first time an upstream service changes its contract and your app fails loudly instead of silently.

If you are building a Next.js product and want the boundary layers done right from day one, I help teams ship type-safe, automation-ready applications. You can reach out through the contact page on this site. I read every message.

Frequently asked questions

Do I need type guards if I already validate everything with Zod?

No, Zod's safeParse already narrows the type for you. But small hand-rolled predicates still earn their place for searchParams, discriminated union state in useActionState, and quick internal checks where a full schema is overkill.

Do type guards work the same in client components as in server components?

Yes. Type guards are plain runtime JavaScript functions, so they behave identically. The only thing to watch is that they run in the browser, so keep them free of server-only imports and heavy dependencies.

Why should I annotate `res.json()` as `unknown` when TypeScript already infers `any`?

any silently disables type checking for everything downstream. unknown forces you to narrow the value with a guard before using it, which is exactly the safety you want at a boundary. It is a one-word change with a large payoff.

Can I combine type guards with Next.js fetch caching and revalidation?

Absolutely. Guards run after the fetch resolves, so next: { revalidate } and cache settings work normally. The guard simply validates the payload that came back, regardless of whether it was cached or fresh.

Share this post

Native Web Share is available on mobile, so that share sheet includes Instagram and any other app you have installed.

Let's Connect

Get In Touch

Let's build something premium together.

Contact info

Follow me
Chat on WhatsApp