Next.js course ยท Module 9: Integrations and Advanced Features

Typed Routes - Safe links with TypeScript

9 min read ยท
In this lesson12

In the navigation systems of Metropolis Quantum 2150 one wrong address sends a transport to a dock that does not exist. In an application it looks harmless: a typo in href, TypeScript stays silent, and after a click the user lands on a 404 page. Matrix, the route guardian of the Metropolis, therefore demands that every path is checked before launch. Typed Routes make this possible - a Next.js feature that provides type safety for the paths in your application.

Problem: Errors in paths

Without Typed Routes paths are plain strings, so the compiler accepts any text:

// Easy to typo - no validation in TypeScript
<Link href="/prodcuts">Products</Link>  // Typo!
<Link href="/users/123/setings">Settings</Link>  // Another typo!

// No parameter checking
redirect('/products/' + productId);  // What if productId is undefined?

All three lines compile, and the errors only surface for the user.

Solution: Typed Routes

Typed Routes automatically generates types for all paths in the application based on the structure of the app directory.

Enabling Typed Routes

Since Next.js 15.5 the typedRoutes option is stable and you set it at the top level of the config. Previously it was hidden in the experimental object:

// next.config.js
module.exports = {
  typedRoutes: true,
};

After enabling it and running next dev, next build or next typegen, Next.js generates a file with the definitions of all routes in the .next/types directory. The project must use TypeScript, and tsconfig.json must include .next/types/**/*.ts.

Basic usage

The Link component from next/link now accepts only existing paths in href:

import Link from 'next/link';

function Navigation() {
  return (
    <nav>
      {/* Correct paths - TypeScript OK */}
      <Link href="/">Home</Link>
      <Link href="/products">Products</Link>
      <Link href="/about">About</Link>

      {/* Invalid path - TypeScript Error! */}
      <Link href="/prodcuts">Products</Link>
      {/* Type '"prodcuts"' is not assignable to type 'Route' */}
    </nav>
  );
}

The /prodcuts typo becomes a compile error with a message that the text does not match the Route type. Correct links work exactly as before.

Dynamic segments

Dynamic segments such as [id] accept any value in their place, but the rest of the path must match:

// For the structure: app/products/[id]/page.tsx
<Link href="/products/123">Product 123</Link>  // OK

// For the structure: app/users/[userId]/posts/[postId]/page.tsx
<Link href="/users/456/posts/789">Post</Link>  // OK

TypeScript checks the shape of the address, not whether product 123 exists in the database.

useRouter with types

In the App Router the router methods from next/navigation are typed too: push, replace and prefetch:

'use client';

import { useRouter } from 'next/navigation';

function ProductActions({ productId }: { productId: string }) {
  const router = useRouter();

  const handleEdit = () => {
    // TypeScript validates the path
    router.push(`/products/${productId}/edit`);
  };

  const handleDelete = () => {
    // Correct
    router.push('/products');
  };

  const handleBroken = () => {
    // TypeScript Error if /prodcts does not exist
    router.push('/prodcts');
  };

  return (
    <div>
      <button onClick={handleEdit}>Edit</button>
      <button onClick={handleDelete}>Delete</button>
    </div>
  );
}

The template /products/${productId}/edit is accepted because it matches the route pattern, while /prodcts is rejected.

redirect() with types

It is worth keeping the paths you pass to redirect() under the same discipline:

import { redirect } from 'next/navigation';

async function ProtectedPage() {
  const session = await getSession();

  if (!session) {
    // TypeScript validates the path
    redirect('/login');
  }

  if (!session.isVerified) {
    // Correct
    redirect('/verify-email');
  }

  return <Dashboard />;
}

The Next.js docs explicitly list typing for Link and the router methods, so with redirect() the safest choice is to use Route-typed constants, which you will meet in a moment.

The Route helper

Next.js generates a Route type imported from the next package, which you can use in your own functions:

import type { Route } from 'next';

// Function accepting only valid paths
function navigateTo(path: Route) {
  window.location.href = path;
}

navigateTo('/products');  // OK
navigateTo('/prodcuts');  // Error

The function accepts only the address of an existing page, so the error appears right at the call site.

Type for dynamic paths

When you build an address from a non-literal string, TypeScript does not know its value, so you need the as Route assertion:

import type { Route } from 'next';

// Function generating a product link
function getProductUrl(id: string): Route {
  return `/products/${id}` as Route;
}

// Usage
<Link href={getProductUrl('123')}>Product</Link>

