Type-Safe URL Parameters and Query Strings
You'll learn: How to type route parameters and query strings so they match your backend API expectations in modern frameworks like Next.js or Remix.
The Problem: Strings Everywhere
When working with URLs, frameworks typically give you strings—whether it's /user/123 or ?sort=asc&limit=10. TypeScript sees these as string or Record<string, string>, which means you lose type safety right where data enters your application.
Think of it like receiving mail: the postal service delivers everything as "an envelope," but you know some contain invoices (numbers), some contain invitations (dates), and some contain surveys (specific options). You need to validate the contents match expectations.
The URL Parameters Challenge
Route parameters (like userId in /users/:userId) arrive as strings. But your backend might expect a number, or a specific ID format. Without typing these, you can't catch mistakes until runtime.
Query strings are even messier: they're optional, can be arrays (?tag=a&tag=b), and need parsing into proper types (numbers, booleans, dates).
The Solution: Type-Level Contracts
Modern frameworks let you define what parameters and queries your routes accept:
In Next.js 13+ App Router, you receive typed params:
// app/users/[userId]/page.tsx
type PageProps = {
params: { userId: string }
searchParams: { sort?: string; limit?: string }
}
export default function UserPage({ params, searchParams }: PageProps) {
// params.userId is known to exist
// searchParams.sort is known to be optional
}
In Remix, loaders provide similar patterns where you type the data contract between routes and components.
The key is creating interfaces that mirror your URL structure, then validating the runtime strings against those contracts using type guards or schema validators like Zod.
Key Takeaway: Typing URL parameters and query strings creates a compile-time contract for data entering your app through routes, catching mismatches between frontend expectations and backend requirements before deployment.