TypeScript in the App Router: Params and APIs
TypeScript in a Next.js project earns its keep at the boundaries â the places where data enters the application from a URL, a form, a database, or a third-party API. Inside a component tree the compiler can help, but it cannot help with a query string a user typed or a JSON body a script posted. A Next.js codebase that is type-safe everywhere except its boundaries is a codebase that will crash at runtime on the first hostile input.
This lesson focuses on those boundaries: the configuration that makes the compiler strict, the shape of dynamic parameters in the App Router, runtime validation with Zod, typed route handlers, and the traps that catch almost every team that migrates.
Prerequisites
- !Basic TypeScript syntax and interfaces
- !The App Router file conventions
- !A Next.js project you can run tsc against
What You'll Learn
- 1Configure strict compiler settings that catch real bugs
- 2Type awaited route params and search params correctly
- 3Validate request bodies with schemas and infer types from them
- 4Recognise the App Router patterns that silently defeat type safety
Getting the configuration right once
A default init gives you a working compiler, not a demanding one. The settings that matter are the ones that remove escape hatches: strict mode bans implicit undefined, no implicit any stops untyped parameters from sliding through, and the strictness flags around class fields and unchecked index access decide whether a missing key is a compile error or a surprise at runtime.
// tsconfig.json â the parts that change daily results
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"plugins": [{ "name": "next" }],
"paths": { "@/*": ["./*"] }
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
Two details are easy to miss. The include list must cover the generated route types that Next.js writes during development, otherwise the compiler validates against a stale snapshot of your routes. And the path alias has to be declared in both the compiler options and the bundler configuration â a mismatch produces module-not-found errors that look like missing dependencies but are really two competing resolution rules.
Typing dynamic params and search params
Dynamic segments reach your page as parameters that must be read before they are usable, and in recent App Router versions they arrive as Promises that the component awaits. Components are async, so awaiting is natural, but forgetting it is the single most common typing error after migration: you get an object where a string was expected, and every property access on it fails to compile.
// app/blog/[slug]/page.tsx
type PageProps = {
params: Promise<{ slug: string }>;
searchParams: Promise<{ page?: string; tag?: string }>;
};
export async function generateMetadata({ params }: PageProps) {
const { slug } = await params;
const post = await getPost(slug);
return {
title: post ? post.title : 'Post not found',
description: post ? post.excerpt : undefined,
};
}
export default async function BlogPost({ params, searchParams }: PageProps) {
const { slug } = await params;
const { page, tag } = await searchParams;
const pageNumber = Number.parseInt(page || '1', 10);
const safePage = Number.isNaN(pageNumber) || pageNumber < 1 ? 1 : pageNumber;
const post = await getPost(slug, { page: safePage, tag });
if (!post) return <p>No post matches {slug}.</p>;
return (
<article>
<h1>{post.title}</h1>
<p>{post.body}</p>
</article>
);
}
Notice the parsing discipline: the type system says a page value is a string, not that it is a valid integer. Treat every search parameter as hostile text, coerce it with a checked conversion, and fall back to a default. Repeated keys can also arrive as a list rather than a single value, so normalise early instead of spreading the assumption across five files.
Validating at the boundary with Zod
Once a value crosses from the network into your domain, you want one type that describes it â and a schema that produces that type rather than a handwritten interface that drifts away from it. A schema-first boundary gives you a runtime check and a compile-time type from the same declaration.
// lib/schemas/post.ts
import { z } from 'zod';
export const CreatePostSchema = z.object({
title: z.string().trim().min(1).max(200),
body: z.string().min(1).max(20000),
tags: z.array(z.string().trim().max(30)).max(10).default([]),
publishAt: z.coerce.date().optional(),
});
export type CreatePostInput = z.infer<typeof CreatePostSchema>;
export type CreatePostOutput = z.output<typeof CreatePostSchema>;
// app/actions/posts.ts
'use server';
import { revalidatePath } from 'next/cache';
import { CreatePostSchema } from '@/lib/schemas/post';
export async function createPost(raw: unknown) {
const parsed = CreatePostSchema.safeParse(raw);
if (!parsed.success) {
return { ok: false as const, fieldErrors: parsed.error.flatten().fieldErrors };
}
const post = await db.posts.create({ data: parsed.data });
revalidatePath('/blog');
return { ok: true as const, post };
}
The two literal return types are the part teams skip and later regret. Without them the caller sees a union whose shape it must narrow anyway, and a missing narrowing becomes a runtime crash when a component reads a field that only exists on the failure branch. Tagging the discriminant with a literal type turns that crash into a compile error at the call site.
The same discipline applies to reading from the database or an external API: the values coming back are typed by a schema, not trusted because a query returned them. Treat validation as a property of the boundary, not of the feature.
Typing route handlers without fooling yourself
A route handler can be typed precisely â the request, the parameters, and the response body â and doing so catches the classic mistake of returning a shape the client does not expect.
// app/api/posts/[id]/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { CreatePostSchema } from '@/lib/schemas/post';
type RouteContext = { params: Promise<{ id: string }> };
export async function GET(request: NextRequest, context: RouteContext) {
const { id } = await context.params;
const post = await db.posts.findUnique({ where: { id } });
if (!post) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
return NextResponse.json(post);
}
export async function PATCH(request: NextRequest, context: RouteContext) {
const { id } = await context.params;
const body = await request.json();
const parsed = CreatePostSchema.partial().safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: 'Invalid body', details: parsed.error.flatten().fieldErrors },
{ status: 400 }
);
}
const updated = await db.posts.update({ where: { id }, data: parsed.data });
return NextResponse.json(updated);
}
The compile-time type says the body is a JSON value; only the schema says it is a valid partial post. Keep a single response helper per route module so success and error envelopes stay consistent, and never widen a handler's return type to a generic response â that is how the client ends up reading a field that has been gone for two releases.
The App Router traps that silently defeat types
| Trap | What actually happens | The fix |
|---|---|---|
| Reading params without awaiting | You hold a Promise, every property access fails | Await it in an async component or loader |
| Treating a body as trusted JSON | The parsed value has no useful type | Run it through a schema before use |
| Client-only globals in server files | Window or document is undefined at runtime | Move to a client component or load dynamically |
| A handwritten interface for API data | Type and implementation drift apart | Derive the type from the schema that validates it |
| Widening with broad any to silence an error | The error moves to production | Use a type guard or an explicit unknown plus narrowing |
| Forgetting generated route types | Compiler checks an outdated route shape | Include the generated types directory and rebuild |
The last row deserves emphasis because it is invisible: if the generated types are excluded from the project, tsc will happily pass code that calls a route which no longer exists. Run the type check after a clean build at least once in continuous integration so the generated directory is always fresh.
Sharing types without sharing code
Duplication across packages is the usual cost of sharing types in a monorepo â but the duplication you want to avoid is a type definition, not the code that computes it. Three patterns cover nearly every case. Export types from a schema module that both the server and the client import, which keeps validation and typing in one file. Generate a typed client from your OpenAPI description so an external consumer cannot drift from the server. Or, with a query library, infer types straight from the query layer rather than maintaining parallel interfaces. In all three, the rule is the same: one source of truth that both ends read.
Making the compiler a gate
A type check that only runs on developer machines is a suggestion. Put it in continuous integration, run it against a clean checkout so generated files are present, and keep the fast feedback loop locally by wiring the same command into your pre-commit hooks. Complement it with a lint pass that bans accidental escape hatches, and periodically grep for the disables that have piled up â every suppression with no expiry is a small hole in the gate. Teams that hold this line find that most of their runtime type errors move to compile time within a sprint, and the remaining failures cluster in the few boundaries where validation, not typing, is the real defence.
Common Mistakes
Accessing route params as if they were a plain object
Fix: Await the params promise inside an async component; the App Router delivers them asynchronously.
Handwriting an interface for data that a schema already validates
Fix: Infer the type from the schema so validation and typing cannot drift.
Returning an untagged union from a server action
Fix: Attach literal ok discriminants so callers must narrow the result and cannot read the wrong branch.
Casting request bodies with as any to get past a compile error
Fix: Parse with a schema and handle failure explicitly; a cast only moves the crash to runtime.
Skipping generated route types from tsconfig include
Fix: Include the generated types directory and rebuild before the check in CI.
Leaving suppressions in place indefinitely
Fix: Review disables on a schedule; each one without an owner is a hole in the gate.
Best Practices
- Turn on strict mode and unchecked index access before writing much code
- Keep one schema module per resource that exports both the validator and the inferred type
- Validate at every network boundary: forms, route handlers, webhooks, and database reads
- Use path aliases consistently in the compiler and the bundler configuration
- Run a clean type check in CI so generated route types are always current
- Prefer narrowing with type guards over widening with casts
Interview Questions
Q1: Why must route params be awaited in recent App Router versions?
They are delivered as a Promise so that dynamic segments can be resolved after streaming begins; awaiting them in the async component is what yields the typed object.
Q2: How do you keep server and client types in sync?
Infer types from a shared validation schema, or generate them from an API description, so there is one definition that both sides consume.
Q3: What is wrong with casting an unknown body to a known type?
The cast asserts what the compiler cannot verify, so malformed input passes the check and fails later inside business logic where context is poor.
Q4: How do you make server action results safe to consume?
Return a discriminated union with literal success flags so the caller must narrow before reading branch-specific fields.
Key Takeaways
- Strict configuration with no unchecked index access removes entire categories of runtime surprises.
- Dynamic params arrive asynchronously and must be awaited before property access compiles.
- A schema is the single source of truth: it validates at runtime and infers the compile-time type.
- Tagged return unions make callers narrow results, turning a class of crashes into compile errors.
- The App Router traps â unawaited params, client globals in server files, stale generated types â are all invisible until runtime if the compiler is not looking.
- Type checking belongs in CI against a clean build, not only in the editor.