An assertion is a promise you make to the compiler, so wrap it in a single helper function instead of scattering it across the app.

Working with search parameters

Query parameters are not part of the route definition, so you can add them as an object or in the string:

import Link from 'next/link';

function ProductFilters() {
  return (
    <div>
      {/* Path with query params */}
      <Link
        href={{
          pathname: '/products',
          query: { category: 'electronics', sort: 'price' },
        }}
      >
        Electronics (sort by price)
      </Link>

      {/* Or as a string */}
      <Link href="/products?category=electronics&sort=price">
        Electronics
      </Link>
    </div>
  );
}

In both cases the /products path is checked, while the category and sort parameters stay free.

Practical example - E-commerce navigation

In a real application you keep links in one place. The NavigationItem interface requires the href field to be of type Route:

// types/navigation.ts
import type { Route } from 'next';

export interface NavigationItem {
  label: string;
  href: Route;
  icon?: React.ReactNode;
}

export const mainNavigation: NavigationItem[] = [
  { label: 'Home', href: '/' },
  { label: 'Products', href: '/products' },
  { label: 'Categories', href: '/categories' },
  { label: 'About', href: '/about' },
  { label: 'Contact', href: '/contact' },
];

export const userNavigation: NavigationItem[] = [
  { label: 'Profile', href: '/account/profile' },
  { label: 'Orders', href: '/account/orders' },
  { label: 'Settings', href: '/account/settings' },
];

Removing the /contact page from the app directory immediately flags an error in this array.

The navigation component only renders this array:

// components/MainNav.tsx
import Link from 'next/link';
import { mainNavigation } from '@/types/navigation';

export function MainNav() {
  return (
    <nav className="flex gap-6">
      {mainNavigation.map((item) => (
        <Link
          key={item.href}
          href={item.href}  // TypeScript knows this is a valid path
          className="hover:text-blue-500"
        >
          {item.label}
        </Link>
      ))}
    </nav>
  );
}

The component contains no hand-typed address, so there is no room for a typo.

Breadcrumbs have an optional href, because the last item is the current page, which is not a link:

// components/Breadcrumbs.tsx
import Link from 'next/link';
import type { Route } from 'next';

interface BreadcrumbItem {
  label: string;
  href?: Route;
}

interface BreadcrumbsProps {
  items: BreadcrumbItem[];
}

export function Breadcrumbs({ items }: BreadcrumbsProps) {
  return (
    <nav aria-label="Breadcrumb" className="flex items-center gap-2 text-sm">
      {items.map((item, index) => (
        <span key={index} className="flex items-center gap-2">
          {index > 0 && <span className="text-gray-400">/</span>}
          {item.href ? (
            <Link href={item.href} className="text-blue-600 hover:underline">
              {item.label}
            </Link>
          ) : (
            <span className="text-gray-600">{item.label}</span>
          )}
        </span>
      ))}
    </nav>
  );
}

// Usage
<Breadcrumbs
  items={[
    { label: 'Home', href: '/' },
    { label: 'Products', href: '/products' },
    { label: 'Electronics', href: '/products?category=electronics' },
    { label: 'Smartphone X' },  // Last item without a link
  ]}
/>

The href?: Route type lets you skip the link, but if you do provide one, it must be valid.

Limitations of Typed Routes

1. Dynamic segments

TypeScript checks the route pattern, but not the value inserted in place of the segment:

// TypeScript cannot validate the value of a dynamic segment
const id = getUserInput();
<Link href={`/products/${id}`}>Product</Link>  // Accepts any string

// You can use a type assertion if you're sure
<Link href={`/products/${id}` as Route}>Product</Link>

Validate user input separately, because the type will not tell you whether such a product exists.

Addresses outside the application are not of type Route:

// External URLs are not Route
<Link href="https://google.com">Google</Link>  // Error

// Use a plain <a> for external links
<a href="https://google.com">Google</a>

For external links use a plain a tag, ideally with rel="noopener noreferrer" when opening in a new tab.

3. Catch-all routes

A catch-all segment [...slug] accepts any number of parts after the prefix:

// For app/docs/[...slug]/page.tsx
// TypeScript checks the prefix but not the full path
<Link href="/docs/getting-started/installation">Docs</Link>  // OK

Only the /docs/ prefix is checked, and whether a given docs page exists only shows up at runtime.

Segment config is checked too

The built-in Next.js TypeScript plugin also watches segment config exports. Such an export consists of the words export const, the option name, the = sign and the value:

// app/products/page.tsx
export const fetchCache = 'force-cache';

