Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 72 ยท Configuration, Tooling and Testing

TypeScript, ESLint and Typed Routes

Set up TypeScript and ESLint in Next.js: tsconfig options, typed props for pages and layouts, PageProps helpers, typed routes, lint rules and the Biome option.

Next.js is built for TypeScript. When you answer "yes" to the TypeScript prompt in create-next-app, you get a configured compiler, types for every special file, and an editor plugin that understands the App Router. The payoff is large: a wrong prop name, a misspelled link or a missing route parameter shows up as a red underline before you ever open the browser.

This lesson explains the files that make it work, how to type pages, layouts and route handlers, what typed routes add, and how linting fits in. The real toolchain (the compiler, ESLint, Biome) cannot run on this site, so configuration is read-only. The runnable examples are real TypeScript programs on the site's TypeScript runner: they rebuild, with ordinary type-level code, the trick Next.js uses to infer route parameters from a path string. They are stand-ins in the sense that Next.js generates its types from your folders instead of from a string you write by hand.

Three safety nets

TypeScript Checks types in the editor and during next build.
Typed routes Link targets are checked against your real pages.
Linting Rules catch mistakes types cannot see.

Types check shapes. Lint rules check habits.

1 / 2

What create-next-app gives you

A TypeScript project contains a tsconfig.json and a file called next-env.d.ts. Do not edit next-env.d.ts: Next.js regenerates it, and it pulls in the framework's global types. Do commit it unless your team's convention says otherwise. A typical tsconfig.json looks like this (yours may differ slightly between versions):

