Course contentsShow
← React
Lesson 1863 of 2,39643. RoutingFree lesson

Type-Safe Search Params: Manual Parsing Patterns

Parse and validate search params into typed values with Zod or manual number/boolean coercion.

Type-Safe Search Params: Manual Parsing Patterns

You'll learn how to transform raw URL search parameters into validated, typed values your components can trust.

The Type Safety Gap

useSearchParams returns all values as strings (or null). When you read ?page=2&active=true, you get "2" and "true" — not numbers or booleans. Passing these directly to functions expecting specific types causes bugs and TypeScript errors.

Manual Parsing Approach

Convert string params to proper types at the boundary:

function ProductList() {
  const [searchParams] = useSearchParams();
  
  // Manual coercion with fallbacks
  const page = Number(searchParams.get('page')) || 1;
  const limit = Number(searchParams.get('limit')) || 10;
  const active = searchParams.get('active') === 'true';
  
  // Now you have typed values
  const offset = (page - 1) * limit; // ✓ number math works
}

Validation with Zod

For complex requirements, use Zod schemas:

import { z } from 'zod';

const paramsSchema = z.object({
  page: z.coerce.number().int().min(1).default(1),
  sort: z.enum(['name', 'date', 'price']).default('name'),
  active: z.coerce.boolean().default(false)
});

function ProductList() {
  const [searchParams] = useSearchParams();
  
  const parsed = paramsSchema.parse({
    page: searchParams.get('page'),
    sort: searchParams.get('sort'),
    active: searchParams.get('active')
  });
  
  // parsed.page is number, parsed.sort is narrowed enum
}

Why It Matters

Without parsing, if (page > 10) compares strings ("2" > "10" is true!). With parsing, you get predictable behavior and TypeScript catches misuse at compile time.

Key Takeaway: Always parse and validate search params into typed values using manual coercion (Number(), equality checks) or schema validators like Zod — never trust raw string values in business logic.