The plugin warns you if you type a value that does not exist, such as 'force-cash'. Remember that in Next.js 16 with Cache Components enabled the fetchCache option goes away in favor of the 'use cache' directive.

Migrating an existing project

Step 1: Enable typedRoutes

Migration starts with the same config change as in a new project:

// next.config.js
module.exports = {
  typedRoutes: true,
};

Nothing breaks yet after saving the file, because the route types have not been generated.

Step 2: Run build or dev

Types are created when you start the dev server or run a build:

npm run dev
# or
npm run build

You can also use next typegen, which generates the types without starting a server.

Step 3: Fix TypeScript errors

Now check types across the whole project. The type-check script is usually tsc --noEmit added in package.json:

# Check for errors
npm run type-check

# Common issues:
# - Typos in paths
# - Non-existent pages
# - External links inside <Link>

Every reported error is a real link that would have led nowhere.

Debugging

If types do not work correctly, delete the generated files and let Next.js create them again:

# Remove generated types and regenerate
rm -rf .next/types
npm run dev

Check the generated file in the .next/types directory. In older versions it was called link.d.ts, newer releases may use a different name:

// .next/types/link.d.ts
// This file contains all the generated Route types

Next.js also generates the global PageProps, LayoutProps and RouteContext helpers there, which type page parameters by path. Do not edit these files by hand, because they will be overwritten.

Summary

Typed Routes in Next.js provide:

  • Type safety - path errors caught at compile time
  • Autocomplete - the IDE suggests available paths
  • Refactoring - changing the routing structure automatically reveals errors
  • Documentation - the types document the available paths

My advice: enable typedRoutes at the start of a project and keep all navigation links in Route-typed arrays. In the next lesson you will learn next-intl, where paths also get a language prefix.

Remember: in Metropolis Quantum every course is checked before launch, and Typed Routes turn a broken link into a compile error.

Code for this lesson: App.tsx
// Demo: Typed Routes - type-safe links with TypeScript
// Next.js experimental typedRoutes provides type-safety for Link and router
import React, { useState } from 'react';

// Configuration in next.config.js:
// /** @type {import('next').NextConfig} */
// const nextConfig = {
//   experimental: {
//     typedRoutes: true,
//   },
// };
//
// After enabling, Next.js generates types in .next/types:
// - Link href is type-checked
// - router.push() requires a valid path
// - Compile errors for non-existent routes

interface Route {
  path: string;
  params?: Record<string, string>;
  description: string;
  valid: boolean;
  component: string;
}

const routes: Route[] = [
  { path: '/', description: 'Home page', valid: true, component: 'app/page.tsx' },
  { path: '/products', description: 'Products listing', valid: true, component: 'app/products/page.tsx' },
  { path: '/products/neural-link', description: 'Product detail (slug)', valid: true, component: 'app/products/[slug]/page.tsx', params: { slug: 'neural-link' } },
  { path: '/dashboard', description: 'User dashboard', valid: true, component: 'app/dashboard/page.tsx' },
  { path: '/dashboard/settings', description: 'Dashboard settings', valid: true, component: 'app/dashboard/settings/page.tsx' },
  { path: '/api/health', description: 'Health check endpoint', valid: true, component: 'app/api/health/route.ts' },
  { path: '/nonexistent', description: 'This route does not exist!', valid: false, component: '???' },
  { path: '/dashbord', description: 'Typo in route name!', valid: false, component: '???' },
];

function TypedLinkExample({ route }: { route: Route }) {
  return (
    <div style={{
      background: route.valid ? 'rgba(100,255,218,0.05)' : 'rgba(244,67,54,0.05)',
      border: `1px solid ${route.valid ? 'rgba(100,255,218,0.15)' : 'rgba(244,67,54,0.2)'}`,
      borderRadius: '8px', padding: '14px', marginBottom: '8px',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <code style={{
            color: route.valid ? '#64ffda' : '#f44336',
            fontSize: '0.9rem',
          }}>
            &lt;Link href="{route.path}"&gt;
          </code>
          {route.params && (
            <span style={{ color: '#ff9800', fontSize: '0.75rem', marginLeft: '8px' }}>
              params: {JSON.stringify(route.params)}
            </span>
          )}
        </div>
        <span style={{
          background: route.valid ? 'rgba(76,175,80,0.15)' : 'rgba(244,67,54,0.15)',
          color: route.valid ? '#4caf50' : '#f44336',
          padding: '2px 10px', borderRadius: '10px', fontSize: '0.7rem',
        }}>
          {route.valid ? 'Type OK' : 'Type Error'}
        </span>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '6px' }}>
        <span style={{ color: '#78909c', fontSize: '0.8rem' }}>{route.description}</span>
        <code style={{ color: '#78909c', fontSize: '0.7rem' }}>{route.component}</code>
      </div>
      {!route.valid && (
        <div style={{
          marginTop: '8px', padding: '8px',
          background: 'rgba(244,67,54,0.08)', borderRadius: '4px',
          fontFamily: 'monospace', fontSize: '0.75rem', color: '#f44336',
        }}>
          Type error: Type '"{route.path}"' is not assignable to type 'Route'.
        </div>
      )}
    </div>
  );
}