JSON
{
  "compilerOptions": {
    "target": "ES2017",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "incremental": true,
    "plugins": [{ "name": "next" }],
    "paths": { "@/*": ["./*"] }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

A few lines deserve a sentence each:

  • "strict": true turns on the strictest family of checks. Keep it: relaxing it later is easy, tightening it is painful.
  • "noEmit": true means the compiler only checks. Turbopack (or webpack) does the real building, so tsc never writes JavaScript.
  • "moduleResolution": "bundler" matches how the bundler resolves imports, so you can import without file extensions.
  • "isolatedModules": true requires every file to be understandable alone, which is what fast per-file compilers need.
  • "plugins": [{ "name": "next" }] loads the Next.js language-service plugin in your editor. It warns about invalid "use client" usage, wrong exports from page.tsx, and offers completions for segment config. It needs the editor to use the workspace TypeScript version.
  • "paths" creates the @/ alias, so import { db } from "@/lib/db" works from any depth. The .next/types entry in include pulls in the generated route types described below.

You can also write the config itself in TypeScript, next.config.ts, and type it with import type { NextConfig } from "next". Configuring Next.js covers the options.

Typing pages, layouts and handlers

In the App Router, each special file receives props with a known shape. The route parameters come in params, and since Next.js 15 both params and searchParams are promises you await:

TSX
// app/blog/[slug]/page.tsx (read-only)
export default async function BlogPost({
  params,
  searchParams,
}: {
  params: Promise<{ slug: string }>;
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
  const { slug } = await params;
  const { preview } = await searchParams;
  return <h1>{slug} {preview ? "(preview)" : ""}</h1>;
}

Writing that shape by hand for every page is repetitive and easy to get wrong when you rename a folder. Recent Next.js versions generate global helper types so you can ask for the shape by route name:

TSX
// app/blog/[slug]/page.tsx (read-only)
export default async function BlogPost(props: PageProps<"/blog/[slug]">) {
  const { slug } = await props.params;
  return <h1>{slug}</h1>;
}
TSX
// app/dashboard/layout.tsx (read-only)
export default function DashboardLayout(props: LayoutProps<"/dashboard">) {
  return <section>{props.children}</section>;
}
TSX
// app/api/users/[id]/route.ts (read-only)
export async function GET(_req: Request, ctx: RouteContext<"/api/users/[id]">) {
  const { id } = await ctx.params;
  return Response.json({ id });
}

PageProps, LayoutProps and RouteContext need no import. They are generated into .next/types whenever you run next dev or next build, and you can produce them on demand with the next typegen command, which is handy in CI before a separate type-check step. If you rename the folder from [slug] to [postId], every PageProps<"/blog/[slug]"> becomes a type error, which is exactly what you want. A layout that has parallel route slots gets those slot names as extra props through LayoutProps too.

Other useful types come from next: Metadata for the metadata export, NextConfig for the config, and MetadataRoute.Sitemap for sitemap.ts. NextRequest and NextResponse come from next/server. The children of a layout are React.ReactNode.

How the route string becomes a parameter type

How can a string like "/blog/[category]/[slug]" produce { category: string; slug: string }? TypeScript can do string pattern matching at the type level with template literal types and infer. The program below is a small version of the idea. Type checking is the point, so the example has almost no runtime logic: if it compiles, the types work. It runs on the site's TypeScript compiler in strict mode.

TypeScript Inferring route params from a path string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Read the types from the top. Segments splits the path at every slash into a union of segments. ParamOf turns one segment into an object type: a single bracket gives a required string, [...x] a required array, and [[...x]] an optional array, matching the real routing rules from Catch-All Routes. UnionToIntersection merges the per-segment objects into one. Try deleting slug from the first call, or passing a string where path expects an array: the compiler refuses to run the program and tells you which property is wrong.

Typed routes

Types for props protect the inside of a page. Typed routes protect the links between pages. Turn them on in the config:

TypeScript
// next.config.ts (read-only)
import type { NextConfig } from "next";

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

export default nextConfig;

With the option on, Next.js writes a union of every route in your app into the generated types, and the href of <Link> becomes checked against it. A typo is a compile error:

TSX
// read-only
import Link from "next/link";

<Link href="/blog/typed-routes">fine</Link>;
<Link href="/blgo">typo: type error</Link>;

Dynamic routes are matched by pattern, so /blog/anything passes while /blog alone only passes if a app/blog/page.tsx exists. For a link built from a variable you do not control, cast it to the Route type (import type { Route } from "next") or build it with a helper that proves it is valid. The checks cover href, router.push, redirect and similar APIs, but only for routes the app knows about: a link to an external site or to a file in public/ is not a route.

The second stand-in shows the same idea with a hand-written union. Real Next.js generates the union from your folders, so you never edit it.

TypeScript A typed href: the compiler rejects typos

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

If you uncomment the last line, the run stops with a compile error instead of printing anything, because the compile step type-checks first and refuses to produce a program. The message reads error TS2345: Argument of type '"/blgo"' is not assignable to parameter of type 'Href'. Real projects behave the same way: next build fails on type errors, so a wrong link cannot reach production. It is possible to switch that check off with typescript.ignoreBuildErrors, but that throws away the safety net, so use it only as a temporary measure.

ESLint

Types find wrong shapes; linting finds suspicious patterns that are perfectly well typed. Next.js ships an ESLint configuration package, eslint-config-next, with rules for React hooks and framework mistakes, for example using a plain <img> where next/image is better, linking to an internal page with <a> instead of <Link>, or breaking the rules of hooks. A modern project uses ESLint's flat config file:

JavaScript
// eslint.config.mjs (read-only)
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";

const eslintConfig = defineConfig([
  ...nextVitals,
  ...nextTs,
  globalIgnores([".next/**", "out/**", "build/**", "next-env.d.ts"]),
]);

export default eslintConfig;

core-web-vitals is the base set with some performance-related rules raised to errors, and typescript adds TypeScript-aware rules. In version 16 the next lint command is gone, and next build no longer runs the linter. You call ESLint yourself:

JSON
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "eslint"
  }
}

Because next build does not lint any more, run npm run lint (and a type check) in your CI pipeline, as separate steps before the build. The rules you will meet most often:

Rule What it catches
react-hooks/rules-of-hooks Hooks called conditionally or in loops
react-hooks/exhaustive-deps Missing dependencies in useEffect and friends
@next/next/no-img-element A plain <img> instead of next/image
@next/next/no-html-link-for-pages <a href="/about"> where <Link> belongs
@next/next/no-sync-scripts A blocking <script> tag

Treat warnings as work to do or rules to switch off on purpose (with a comment saying why), never as noise to ignore. A clean lint run is only useful if it stays clean.

Biome as an alternative

Biome is a single fast tool that both formats and lints JavaScript and TypeScript. create-next-app offers it as an alternative to ESLint (and Prettier), and you can add it by hand:

JSON
// biome.json (read-only)
{
  "$schema": "https://biomejs.dev/schemas/latest/schema.json",
  "linter": { "enabled": true, "rules": { "recommended": true } },
  "formatter": { "enabled": true, "indentStyle": "space" },
  "files": { "includes": ["**", "!.next", "!node_modules"] }
}
JSON
{
  "scripts": {
    "lint": "biome check",
    "format": "biome format --write"
  }
}

The trade-off is coverage. Biome is quicker and needs one config file, but ESLint has the larger plugin ecosystem and the Next.js-specific rules above. Many teams start with the default ESLint setup and move to Biome when the speed matters more than the extra rules. Either way, keep type checking separate: neither tool replaces tsc --noEmit or next build.

A reliable pre-merge routine is next typegen, then tsc --noEmit, then npm run lint, then next build. Typegen first means the generated route types exist even on a fresh CI checkout.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is params a Promise in current App Router page props?

    Since version 15, params and searchParams are asynchronous. You write const { slug } = await params, and the types reflect that.
  2. 2. What does PageProps<"/blog/[slug]"> give you?

    It is a globally available helper type generated from your folders. Renaming the folder makes stale usages a type error.
  3. 3. After enabling typedRoutes, <Link href="/blgo"> fails to compile. What made that possible?

    The check happens at type-check time. The generated route union is the only set of values href accepts.
  4. 4. In Next.js 16, which statement about linting is true?

    The next lint command was removed and next build no longer lints, so call the linter directly and add it to your CI steps.
  5. 5. Which line in tsconfig.json loads the editor plugin that understands Next.js conventions?

    The plugins entry enables the Next.js TypeScript language-service plugin. The other options control module resolution, per-file compilation and import aliases.

Summary

  • create-next-app sets up tsconfig.json with strict checks, bundler module resolution, the next editor plugin and an @/ alias; leave next-env.d.ts to Next.js.
  • Page, layout and route handler props are typed, and params/searchParams are promises. PageProps<"/route">, LayoutProps and RouteContext are generated from your folders; next typegen creates them on demand.
  • typedRoutes: true makes link and navigation targets type-checked against your real routes.
  • Template literal types can derive parameter types from a route string, which is the idea behind the generated helpers.
  • ESLint (eslint-config-next) or Biome catches habits types cannot; in version 16 you run the linter yourself and keep type checking, linting and building as separate CI steps.

Next: Testing Next.js Apps