Home / Articles

Type-check Next.js links and params before a 404 ships

Turn on Next.js typed routes so TypeScript rejects a mistyped href, a bad dynamic segment, and the wrong param name before that path can 404.

Publisher: REACTAPP.TOP10 min read2322 words

This article is published in English.

Sources: Next.js Typed Routes: Catch Broken Links and Wrong Params at Build Time

You can ship a broken internal link without ever sitting down to type one. Early in a Next.js app it usually shows up after a rename. The folder app/settings becomes app/account, the production build still exits cleanly, the deploy stays green, and three menus in other corners of the UI still aim at a route the folder tree no longer owns.

CI looks fine the whole time. A visitor chooses Settings and the response is a 404.

Telling the team to look harder will not close that hole. TypeScript can reject a path that does not match a real page. You turn the check on with one config field, then it covers Link, the navigation helpers, dynamic segments written as template literals, and the param helpers PageProps, LayoutProps, and RouteContext.

When every href is only a string

The compiler is perfectly happy with a header like this:

// app/components/header.tsx
import Link from 'next/link';

export function Header() {
  return <Link href="/setings">Settings</Link>;
}

Linger on /setings and the missing t is loud. Rush the edit, and the same string looks ordinary.

Out of the box, href is typed as a bare string. Any string is legal. TypeScript has no inventory of the pages that live under app.

params has the same blind spot. The directory segment is [slug], the page reads params.id, and nothing complains until render, when the value is undefined.

Practical rule: when a tool can see the mistake, stop spending a person's attention on it.

Paper map versus GPS

Hold two ways of picking a destination next to each other.

  • A paper map will accept any street you scribble on the envelope. You find the problem only after you arrive.
  • A GPS offers addresses that exist. A misspelling never becomes a route.

Unchecked href values behave like that paper map. The typed-route flag behaves like the GPS.

The framework already holds every path, since folder names are how it builds the app. Passing that inventory to TypeScript lets the editor flag a missing page while the file is still open.

That handoff is the whole mechanism.

The config flag

You need a TypeScript project, and you need one field in the config:

// next.config.ts
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  typedRoutes: true,
};

export default nextConfig;

Current releases read typedRoutes from the root of the config object. Beta-era guides buried the same key inside experimental. Drop that wrapper.

With the flag set, Next.js writes a generated declaration under .next/types. The file names every route in the app. Those declarations are rewritten by next dev, by next build, and by next typegen.

Scaffold the app with create-next-app and those generated files are already on the compilation path. If you assembled tsconfig.json yourself, the include array has to mention them:

{
  "include": [
    "next-env.d.ts",
    ".next/types/**/*.ts",
    "**/*.ts",
    "**/*.tsx"
  ]
}

After the first generation, restart the TypeScript server in your editor. Until you do, the editor is still looking at the old program and will not see the new route types.

Errors the checker actually raises

With the types loaded, the header typo fails in the editor:

// app/components/header.tsx
import Link from 'next/link';

export function Header() {
  return (
    <nav>
      <Link href="/settings">Settings</Link>
      <Link href="/setings">Typo</Link>
    </nav>
  );
}

/settings matches a real page, so the first link is fine. /setings fails to type-check. No folder produces that path.

Three kinds of call get checked:

  • The href prop on next/link, whether the page lives in the App Router or the Pages Router.
  • On the App Router, push, replace, and prefetch from the next/navigation router.
  • A dynamic folder, for example /blog/[slug], as long as the href is written with a template literal.

The dynamic-folder case is the one teams skip. A template literal whose shape matches a real folder is accepted:

// app/blog/post-card.tsx
import Link from 'next/link';

export function PostCard({ slug, title }: { slug: string; title: string }) {
  return <Link href={`/blog/${slug}`}>{title}</Link>;
}

Read it as a sentence. A link of /blog/ plus exactly one segment is legal, because app/blog/[slug] is a real folder.

