- Published
- Author
- Ashwani Kumar JhaSenior System Analyst
Next.js Typed Routes
Next.js now provides TypeScript support for route parameters and navigation, helping catch routing errors at compile time rather than runtime.
Next.js automatically generates route types based on our file structure in the
For example, if we have:
The generated types will understand routes like
#nextjs #typescript
Next.js now provides TypeScript support for route parameters and navigation, helping catch routing errors at compile time rather than runtime.
Next.js automatically generates route types based on our file structure in the
app directory.For example, if we have:
Code
app/
users/
[id]/
page.tsx
posts/
[slug]/
page.tsxThe generated types will understand routes like
/users/123 and /posts/my-post-slug.Code
import { useRouter } from 'next/navigation'
import Link from 'next/link'
// TypeScript knows about our routes
const router = useRouter()
router.push('/users/123') // ✅ Valid
router.push('/invalid-route') // ❌ TypeScript error
// Link component is also typed
<Link href="/posts/my-slug">My Post</Link> // ✅ Valid
<Link href="/wrong-path">Invalid</Link> // ❌ TypeScript error#nextjs #typescript