Typed links and route contracts
What you need to know
Typed routes can catch misspelled internal destinations during development. Runtime data and external URLs still require validation, even in a project that passes the TypeScript compiler.
By the end, you can: detect invalid route strings; separate runtime validation.
Opt in to typed links
// next.config.tsimport type {NextConfig} from 'next';const config: NextConfig = {typedRoutes: true, cacheComponents: false};export default config;Expected behavior: In a reviewed TypeScript app, regenerated declarations enable typed route checking. Exact compiler diagnostics depend on the route tree.
How it works
Enable typedRoutes in next.config.ts and regenerate route declarations. Link href checking can then catch incorrect literal paths. A constructed URL may be inferred correctly when its template literal matches a known route; more complex strings may require narrowing or a reviewed Route assertion. An assertion is not a validator: it simply tells the compiler to accept a value. Never cast user input to Route and navigate to it without checking. Use a closed map of destinations for known navigation choices and validate dynamic data with a narrow domain rule. For a route string from the network, reject unknown targets or map them to a safe default. Generated route types do not guarantee authorization, valid search parameters or resource existence. Run actual route generation before treating a compile result as proof of this feature.
Choose known destinations instead of casting input
// app/nav/SectionLink.tsx — /catalog and /help must existimport Link from 'next/link';const destinations = {books:'/catalog',support:'/help'} as const;export default function SectionLink({choice}:{choice:unknown}) { const href = choice === 'books' ? destinations.books : destinations.support; return <Link href={href}>Open section</Link>;}Expected behavior: books links to /catalog; anything else falls back to /help. No arbitrary destination is accepted.
Common mistake
raw as Route does not stop an external URL or malformed value at runtime. Use allowlisted mappings or validated components before constructing a destination. Do not turn off typed route errors to hide broken links.
Practice and verification
Add a /help route to the fixture and intentionally write a link to /hepl. After type generation check the diagnostic, then fix it. Test unknown navigation choices independently.
Scope: App Router, proposed Next.js 16.x, React 19 family, Cache Components disabled. Framework snippets are static or explicitly partial; actual browser, auth and generated-route checks are pending. SQLite exercises run separately in the authoring environment, not the ByteMind evaluator.
Further reading: Typed Routes · Ts · Cli