There is a limit. The checker only cares about URL shape. A slug can be absent from the database and the link will still type-check.

Concatenation and the Route cast

Template literals are inspected. A string built with + is not, because the compiler cannot see through the concatenation.

This version is a type error. TypeScript has no idea what the finished string will be:

// app/components/back-link.tsx (Bad: type error)
import Link from 'next/link';

export function BackLink({ section }: { section: string }) {
  return <Link href={'/' + section}>Back</Link>;
}

When you have already confirmed the path is real, cast it to Route:

// app/components/back-link.tsx (Good: explicit cast)
import type { Route } from 'next';
import Link from 'next/link';

export function BackLink({ section }: { section: string }) {
  return <Link href={('/' + section) as Route}>Back</Link>;
}

The cast is a promise to the compiler that you checked this path yourself. The type system stops looking.

Practical rule: write template literals first. Use as Route only if you have no other option, and keep those spots rare enough that a reviewer will actually see them.

Paths that live only inside proxy.ts, or only as rewrites, need the same cast. Next.js never sees those as files under app, so they never appear in the generated route list.

Menus are where dead links sit the longest. One array holds the whole menu, and renames usually forget it.

Give the array a Route element type and every entry is checked:

// app/components/nav-items.ts
import type { Route } from 'next';

type NavItem<T extends string = string> = {
  href: T;
  label: string;
};

export const navItems: NavItem<Route>[] = [
  { href: '/', label: 'Home' },
  { href: '/pricing', label: 'Pricing' },
  { href: '/blog', label: 'Blog' },
];

Rename app/pricing and the build fails until this file changes too. That is the outcome you want.

Most codebases wrap next/link in a NavLink or a Card. Type that wrapper's href as string and the checks disappear again.

A generic keeps the literal type flowing through to Link:

// app/components/nav-link.tsx
import type { Route } from 'next';
import Link from 'next/link';

export function NavLink<T extends string>({
  href,
  children,
}: {
  href: Route<T>;
  children: React.ReactNode;
}) {
  return (
    <Link href={href} className="px-3 py-2 hover:underline">
      {children}
    </Link>
  );
}

Route<T> preserves whatever literal the caller passed. A caller typing /setings into that prop is still rejected.

The docs type this prop as Route<T> | URL. If you pass that union into <Link> on Next.js 16.4, the compiler can reject the call. Leave the prop typed as Route<T>. Add URL only if a call site truly passes URL objects.

PageProps for params and searchParams

Typed links are one side of the problem. The other side is reading params without guessing the key.

A global helper named PageProps is already in scope. There is no import to add. Pass the route literal, and both params and searchParams come back typed:

// app/blog/[slug]/page.tsx
export default async function BlogPostPage(props: PageProps<'/blog/[slug]'>) {
  const { slug } = await props.params;
  const { ref } = await props.searchParams;

  return (
    <article>
      <h1>{slug}</h1>
      {typeof ref === 'string' && <p>Shared from {ref}</p>}
    </article>
  );
}

Each piece of that page does a specific job:

  • Pass '/blog/[slug]' and the resolved params object contains slug as a string. id is not a key, so reading it fails the type check.
  • You have to await props.params before you destructure it. Recent Next.js versions expose params asynchronously, which is why the await is mandatory.
  • Each searchParams entry might be one string, an array of strings, or missing. Narrow the value before you render it. The sample does that for ref: the shared-from line renders only when ref is a single string.

Wrong param names are the most common junior bug on a dynamic route. PageProps makes that bug a compile error.

LayoutProps and route handler context

Layouts and Route Handlers follow the same pattern.

LayoutProps covers the children node, the route params, and parallel slots. @analytics is the usual example:

// app/dashboard/layout.tsx
export default function DashboardLayout(props: LayoutProps<'/dashboard'>) {
  return <section className="mx-auto max-w-5xl">{props.children}</section>;
}