function CodeComparison() {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginTop: '20px' }}>
      <div style={{
        background: 'rgba(244,67,54,0.05)', border: '1px solid rgba(244,67,54,0.15)',
        borderRadius: '10px', padding: '16px',
      }}>
        <h4 style={{ color: '#f44336', marginBottom: '8px', fontSize: '0.85rem' }}>
          Without Typed Routes
        </h4>
        <pre style={{ margin: 0, color: '#b0bec5', fontSize: '0.75rem', lineHeight: 1.6 }}>
{
`// No verification at compile-time
<Link href="/dashbord">  // Typo!
<Link href="/old-page">  // Does not exist!

// Error discovered only at runtime
// 404 page, wrong navigation...`}
        </pre>
      </div>
      <div style={{
        background: 'rgba(76,175,80,0.05)', border: '1px solid rgba(76,175,80,0.15)',
        borderRadius: '10px', padding: '16px',
      }}>
        <h4 style={{ color: '#4caf50', marginBottom: '8px', fontSize: '0.85rem' }}>
          With Typed Routes
        </h4>
        <pre style={{ margin: 0, color: '#b0bec5', fontSize: '0.75rem', lineHeight: 1.6 }}>
{
`// TypeScript checks at compile-time
<Link href="/dashbord">  // TS Error!
// Type '"/dashbord"' is not
// assignable to type 'Route'

<Link href="/dashboard"> // OK!
router.push("/products") // OK!`}
        </pre>
      </div>
    </div>
  );
}

export default function TypedRoutesDemo() {
  const [showAll, setShowAll] = useState(true);

  const displayed = showAll ? routes : routes.filter(r => !r.valid);

  return (
    <div style={{
      background: '#0f0f23', minHeight: '100vh', padding: '24px',
      color: '#fff', fontFamily: 'system-ui, sans-serif',
    }}>
      <h1 style={{ color: '#64ffda', marginBottom: '4px' }}>Typed Routes</h1>
      <p style={{ color: '#b0bec5', marginBottom: '20px' }}>
        Type-safe links with TypeScript - errors caught at compile-time
      </p>

      <div style={{
        background: 'rgba(0,0,0,0.3)', borderRadius: '8px',
        padding: '12px', marginBottom: '20px',
      }}>
        <code style={{ color: '#78909c', fontSize: '0.8rem' }}>
          // next.config.js
        </code>
        <br />
        <code style={{ color: '#64ffda', fontSize: '0.8rem' }}>
          experimental: {'{'} typedRoutes: true {'}'}
        </code>
      </div>

      <div style={{ display: 'flex', gap: '8px', marginBottom: '16px' }}>
        <button onClick={() => setShowAll(true)} style={{
          background: showAll ? '#64ffda' : 'transparent',
          color: showAll ? '#0f0f23' : '#b0bec5',
          border: '1px solid rgba(100,255,218,0.3)',
          padding: '6px 14px', borderRadius: '20px', cursor: 'pointer',
        }}>All Routes</button>
        <button onClick={() => setShowAll(false)} style={{
          background: !showAll ? '#f44336' : 'transparent',
          color: !showAll ? '#fff' : '#b0bec5',
          border: '1px solid rgba(255,255,255,0.1)',
          padding: '6px 14px', borderRadius: '20px', cursor: 'pointer',
        }}>Type Errors Only</button>
      </div>

      {displayed.map(r => (
        <TypedLinkExample key={r.path} route={r} />
      ))}

      <CodeComparison />
    </div>
  );
}

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Typed Routes in Next.js provide:

Hands-on tasks in the game

  • Horizontal ordering

    Arrange the elements in the correct order: export const โ†’ fetchCache โ†’ =

  1. QuestionTyped Routes in Next.js
  2. Put in orderOrder: export const โ†’ fetchCache โ†’ =

Useful articles