Add a parallel-route folder like app/dashboard/@analytics, and the layout receives props.analytics with a real type. Delete that folder and a layout that still outputs the slot will no longer compile. Same GPS, now applied to slots.

For a Route Handler, RouteContext types the context argument:

// app/api/users/[id]/route.ts
import type { NextRequest } from 'next/server';

export async function GET(
  _req: NextRequest,
  ctx: RouteContext<'/api/users/[id]'>
) {
  const { id } = await ctx.params;
  return Response.json({ id });
}

That string should be copied from the folders on disk. Match the directories and the param name stays honest.

Assistants are good at inventing a route that has no folder, and at reading a param the page never defined. With the flag on, those invented paths and keys fail the type check immediately.

Turning the flag on in a large app

Flip typedRoutes on in a big codebase and you can get dozens of errors in one pass. Treat that flood as useful. Each error is a path that might 404 for a visitor.

Work the errors down this list:

  • Typos in real paths come first. They are defects. Fix the string and a visitor never hits that 404.
  • Old links come second. A page moved or removed months back can still be referenced. Point the reference at the new path, or drop it.
  • Joined strings come third. Where you can, rebuild them with template literals so the checker stays in the loop.
  • Casts come last. Save as Route for what remains, mostly paths that exist only as rewrites. A one-line comment should say why you opted out of the check.

After the links are clean, switch each page off its hand-written param type and onto PageProps. Do a single route per change. The diff stays tiny and reviewers can follow it.

Skip the idea of one giant pull request. Clearing a handful of folders each day is plenty, as long as links you add from today onward go through the typed API.

Generate route types in CI

Route types used to show up only while next dev or next build was running. A lone tsc --noEmit in CI could therefore miss them.

There is now a command for that step:

# terminal
npx next typegen && npx tsc --noEmit

next typegen emits the route declarations, along with next-env.d.ts, and it skips the production compile. tsc then checks every link, every push, and every PageProps call against those files.

Wire both commands into the checks that run on a pull request. Then main never receives a path the type checker would reject.

Also ignore next-env.d.ts. Next.js rewrites it whenever the commands run, and a committed copy just drifts.

Mistakes that silently disable the check

  • Still nesting typedRoutes inside experimental. Current releases want that key at the root of the config. Shift it up.
  • Leaving the generated files out of tsconfig. If include never mentions .next/types/**/*.ts, the checker has nothing to read.
  • Joining an href with +. The checker cannot see a plus-built string, so it demands as Route. A template literal stays visible to the checker, which is what you want.
  • A wrapper typed as string. If NavLink declares href: string, the checker goes quiet. Declare Route<T> instead.
  • Sprinkling as Route on every href. Once every call site opts out, you are back to unchecked strings.
  • Running tsc in CI with no next typegen ahead of it. The route declarations may be missing, so a bad path gets through.

Questions that come up

Does typedRoutes slow the build?

You pay for an extra generation pass, and the compiler has more types to walk. On a typical app that extra time is minor compared with the 404s it prevents.

Does this work in a JavaScript project?

No. Typed routes need TypeScript. A JavaScript project can keep using ordinary links, and it simply will not get the checks.

Should external links use a plain anchor?

Yes. Point other websites at a normal anchor whose href is a full https URL. Reserve Link for paths that belong to this app.

Can an assistant migrate the links?

Yes. Hand the assistant your route list and insist on template literals, not casts. Opting every path out with a cast would erase the check you just enabled.

What you leave switched on

Leave typedRoutes set to true on the root object in next.config.ts, and confirm tsconfig.json pulls in .next/types. From then on the compiler watches Link, push, and prefetch.

Write template literals when you can. Save the Route cast for the odd path you cannot express that way. Menus and custom link components should be generic over Route. Pages, layouts, and route handlers should take PageProps, LayoutProps, and RouteContext rather than interfaces you maintain yourself. CI should invoke next typegen and only then tsc.

Once a bad link fails the build, a plain string stops looking like a safe way to name a page.