Unverified Commit 03c8e5d0 authored by Ben Gubler's avatar Ben Gubler Committed by GitHub

feat: automatically generate route types (#81396)

## Overview
Generates `.next/types/routes.d.ts` file that provides typed route
definitions and global `PageProps`/`LayoutProps` types for App Router
components, eliminating the need for manual imports and providing full
type safety for routing.

## Generated Type Structure
```typescript
// Route union types
type AppRoutes = "/" | "/blog/[slug]" | "/dashboard/[...path]"
type LayoutRoutes = "/" | "/dashboard" 
type PageRoutes = never // for pages directory
type RedirectRoutes = "/old-path"
type RewriteRoutes = "/api/proxy/[...path]"

// Parameter mapping with full dynamic route support
type ParamMap = {
  "/": {}
  "/blog/[slug]": { "slug": string }
  "/dashboard/[[...path]]": { "path"?: string[] } // optional catch-all
  "/api/[...segments]": { "segments": string[] }  // required catch-all
}

// Parallel route slots for layouts
type LayoutSlotMap = {
  "/dashboard": "analytics" | "team"
  "/": never
}
```

## Usage Examples
```typescript
// Page component - no imports needed, full parameter typing
export default function BlogPost(props: PageProps<'/blog/[slug]'>) {
  const { slug } = await props.params // slug is typed as string
  const searchParams = await props.searchParams // Record<string, string | string[] | undefined>
  return <div>Post: {slug}</div>
}

// Layout with parallel routes - automatic slot typing
export default function DashboardLayout(props: LayoutProps<'/dashboard'>) {
  return (
    <div>
      {props.children}
      {props.analytics}  {/* Typed parallel route slot */}
      {props.team}       {/* Typed parallel route slot */}
    </div>
  )
}

// Catch-all routes with array parameters
export default function DocsPage(props: PageProps<'/docs/[...path]'>) {
  const { path } = await props.params // path is typed as string[]
  return <div>Docs path: {path.join('/')}</div>
}
```

## Key Features
- **Zero imports**: All types are globally available via declaration
merging
- **Route validation**: TypeScript ensures only valid routes can be used
- **Dynamic route support**: Full typing for `[param]`, `[...param]`,
and `[[...param]]` patterns
- **Parameter extraction**: Automatic typing of route parameters based
on file structure
- **Parallel routes**: Automatic slot typing for layouts with `@slot`
directories
- **Custom routes**: Support for `redirects` and `rewrites` from
`next.config.js`
- **IDE integration**: Full auto-completion for route paths and
parameters

## Route Discovery
The system automatically discovers routes from:
- **App Router**: `app/` directory structure with `page.tsx` and
`layout.tsx` files
- **Pages Router**: `pages/` directory structure (legacy support)
- **Redirects**: Custom redirects defined in `next.config.js`
- **Rewrites**: Custom rewrites defined in `next.config.js`
- **Parallel Routes**: `@slot` directories for layout composition
parent d87d80ae
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information. // see https://nextjs.org/docs/basic-features/typescript for more information.
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. // see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. // see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. // see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. // see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information. // see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information. // see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information. // see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information. // see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
...@@ -20,6 +20,7 @@ import type { NextLintOptions } from '../cli/next-lint.js' ...@@ -20,6 +20,7 @@ import type { NextLintOptions } from '../cli/next-lint.js'
import type { NextInfoOptions } from '../cli/next-info.js' import type { NextInfoOptions } from '../cli/next-info.js'
import type { NextDevOptions } from '../cli/next-dev.js' import type { NextDevOptions } from '../cli/next-dev.js'
import type { NextBuildOptions } from '../cli/next-build.js' import type { NextBuildOptions } from '../cli/next-build.js'
import type { NextTypegenOptions } from '../cli/next-typegen.js'
if (process.env.NEXT_RSPACK) { if (process.env.NEXT_RSPACK) {
// silent rspack's schema check // silent rspack's schema check
...@@ -382,6 +383,24 @@ program ...@@ -382,6 +383,24 @@ program
) )
) )
program
.command('typegen')
.description(
'Generate TypeScript definitions for routes, pages, and layouts without running a full build.'
)
.argument(
'[directory]',
`A directory on which to generate types. ${italic(
'If no directory is provided, the current directory will be used.'
)}`
)
.action((directory: string, options: NextTypegenOptions) =>
import('../cli/next-typegen.js').then((mod) =>
mod.nextTypegen(options, directory)
)
)
.usage('[directory] [options]')
program program
.command('experimental-test') .command('experimental-test')
.description( .description(
......
...@@ -75,6 +75,224 @@ import type { PageExtensions } from './page-extensions-type' ...@@ -75,6 +75,224 @@ import type { PageExtensions } from './page-extensions-type'
import type { MappedPages } from './build-context' import type { MappedPages } from './build-context'
import { PAGE_TYPES } from '../lib/page-types' import { PAGE_TYPES } from '../lib/page-types'
import { isAppPageRoute } from '../lib/is-app-page-route' import { isAppPageRoute } from '../lib/is-app-page-route'
import { recursiveReadDir } from '../lib/recursive-readdir'
import { createValidFileMatcher } from '../server/lib/find-page-file'
import { isReservedPage } from './utils'
import { isParallelRouteSegment } from '../shared/lib/segment'
import { ensureLeadingSlash } from '../shared/lib/page-path/ensure-leading-slash'
/**
* Collect app pages and layouts from the app directory
* @param appDir - The app directory path
* @param pageExtensions - The configured page extensions
* @param options - Optional configuration
* @returns Object containing appPaths and layoutPaths arrays
*/
export async function collectAppFiles(
appDir: string,
pageExtensions: PageExtensions
): Promise<{
appPaths: string[]
layoutPaths: string[]
}> {
const validFileMatcher = createValidFileMatcher(pageExtensions, appDir)
// Collect both app pages and layouts in a single directory traversal
const allAppFiles = await recursiveReadDir(appDir, {
pathnameFilter: (absolutePath) =>
validFileMatcher.isAppRouterPage(absolutePath) ||
validFileMatcher.isRootNotFound(absolutePath) ||
validFileMatcher.isAppLayoutPage(absolutePath),
ignorePartFilter: (part) => part.startsWith('_'),
})
// Separate app pages from layouts
const appPaths = allAppFiles.filter(
(absolutePath) =>
validFileMatcher.isAppRouterPage(absolutePath) ||
validFileMatcher.isRootNotFound(absolutePath)
)
const layoutPaths = allAppFiles.filter((absolutePath) =>
validFileMatcher.isAppLayoutPage(absolutePath)
)
return { appPaths, layoutPaths }
}
/**
* Collect pages from the pages directory
* @param pagesDir - The pages directory path
* @param pageExtensions - The configured page extensions
* @returns Array of page file paths
*/
export async function collectPagesFiles(
pagesDir: string,
pageExtensions: PageExtensions
): Promise<string[]> {
return recursiveReadDir(pagesDir, {
pathnameFilter: (absolutePath) => {
const relativePath = absolutePath.replace(pagesDir + '/', '')
return pageExtensions.some((ext) => relativePath.endsWith(`.${ext}`))
},
ignorePartFilter: (part) => part.startsWith('_'),
})
}
// Types for route processing
export type RouteInfo = {
route: string
filePath: string
}
export type SlotInfo = {
name: string
parent: string
}
/**
* Create a relative file path from a mapped page path
* @param baseDir - The base directory path
* @param filePath - The mapped file path (with private prefix)
* @param prefix - The directory prefix ('pages' or 'app')
* @returns The relative file path
*/
export function createRelativeFilePath(
baseDir: string,
filePath: string,
prefix: 'pages' | 'app'
): string {
const privatePrefix =
prefix === 'pages' ? 'private-next-pages' : 'private-next-app-dir'
return join(
baseDir,
filePath.replace(new RegExp(`^${privatePrefix}/`), `${prefix}/`)
)
}
/**
* Process pages routes from mapped pages
* @param mappedPages - The mapped pages object
* @param baseDir - The base directory path
* @returns Object containing pageRoutes and pageApiRoutes
*/
export function processPageRoutes(
mappedPages: { [page: string]: string },
baseDir: string
): {
pageRoutes: RouteInfo[]
pageApiRoutes: RouteInfo[]
} {
const pageRoutes: RouteInfo[] = []
const pageApiRoutes: RouteInfo[] = []
for (const [route, filePath] of Object.entries(mappedPages)) {
const relativeFilePath = createRelativeFilePath(baseDir, filePath, 'pages')
if (route.startsWith('/api/')) {
pageApiRoutes.push({
route: normalizePathSep(route),
filePath: relativeFilePath,
})
} else {
// Filter out _app, _error, _document
if (isReservedPage(route)) continue
pageRoutes.push({
route: normalizePathSep(route),
filePath: relativeFilePath,
})
}
}
return { pageRoutes, pageApiRoutes }
}
/**
* Extract slots from app routes
* @param mappedAppPages - The mapped app pages object
* @returns Array of slot information
*/
export function extractSlotsFromAppRoutes(mappedAppPages: {
[page: string]: string
}): SlotInfo[] {
const slots: SlotInfo[] = []
for (const [route] of Object.entries(mappedAppPages)) {
if (route === '/_not-found/page') continue
const segments = route.split('/')
for (let i = segments.length - 1; i >= 0; i--) {
const segment = segments[i]
if (isParallelRouteSegment(segment)) {
const parentPath = normalizeAppPath(segments.slice(0, i).join('/'))
const slotName = segment.slice(1)
// Check if the slot already exists
if (slots.some((s) => s.name === slotName && s.parent === parentPath))
continue
slots.push({
name: slotName,
parent: parentPath,
})
break
}
}
}
return slots
}
/**
* Process app routes from mapped app pages
* @param mappedAppPages - The mapped app pages object
* @param baseDir - The base directory path
* @returns Array of route information
*/
export function processAppRoutes(
mappedAppPages: { [page: string]: string },
baseDir: string
): RouteInfo[] {
const appRoutes: RouteInfo[] = []
for (const [route, filePath] of Object.entries(mappedAppPages)) {
if (route === '/_not-found/page') continue
const relativeFilePath = createRelativeFilePath(baseDir, filePath, 'app')
appRoutes.push({
route: normalizeAppPath(normalizePathSep(route)),
filePath: relativeFilePath,
})
}
return appRoutes
}
/**
* Process layout routes from mapped app layouts
* @param mappedAppLayouts - The mapped app layouts object
* @param baseDir - The base directory path
* @returns Array of layout route information
*/
export function processLayoutRoutes(
mappedAppLayouts: { [page: string]: string },
baseDir: string
): RouteInfo[] {
const layoutRoutes: RouteInfo[] = []
for (const [route, filePath] of Object.entries(mappedAppLayouts)) {
const relativeFilePath = createRelativeFilePath(baseDir, filePath, 'app')
layoutRoutes.push({
route: ensureLeadingSlash(
normalizeAppPath(normalizePathSep(route)).replace(/\/layout$/, '')
),
filePath: relativeFilePath,
})
}
return layoutRoutes
}
export function sortByPageExts(pageExtensions: PageExtensions) { export function sortByPageExts(pageExtensions: PageExtensions) {
return (a: string, b: string) => { return (a: string, b: string) => {
......
...@@ -108,8 +108,15 @@ import type { EventBuildFeatureUsage } from '../telemetry/events' ...@@ -108,8 +108,15 @@ import type { EventBuildFeatureUsage } from '../telemetry/events'
import { Telemetry } from '../telemetry/storage' import { Telemetry } from '../telemetry/storage'
import { import {
createPagesMapping, createPagesMapping,
collectAppFiles,
getStaticInfoIncludingLayouts, getStaticInfoIncludingLayouts,
sortByPageExts, sortByPageExts,
processPageRoutes,
processAppRoutes,
processLayoutRoutes,
extractSlotsFromAppRoutes,
type RouteInfo,
type SlotInfo,
} from './entries' } from './entries'
import { PAGE_TYPES } from '../lib/page-types' import { PAGE_TYPES } from '../lib/page-types'
import { generateBuildId } from './generate-build-id' import { generateBuildId } from './generate-build-id'
...@@ -211,6 +218,10 @@ import { ...@@ -211,6 +218,10 @@ import {
sortPages, sortPages,
sortSortableRouteObjects, sortSortableRouteObjects,
} from '../shared/lib/router/utils/sortable-routes' } from '../shared/lib/router/utils/sortable-routes'
import {
createRouteTypesManifest,
writeRouteTypesManifest,
} from '../server/lib/router-utils/route-types-utils'
type Fallback = null | boolean | string type Fallback = null | boolean | string
...@@ -1113,12 +1124,6 @@ export default async function build( ...@@ -1113,12 +1124,6 @@ export default async function build(
await recursiveDelete(distDir, /^cache/) await recursiveDelete(distDir, /^cache/)
} }
// For app directory, we run type checking after build. That's because
// we dynamically generate types for each layout and page in the app
// directory.
if (!appDir && !isCompileMode)
await startTypeChecking(typeCheckingOptions)
if (appDir && 'exportPathMap' in config) { if (appDir && 'exportPathMap' in config) {
Log.error( Log.error(
'The "exportPathMap" configuration cannot be used with the "app" directory. Please use generateStaticParams() instead.' 'The "exportPathMap" configuration cannot be used with the "app" directory. Please use generateStaticParams() instead.'
...@@ -1206,6 +1211,7 @@ export default async function build( ...@@ -1206,6 +1211,7 @@ export default async function build(
NextBuildContext.mappedPages = mappedPages NextBuildContext.mappedPages = mappedPages
let mappedAppPages: MappedPages | undefined let mappedAppPages: MappedPages | undefined
let mappedAppLayouts: MappedPages | undefined
let denormalizedAppPages: string[] | undefined let denormalizedAppPages: string[] | undefined
if (appDir) { if (appDir) {
...@@ -1213,20 +1219,21 @@ export default async function build( ...@@ -1213,20 +1219,21 @@ export default async function build(
process.env.NEXT_PRIVATE_APP_PATHS || '[]' process.env.NEXT_PRIVATE_APP_PATHS || '[]'
) )
let appPaths = Boolean(process.env.NEXT_PRIVATE_APP_PATHS) let appPaths: string[]
? providedAppPaths let layoutPaths: string[]
: await nextBuildSpan
.traceChild('collect-app-paths') if (Boolean(process.env.NEXT_PRIVATE_APP_PATHS)) {
.traceAsyncFn(() => appPaths = providedAppPaths
recursiveReadDir(appDir, { layoutPaths = []
pathnameFilter: (absolutePath) => } else {
validFileMatcher.isAppRouterPage(absolutePath) || // Collect both app pages and layouts in a single directory traversal
// For now we only collect the root /not-found page in the app const result = await nextBuildSpan
// directory as the 404 fallback .traceChild('collect-app-files')
validFileMatcher.isRootNotFound(absolutePath), .traceAsyncFn(() => collectAppFiles(appDir, config.pageExtensions))
ignorePartFilter: (part) => part.startsWith('_'),
}) appPaths = result.appPaths
) layoutPaths = result.layoutPaths
}
mappedAppPages = await nextBuildSpan mappedAppPages = await nextBuildSpan
.traceChild('create-app-mapping') .traceChild('create-app-mapping')
...@@ -1241,6 +1248,19 @@ export default async function build( ...@@ -1241,6 +1248,19 @@ export default async function build(
}) })
) )
mappedAppLayouts = await nextBuildSpan
.traceChild('create-app-layouts')
.traceAsyncFn(() =>
createPagesMapping({
pagePaths: layoutPaths,
isDev: false,
pagesType: PAGE_TYPES.APP,
pageExtensions: config.pageExtensions,
pagesDir,
appDir,
})
)
NextBuildContext.mappedAppPages = mappedAppPages NextBuildContext.mappedAppPages = mappedAppPages
} }
...@@ -1289,6 +1309,49 @@ export default async function build( ...@@ -1289,6 +1309,49 @@ export default async function build(
app: appPaths.length > 0 ? appPaths : undefined, app: appPaths.length > 0 ? appPaths : undefined,
} }
await nextBuildSpan
.traceChild('generate-route-types')
.traceAsyncFn(async () => {
const routeTypesFilePath = path.join(distDir, 'types', 'routes.d.ts')
await fs.mkdir(path.dirname(routeTypesFilePath), { recursive: true })
let pageRoutes: RouteInfo[] = []
let appRoutes: RouteInfo[] = []
let layoutRoutes: RouteInfo[] = []
let slots: SlotInfo[] = []
// Build pages routes
const processedPages = processPageRoutes(mappedPages, dir)
// We combine both page routes and API routes
pageRoutes = [
...processedPages.pageRoutes,
...processedPages.pageApiRoutes,
]
// Build app routes
if (appDir && mappedAppPages) {
slots = extractSlotsFromAppRoutes(mappedAppPages)
appRoutes = processAppRoutes(mappedAppPages, dir)
}
// Build app layouts
if (appDir && mappedAppLayouts) {
layoutRoutes = processLayoutRoutes(mappedAppLayouts, dir)
}
const routeTypesManifest = await createRouteTypesManifest({
dir,
pageRoutes,
appRoutes,
layoutRoutes,
slots,
redirects: config.redirects,
rewrites: config.rewrites,
})
await writeRouteTypesManifest(routeTypesManifest, routeTypesFilePath)
})
// Turbopack already handles conflicting app and page routes. // Turbopack already handles conflicting app and page routes.
if (!isTurbopack) { if (!isTurbopack) {
const numConflictingAppPaths = conflictingAppPagePaths.length const numConflictingAppPaths = conflictingAppPagePaths.length
...@@ -1461,6 +1524,11 @@ export default async function build( ...@@ -1461,6 +1524,11 @@ export default async function build(
} satisfies RoutesManifest } satisfies RoutesManifest
}) })
// For pages directory, we run type checking after route collection but before build.
if (!appDir && !isCompileMode) {
await startTypeChecking(typeCheckingOptions)
}
let clientRouterFilters: let clientRouterFilters:
| undefined | undefined
| ReturnType<typeof createClientRouterFilter> | ReturnType<typeof createClientRouterFilter>
......
#!/usr/bin/env node
import { existsSync } from 'fs'
import { join } from 'path'
import { mkdir } from 'fs/promises'
import loadConfig from '../server/config'
import { printAndExit } from '../server/lib/utils'
import { PHASE_PRODUCTION_BUILD } from '../shared/lib/constants'
import { getProjectDir } from '../lib/get-project-dir'
import { findPagesDir } from '../lib/find-pages-dir'
import { verifyTypeScriptSetup } from '../lib/verify-typescript-setup'
import {
createPagesMapping,
collectAppFiles,
collectPagesFiles,
processPageRoutes,
processAppRoutes,
processLayoutRoutes,
extractSlotsFromAppRoutes,
type RouteInfo,
type SlotInfo,
} from '../build/entries'
import { PAGE_TYPES } from '../lib/page-types'
import {
createRouteTypesManifest,
writeRouteTypesManifest,
} from '../server/lib/router-utils/route-types-utils'
export type NextTypegenOptions = {
dir?: string
}
const nextTypegen = async (
_options: NextTypegenOptions,
directory?: string
) => {
const baseDir = getProjectDir(directory)
// Check if the provided directory exists
if (!existsSync(baseDir)) {
printAndExit(`> No such directory exists as the project root: ${baseDir}`)
}
const nextConfig = await loadConfig(PHASE_PRODUCTION_BUILD, baseDir)
const distDir = join(baseDir, nextConfig.distDir)
const { pagesDir, appDir } = findPagesDir(baseDir)
await verifyTypeScriptSetup({
dir: baseDir,
distDir: nextConfig.distDir,
intentDirs: [pagesDir, appDir].filter(Boolean) as string[],
typeCheckPreflight: false,
tsconfigPath: nextConfig.typescript.tsconfigPath,
disableStaticImages: nextConfig.images.disableStaticImages,
hasAppDir: !!appDir,
hasPagesDir: !!pagesDir,
})
console.log('Generating route types...')
const routeTypesFilePath = join(distDir, 'types', 'routes.d.ts')
await mkdir(join(distDir, 'types'), { recursive: true })
let pageRoutes: RouteInfo[] = []
let appRoutes: RouteInfo[] = []
let layoutRoutes: RouteInfo[] = []
let slots: SlotInfo[] = []
let _pageApiRoutes: RouteInfo[] = []
let mappedPages: { [page: string]: string } = {}
let mappedAppPages: { [page: string]: string } = {}
let mappedAppLayouts: { [page: string]: string } = {}
// Helper function to reduce createPagesMapping duplication
const createMapping = (pagePaths: string[], pagesType: any) =>
createPagesMapping({
pagePaths,
isDev: false,
pagesType,
pageExtensions: nextConfig.pageExtensions,
pagesDir,
appDir,
})
// Build pages routes
if (pagesDir) {
const pagePaths = await collectPagesFiles(
pagesDir,
nextConfig.pageExtensions
)
mappedPages = await createMapping(pagePaths, PAGE_TYPES.PAGES)
// Process pages routes
const processedPages = processPageRoutes(mappedPages, baseDir)
pageRoutes = processedPages.pageRoutes
_pageApiRoutes = processedPages.pageApiRoutes
}
// Build app routes
if (appDir) {
// Collect both app pages and layouts in a single directory traversal
const { appPaths, layoutPaths } = await collectAppFiles(
appDir,
nextConfig.pageExtensions
)
mappedAppPages = await createMapping(appPaths, PAGE_TYPES.APP)
mappedAppLayouts = await createMapping(layoutPaths, PAGE_TYPES.APP)
// Process app routes and extract slots
slots = extractSlotsFromAppRoutes(mappedAppPages)
appRoutes = processAppRoutes(mappedAppPages, baseDir)
// Process layout routes
layoutRoutes = processLayoutRoutes(mappedAppLayouts, baseDir)
}
const routeTypesManifest = await createRouteTypesManifest({
dir: baseDir,
pageRoutes,
appRoutes,
layoutRoutes,
slots,
redirects: nextConfig.redirects,
rewrites: nextConfig.rewrites,
})
await writeRouteTypesManifest(routeTypesManifest, routeTypesFilePath)
console.log('✓ Route types generated successfully')
}
export { nextTypegen }
...@@ -4,11 +4,13 @@ import { promises as fs } from 'fs' ...@@ -4,11 +4,13 @@ import { promises as fs } from 'fs'
export async function writeAppTypeDeclarations({ export async function writeAppTypeDeclarations({
baseDir, baseDir,
distDir,
imageImportsEnabled, imageImportsEnabled,
hasPagesDir, hasPagesDir,
hasAppDir, hasAppDir,
}: { }: {
baseDir: string baseDir: string
distDir: string
imageImportsEnabled: boolean imageImportsEnabled: boolean
hasPagesDir: boolean hasPagesDir: boolean
hasAppDir: boolean hasAppDir: boolean
...@@ -55,6 +57,13 @@ export async function writeAppTypeDeclarations({ ...@@ -55,6 +57,13 @@ export async function writeAppTypeDeclarations({
) )
} }
const routeTypesPath = path.posix.join(
distDir.replaceAll(path.win32.sep, path.posix.sep),
'types/routes.d.ts'
)
directives.push(`/// <reference path="./${routeTypesPath}" />`)
// Push the notice in. // Push the notice in.
directives.push( directives.push(
'', '',
......
...@@ -129,6 +129,7 @@ export async function verifyTypeScriptSetup({ ...@@ -129,6 +129,7 @@ export async function verifyTypeScriptSetup({
// Next.js' types: // Next.js' types:
await writeAppTypeDeclarations({ await writeAppTypeDeclarations({
baseDir: dir, baseDir: dir,
distDir,
imageImportsEnabled: !disableStaticImages, imageImportsEnabled: !disableStaticImages,
hasPagesDir, hasPagesDir,
hasAppDir, hasAppDir,
......
...@@ -90,6 +90,9 @@ export function createValidFileMatcher( ...@@ -90,6 +90,9 @@ export function createValidFileMatcher(
pageExtensions pageExtensions
)}$` )}$`
) )
const leafOnlyLayoutFileRegex = new RegExp(
`(^(layout)|[\\\\/](layout))\\.${getExtensionRegexString(pageExtensions)}$`
)
const rootNotFoundFileRegex = new RegExp( const rootNotFoundFileRegex = new RegExp(
`^not-found\\.${getExtensionRegexString(pageExtensions)}$` `^not-found\\.${getExtensionRegexString(pageExtensions)}$`
) )
...@@ -123,6 +126,10 @@ export function createValidFileMatcher( ...@@ -123,6 +126,10 @@ export function createValidFileMatcher(
return leafOnlyPageFileRegex.test(filePath) || isMetadataFile(filePath) return leafOnlyPageFileRegex.test(filePath) || isMetadataFile(filePath)
} }
function isAppLayoutPage(filePath: string) {
return leafOnlyLayoutFileRegex.test(filePath)
}
function isPageFile(filePath: string) { function isPageFile(filePath: string) {
return validExtensionFileRegex.test(filePath) || isMetadataFile(filePath) return validExtensionFileRegex.test(filePath) || isMetadataFile(filePath)
} }
...@@ -141,6 +148,7 @@ export function createValidFileMatcher( ...@@ -141,6 +148,7 @@ export function createValidFileMatcher(
return { return {
isPageFile, isPageFile,
isAppRouterPage, isAppRouterPage,
isAppLayoutPage,
isMetadataFile, isMetadataFile,
isRootNotFound, isRootNotFound,
} }
......
import path from 'path'
import {
getRouteRegex,
type Group,
} from '../../../shared/lib/router/utils/route-regex'
import type { NextConfigComplete } from '../../config-shared'
import { isParallelRouteSegment } from '../../../shared/lib/segment'
import fs from 'fs'
import { generateRouteTypesFile } from './typegen'
import { tryToParsePath } from '../../../lib/try-to-parse-path'
interface RouteInfo {
path: string
groups: { [groupName: string]: Group }
}
export interface RouteTypesManifest {
appRoutes: Record<string, RouteInfo>
pageRoutes: Record<string, RouteInfo>
layoutRoutes: Record<string, RouteInfo & { slots: string[] }>
/** Map of redirect source => RouteInfo */
redirectRoutes: Record<string, RouteInfo>
/** Map of rewrite source => RouteInfo */
rewriteRoutes: Record<string, RouteInfo>
}
// Convert a custom-route source string (`/blog/:slug`, `/docs/:path*`, ...)
// into the bracket-syntax used by other Next.js route helpers so that we can
// reuse `getRouteRegex()` to extract groups.
export function convertCustomRouteSource(source: string): string {
const parseResult = tryToParsePath(source)
if (parseResult.error || !parseResult.tokens) {
// Fallback to original source if parsing fails
return source.startsWith('/') ? source : '/' + source
}
let result = ''
for (const token of parseResult.tokens) {
if (typeof token === 'string') {
// Literal path segment
result += token
} else {
// Parameter token
const { name, modifier, prefix } = token
// Add the prefix (usually '/')
result += prefix
if (modifier === '*') {
// Catch-all zero or more: :param* -> [[...param]]
result += `[[...${name}]]`
} else if (modifier === '+') {
// Catch-all one or more: :param+ -> [...param]
result += `[...${name}]`
} else if (modifier === '?') {
// Optional catch-all: :param? -> [[...param]]
result += `[[...${name}]]`
} else {
// Standard dynamic segment: :param -> [param]
result += `[${name}]`
}
}
}
// Ensure leading slash
if (!result.startsWith('/')) result = '/' + result
return result
}
/**
* Extracts route parameters from a route pattern
*/
export function extractRouteParams(route: string) {
const regex = getRouteRegex(route)
return regex.groups
}
function isCanonicalRoute(route: string) {
const segments = route.split('/')
for (let i = segments.length - 1; i >= 0; i--) {
const segment = segments[i]
if (
isParallelRouteSegment(segment) ||
segment.startsWith('(.)') ||
segment.startsWith('(..)') ||
segment.startsWith('(...)')
) {
return false
}
}
return true
}
/**
* Creates a route types manifest from processed route data
* (used for both build and dev)
*/
export async function createRouteTypesManifest({
dir,
pageRoutes,
appRoutes,
layoutRoutes,
slots,
redirects,
rewrites,
}: {
dir: string
pageRoutes: Array<{ route: string; filePath: string }>
appRoutes: Array<{ route: string; filePath: string }>
layoutRoutes: Array<{ route: string; filePath: string }>
slots: Array<{ name: string; parent: string }>
redirects?: NextConfigComplete['redirects']
rewrites?: NextConfigComplete['rewrites']
}): Promise<RouteTypesManifest> {
const manifest: RouteTypesManifest = {
appRoutes: {},
pageRoutes: {},
layoutRoutes: {},
redirectRoutes: {},
rewriteRoutes: {},
}
// Process page routes
for (const { route, filePath } of pageRoutes) {
manifest.pageRoutes[route] = {
path: path.relative(dir, filePath),
groups: extractRouteParams(route),
}
}
// Process layout routes
for (const { route, filePath } of layoutRoutes) {
if (!isCanonicalRoute(route)) continue
manifest.layoutRoutes[route] = {
path: path.relative(dir, filePath),
groups: extractRouteParams(route),
slots: [],
}
}
// Process slots
for (const slot of slots) {
if (manifest.layoutRoutes[slot.parent]) {
manifest.layoutRoutes[slot.parent].slots.push(slot.name)
}
}
// Process app routes
for (const { route, filePath } of appRoutes) {
if (!isCanonicalRoute(route)) continue
manifest.appRoutes[route] = {
path: path.relative(dir, filePath),
groups: extractRouteParams(route),
}
}
// Process redirects
if (typeof redirects === 'function') {
const rd = await redirects()
for (const item of rd) {
const source = convertCustomRouteSource(item.source)
manifest.redirectRoutes[source] = {
path: source,
groups: extractRouteParams(source),
}
}
}
// Process rewrites
if (typeof rewrites === 'function') {
const rw = await rewrites()
const allSources = Array.isArray(rw)
? rw
: [
...(rw?.beforeFiles || []),
...(rw?.afterFiles || []),
...(rw?.fallback || []),
]
for (const item of allSources) {
const source = convertCustomRouteSource(item.source)
manifest.rewriteRoutes[source] = {
path: source,
groups: extractRouteParams(source),
}
}
}
return manifest
}
export async function writeRouteTypesManifest(
manifest: RouteTypesManifest,
filePath: string
) {
const dirname = path.dirname(filePath)
if (!fs.existsSync(dirname)) {
await fs.promises.mkdir(dirname, { recursive: true })
}
await fs.promises.writeFile(filePath, generateRouteTypesFile(manifest))
}
...@@ -12,7 +12,6 @@ import type { NextJsHotReloaderInterface } from '../../dev/hot-reloader-types' ...@@ -12,7 +12,6 @@ import type { NextJsHotReloaderInterface } from '../../dev/hot-reloader-types'
import { createDefineEnv } from '../../../build/swc' import { createDefineEnv } from '../../../build/swc'
import fs from 'fs' import fs from 'fs'
import { mkdir } from 'fs/promises'
import url from 'url' import url from 'url'
import path from 'path' import path from 'path'
import qs from 'querystring' import qs from 'querystring'
...@@ -85,6 +84,12 @@ import { getDefineEnv } from '../../../build/define-env' ...@@ -85,6 +84,12 @@ import { getDefineEnv } from '../../../build/define-env'
import { TurbopackInternalError } from '../../../shared/lib/turbopack/internal-error' import { TurbopackInternalError } from '../../../shared/lib/turbopack/internal-error'
import { normalizePath } from '../../../lib/normalize-path' import { normalizePath } from '../../../lib/normalize-path'
import { JSON_CONTENT_TYPE_HEADER } from '../../../lib/constants' import { JSON_CONTENT_TYPE_HEADER } from '../../../lib/constants'
import {
createRouteTypesManifest,
writeRouteTypesManifest,
} from './route-types-utils'
import { isParallelRouteSegment } from '../../../shared/lib/segment'
import { ensureLeadingSlash } from '../../../shared/lib/page-path/ensure-leading-slash'
export type SetupOpts = { export type SetupOpts = {
renderServer: LazyRenderServerInstance renderServer: LazyRenderServerInstance
...@@ -167,18 +172,9 @@ async function startWatcher( ...@@ -167,18 +172,9 @@ async function startWatcher(
) { ) {
const { nextConfig, appDir, pagesDir, dir, resetFetch } = opts const { nextConfig, appDir, pagesDir, dir, resetFetch } = opts
const { useFileSystemPublicRoutes } = nextConfig const { useFileSystemPublicRoutes } = nextConfig
const usingTypeScript = await verifyTypeScript(opts)
const distDir = path.join(opts.dir, opts.nextConfig.distDir) const distDir = path.join(opts.dir, opts.nextConfig.distDir)
// we ensure the types directory exists here
if (usingTypeScript) {
const distTypesDir = path.join(distDir, 'types')
if (!fs.existsSync(distTypesDir)) {
await mkdir(distTypesDir, { recursive: true })
}
}
setGlobal('distDir', distDir) setGlobal('distDir', distDir)
setGlobal('phase', PHASE_DEVELOPMENT_SERVER) setGlobal('phase', PHASE_DEVELOPMENT_SERVER)
...@@ -217,6 +213,20 @@ async function startWatcher( ...@@ -217,6 +213,20 @@ async function startWatcher(
// have to write this after starting hot-reloader since that // have to write this after starting hot-reloader since that
// cleans the dist dir // cleans the dist dir
const distTypesDir = path.join(distDir, 'types')
await writeRouteTypesManifest(
{
appRoutes: {},
pageRoutes: {},
layoutRoutes: {},
redirectRoutes: {},
rewriteRoutes: {},
},
path.join(distTypesDir, 'routes.d.ts')
)
const usingTypeScript = await verifyTypeScript(opts)
const routesManifestPath = path.join(distDir, ROUTES_MANIFEST) const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)
const routesManifest: DevRoutesManifest = { const routesManifest: DevRoutesManifest = {
version: 3, version: 3,
...@@ -323,6 +333,8 @@ async function startWatcher( ...@@ -323,6 +333,8 @@ async function startWatcher(
let previousClientRouterFilters: any let previousClientRouterFilters: any
let previousConflictingPagePaths: Set<string> = new Set() let previousConflictingPagePaths: Set<string> = new Set()
const routeTypesFilePath = path.join(distDir, 'types', 'routes.d.ts')
wp.on('aggregated', async () => { wp.on('aggregated', async () => {
let middlewareMatchers: MiddlewareMatcher[] | undefined let middlewareMatchers: MiddlewareMatcher[] | undefined
const routedPages: string[] = [] const routedPages: string[] = []
...@@ -333,6 +345,11 @@ async function startWatcher( ...@@ -333,6 +345,11 @@ async function startWatcher(
const appPageFilePaths = new Map<string, string>() const appPageFilePaths = new Map<string, string>()
const pagesPageFilePaths = new Map<string, string>() const pagesPageFilePaths = new Map<string, string>()
const pageRoutes: Array<{ route: string; filePath: string }> = []
const appRoutes: Array<{ route: string; filePath: string }> = []
const layoutRoutes: Array<{ route: string; filePath: string }> = []
const slots: Array<{ name: string; parent: string }> = []
let envChange = false let envChange = false
let tsconfigChange = false let tsconfigChange = false
let conflictingPageChange = 0 let conflictingPageChange = 0
...@@ -504,14 +521,57 @@ async function startWatcher( ...@@ -504,14 +521,57 @@ async function startWatcher(
if (isRootNotFound) { if (isRootNotFound) {
continue continue
} }
if (!isRootNotFound && !validFileMatcher.isAppRouterPage(fileName)) {
continue
}
// Ignore files/directories starting with `_` in the app directory // Ignore files/directories starting with `_` in the app directory
if (normalizePathSep(pageName).includes('/_')) { if (normalizePathSep(pageName).includes('/_')) {
continue continue
} }
// Record parallel route slots for layout typing
// May run multiple times (e.g. if a parallel route
// has both a layout and a page, and children) but that's fine
const segments = normalizePathSep(pageName).split('/')
for (let i = segments.length - 1; i >= 0; i--) {
const segment = segments[i]
if (isParallelRouteSegment(segment)) {
const parentPath = normalizeAppPath(
segments.slice(0, i).join('/')
)
const slotName = segment.slice(1)
// check if the slot already exists
if (
slots.some(
(s) => s.name === slotName && s.parent === parentPath
)
)
continue
slots.push({
name: slotName,
parent: parentPath,
})
break
}
}
// Record layouts
if (validFileMatcher.isAppLayoutPage(fileName)) {
layoutRoutes.push({
route: ensureLeadingSlash(
normalizeAppPath(normalizePathSep(pageName)).replace(
/\/layout$/,
''
)
),
filePath: fileName,
})
}
if (!validFileMatcher.isAppRouterPage(fileName)) {
continue
}
const originalPageName = pageName const originalPageName = pageName
pageName = normalizeAppPath(pageName).replace(/%5F/g, '_') pageName = normalizeAppPath(pageName).replace(/%5F/g, '_')
if (!appPaths[pageName]) { if (!appPaths[pageName]) {
...@@ -528,6 +588,11 @@ async function startWatcher( ...@@ -528,6 +588,11 @@ async function startWatcher(
appFiles.add(pageName) appFiles.add(pageName)
} }
appRoutes.push({
route: normalizePathSep(pageName),
filePath: fileName,
})
if (routedPages.includes(pageName)) { if (routedPages.includes(pageName)) {
continue continue
} }
...@@ -538,11 +603,19 @@ async function startWatcher( ...@@ -538,11 +603,19 @@ async function startWatcher(
// entries that actually use getStaticProps/getServerSideProps // entries that actually use getStaticProps/getServerSideProps
opts.fsChecker.nextDataRoutes.add(pageName) opts.fsChecker.nextDataRoutes.add(pageName)
} }
pageRoutes.push({
route: normalizePathSep(pageName),
filePath: fileName,
})
}
// Record pages
if (isAppPath) {
appPageFilePaths.set(pageName, fileName)
} else {
pagesPageFilePaths.set(pageName, fileName)
} }
;(isAppPath ? appPageFilePaths : pagesPageFilePaths).set(
pageName,
fileName
)
if (appDir && pageNameSet.has(pageName)) { if (appDir && pageNameSet.has(pageName)) {
conflictingAppPagePaths.add(pageName) conflictingAppPagePaths.add(pageName)
...@@ -939,6 +1012,20 @@ async function startWatcher( ...@@ -939,6 +1012,20 @@ async function startWatcher(
} }
prevSortedRoutes = sortedRoutes prevSortedRoutes = sortedRoutes
if (usingTypeScript) {
const routeTypesManifest = await createRouteTypesManifest({
dir,
pageRoutes,
appRoutes,
layoutRoutes,
slots,
redirects: opts.nextConfig.redirects,
rewrites: opts.nextConfig.rewrites,
})
await writeRouteTypesManifest(routeTypesManifest, routeTypesFilePath)
}
if (!resolved) { if (!resolved) {
resolve() resolve()
resolved = true resolved = true
......
import type { RouteTypesManifest } from './route-types-utils'
import { isDynamicRoute } from '../../../shared/lib/router/utils/is-dynamic'
function generateRouteTypes(routesManifest: RouteTypesManifest): string {
const appRoutes = Object.keys(routesManifest.appRoutes).sort()
const pageRoutes = Object.keys(routesManifest.pageRoutes).sort()
const layoutRoutes = Object.keys(routesManifest.layoutRoutes).sort()
const redirectRoutes = Object.keys(routesManifest.redirectRoutes).sort()
const rewriteRoutes = Object.keys(routesManifest.rewriteRoutes).sort()
let result = ''
// Generate AppRoutes union type
if (appRoutes.length > 0) {
result += `type AppRoutes = ${appRoutes.map((route) => JSON.stringify(route)).join(' | ')}\n`
} else {
result += 'type AppRoutes = never\n'
}
// Generate PageRoutes union type
if (pageRoutes.length > 0) {
result += `type PageRoutes = ${pageRoutes.map((route) => JSON.stringify(route)).join(' | ')}\n`
} else {
result += 'type PageRoutes = never\n'
}
// Generate LayoutRoutes union type
if (layoutRoutes.length > 0) {
result += `type LayoutRoutes = ${layoutRoutes.map((route) => JSON.stringify(route)).join(' | ')}\n`
} else {
result += 'type LayoutRoutes = never\n'
}
// Generate RedirectRoutes union type
if (redirectRoutes.length > 0) {
result += `type RedirectRoutes = ${redirectRoutes
.map((route) => JSON.stringify(route))
.join(' | ')}\n`
} else {
result += 'type RedirectRoutes = never\n'
}
// Generate RewriteRoutes union type
if (rewriteRoutes.length > 0) {
result += `type RewriteRoutes = ${rewriteRoutes
.map((route) => JSON.stringify(route))
.join(' | ')}\n`
} else {
result += 'type RewriteRoutes = never\n'
}
result +=
'type Routes = AppRoutes | PageRoutes | LayoutRoutes | RedirectRoutes | RewriteRoutes\n'
return result
}
function generateParamTypes(routesManifest: RouteTypesManifest): string {
const allRoutes = {
...routesManifest.appRoutes,
...routesManifest.pageRoutes,
...routesManifest.layoutRoutes,
...routesManifest.redirectRoutes,
...routesManifest.rewriteRoutes,
}
let paramTypes = 'interface ParamMap {\n'
// Sort routes deterministically for consistent output
const sortedRoutes = Object.entries(allRoutes).sort(([a], [b]) =>
a.localeCompare(b)
)
for (const [route, routeInfo] of sortedRoutes) {
const { groups } = routeInfo
// For static routes (no dynamic segments), we can produce an empty parameter map.
if (!isDynamicRoute(route) || Object.keys(groups ?? {}).length === 0) {
paramTypes += ` ${JSON.stringify(route)}: {}\n`
continue
}
let paramType = '{'
// Process each group based on its properties
for (const [key, group] of Object.entries(groups)) {
const escapedKey = JSON.stringify(key)
if (group.repeat) {
// Catch-all parameters
if (group.optional) {
paramType += ` ${escapedKey}?: string[];`
} else {
paramType += ` ${escapedKey}: string[];`
}
} else {
// Regular parameters
if (group.optional) {
paramType += ` ${escapedKey}?: string;`
} else {
paramType += ` ${escapedKey}: string;`
}
}
}
paramType += ' }'
paramTypes += ` ${JSON.stringify(route)}: ${paramType}\n`
}
paramTypes += '}\n'
return paramTypes
}
function generateLayoutSlotMap(routesManifest: RouteTypesManifest): string {
let slotMap = 'interface LayoutSlotMap {\n'
// Sort routes deterministically for consistent output
const sortedLayoutRoutes = Object.entries(routesManifest.layoutRoutes).sort(
([a], [b]) => a.localeCompare(b)
)
for (const [route, routeInfo] of sortedLayoutRoutes) {
if ('slots' in routeInfo) {
const slots = routeInfo.slots.sort()
if (slots.length > 0) {
slotMap += ` ${JSON.stringify(route)}: ${slots.map((slot) => JSON.stringify(slot)).join(' | ')}\n`
} else {
slotMap += ` ${JSON.stringify(route)}: never\n`
}
} else {
slotMap += ` ${JSON.stringify(route)}: never\n`
}
}
slotMap += '}\n'
return slotMap
}
export function generateRouteTypesFile(
routesManifest: RouteTypesManifest
): string {
const routeTypes = generateRouteTypes(routesManifest)
const paramTypes = generateParamTypes(routesManifest)
const layoutSlotMap = generateLayoutSlotMap(routesManifest)
return `// This file is generated automatically by Next.js
// Do not edit this file manually
${routeTypes}
${paramTypes}
export type ParamsOf<Route extends Routes> = ParamMap[Route]
${layoutSlotMap}
export type { AppRoutes, PageRoutes, LayoutRoutes, RedirectRoutes, RewriteRoutes }
declare global {
/**
* Props for Next.js App Router page components
* @example
* \`\`\`tsx
* export default function Page(props: PageProps<'/blog/[slug]'>) {
* const { slug } = await props.params
* return <div>Blog post: {slug}</div>
* }
* \`\`\`
*/
interface PageProps<AppRoute extends AppRoutes> {
params: Promise<ParamMap[AppRoute]>
searchParams: Promise<Record<string, string | string[] | undefined>>
}
/**
* Props for Next.js App Router layout components
* @example
* \`\`\`tsx
* export default function Layout(props: LayoutProps<'/dashboard'>) {
* return <div>{props.children}</div>
* }
* \`\`\`
*/
type LayoutProps<LayoutRoute extends LayoutRoutes> = {
params: Promise<ParamMap[LayoutRoute]>
children: React.ReactNode
} & {
[K in LayoutSlotMap[LayoutRoute]]: React.ReactNode
}
}
`
}
export default async function Page(props: PageProps<'/_shop/[[...category]]'>) {
const { category } = await props.params
return <p>shop {category?.join('/')}</p>
}
export default function Layout({ children }: LayoutProps<'/'>) {
return <div>{children}</div>
}
export default async function Page(props: PageProps<'/project/[slug]'>) {
const { slug } = await props.params
return <p>project {slug}</p>
}
export default function Page() {
return <div>hidden</div>
}
export default function Page(props: PageProps<'/dashboard'>) {
return <p>analytics</p>
}
export default function Page(props: PageProps<'/dashboard/settings'>) {
return <p>analytics settings</p>
}
export default function Page(props: PageProps<'/dashboard'>) {
return <p>team</p>
}
export default function Page(props: PageProps<'/dashboard/settings'>) {
return <p>team settings</p>
}
export default async function Layout(props: LayoutProps<'/dashboard'>) {
const { analytics, team, children } = props
return (
<div>
<div>dashboard layout</div>
<div>{analytics}</div>
<div>{team}</div>
<div>{children}</div>
</div>
)
}
export default function Page(props: PageProps<'/dashboard'>) {
return <p>analytics</p>
}
export default function Page(props: PageProps<'/dashboard/settings'>) {
return <p>dashboard settings</p>
}
export default async function Page(props: PageProps<'/docs/[...slug]'>) {
const { slug } = await props.params
return <p>docs {slug.join('/')}</p>
}
export default async function Page(props: PageProps<'/gallery/photo/[id]'>) {
const { id } = await props.params
return <p>photo {id}</p>
}
export default async function Page(props: PageProps<'/gallery/photo/[id]'>) {
const { id } = await props.params
return <p>intercepted photo {id}</p>
}
import { Suspense } from 'react'
export default function Root(props: LayoutProps<'/'>) {
return (
<html>
<body>
<Suspense>{props.children}</Suspense>
</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
/* eslint-disable @typescript-eslint/no-unused-vars */
type ValidPage = PageProps<'/dashboard'>
// type InvalidPage = PageProps<'/dasboard'>
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
async redirects() {
return [
{
source: '/project/:slug',
destination: '/project/:slug',
permanent: true,
},
{
source: '/blog/:category/:slug*',
destination: '/posts/:category/:slug*',
permanent: false,
},
{
source: '/optional/:param?',
destination: '/fallback',
permanent: false,
},
]
},
async rewrites() {
return {
beforeFiles: [],
afterFiles: [
{
source: '/docs-old/:path+',
destination: '/docs/:path+',
},
{
source: '/api-legacy/:version/:endpoint*',
destination: '/api/:version/:endpoint*',
},
],
fallback: [],
}
},
}
module.exports = nextConfig
export default function AboutPage() {
return <div>About Page</div>
}
export default function UserPage({ id }: { id: string }) {
return <div>User: {id}</div>
}
export async function getServerSideProps({ query }: { query: { id: string } }) {
return {
props: {
id: query.id,
},
}
}
import { nextTestSetup } from 'e2e-utils'
const expectedDts = `
type AppRoutes = "/" | "/_shop/[[...category]]" | "/dashboard" | "/dashboard/settings" | "/docs/[...slug]" | "/gallery/photo/[id]" | "/project/[slug]"
type PageRoutes = "/about" | "/users/[id]"
type LayoutRoutes = "/" | "/dashboard"
type RedirectRoutes = "/blog/[category]/[[...slug]]" | "/optional/[[...param]]" | "/project/[slug]"
type RewriteRoutes = "/api-legacy/[version]/[[...endpoint]]" | "/docs-old/[...path]"
type Routes = AppRoutes | PageRoutes | LayoutRoutes | RedirectRoutes | RewriteRoutes
`
describe('typed-routes', () => {
const { next, isNextDev, isNextStart, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should generate route types correctly', async () => {
const dts = await next.readFile('.next/types/routes.d.ts')
expect(dts).toContain(expectedDts)
})
it('should correctly convert custom route patterns from path-to-regexp to bracket syntax', async () => {
const dts = await next.readFile('.next/types/routes.d.ts')
// Test standard dynamic segment: :slug -> [slug]
expect(dts).toContain('"/project/[slug]"')
// Test catch-all one-or-more: :path+ -> [...path]
expect(dts).toContain('"/docs-old/[...path]"')
// Test catch-all zero-or-more: :slug* -> [[...slug]]
expect(dts).toContain('"/blog/[category]/[[...slug]]"')
expect(dts).toContain('"/api-legacy/[version]/[[...endpoint]]"')
// Test optional parameter: :param? -> [[...param]]
expect(dts).toContain('"/optional/[[...param]]"')
})
if (isNextDev) {
it('should update route types file when routes change', async () => {
// Create a new layout file
await next.patchFile(
'app/new-layout/layout.tsx',
`
export default function NewLayout() {
return <div>New Layout</div>
}
`
)
const routeTypesContent = await next.readFile('.next/types/routes.d.ts')
expect(routeTypesContent).toContain(
'type LayoutRoutes = "/" | "/dashboard" | "/new-layout"'
)
})
}
if (isNextStart) {
it('should throw type errors', async () => {
await next.stop()
await next.patchFile(
'app/type-testing.ts',
`type ValidPage = PageProps<'/dashboard'>
type InvalidPage = PageProps<'/dasboard'>`
)
const { cliOutput } = await next.build()
expect(cliOutput).toContain(
`Type '"/dasboard"' does not satisfy the constraint 'AppRoutes'.`
)
})
}
})
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information. // see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
...@@ -22,6 +22,8 @@ describe('find config', () => { ...@@ -22,6 +22,8 @@ describe('find config', () => {
(imageImportsEnabled (imageImportsEnabled
? '/// <reference types="next/image-types/global" />' + eol ? '/// <reference types="next/image-types/global" />' + eol
: '') + : '') +
'/// <reference path="./.next/types/routes.d.ts" />' +
eol +
eol + eol +
'// NOTE: This file should not be edited' + '// NOTE: This file should not be edited' +
eol + eol +
...@@ -32,6 +34,7 @@ describe('find config', () => { ...@@ -32,6 +34,7 @@ describe('find config', () => {
await writeAppTypeDeclarations({ await writeAppTypeDeclarations({
baseDir: fixtureDir, baseDir: fixtureDir,
distDir: '.next',
imageImportsEnabled, imageImportsEnabled,
hasPagesDir: false, hasPagesDir: false,
hasAppDir: false, hasAppDir: false,
...@@ -47,6 +50,8 @@ describe('find config', () => { ...@@ -47,6 +50,8 @@ describe('find config', () => {
(imageImportsEnabled (imageImportsEnabled
? '/// <reference types="next/image-types/global" />' + eol ? '/// <reference types="next/image-types/global" />' + eol
: '') + : '') +
'/// <reference path="./.next/types/routes.d.ts" />' +
eol +
eol + eol +
'// NOTE: This file should not be edited' + '// NOTE: This file should not be edited' +
eol + eol +
...@@ -57,6 +62,7 @@ describe('find config', () => { ...@@ -57,6 +62,7 @@ describe('find config', () => {
await writeAppTypeDeclarations({ await writeAppTypeDeclarations({
baseDir: fixtureDir, baseDir: fixtureDir,
distDir: '.next',
imageImportsEnabled, imageImportsEnabled,
hasPagesDir: false, hasPagesDir: false,
hasAppDir: false, hasAppDir: false,
...@@ -72,6 +78,8 @@ describe('find config', () => { ...@@ -72,6 +78,8 @@ describe('find config', () => {
(imageImportsEnabled (imageImportsEnabled
? '/// <reference types="next/image-types/global" />' + eol ? '/// <reference types="next/image-types/global" />' + eol
: '') + : '') +
'/// <reference path="./.next/types/routes.d.ts" />' +
eol +
eol + eol +
'// NOTE: This file should not be edited' + '// NOTE: This file should not be edited' +
eol + eol +
...@@ -80,6 +88,7 @@ describe('find config', () => { ...@@ -80,6 +88,7 @@ describe('find config', () => {
await writeAppTypeDeclarations({ await writeAppTypeDeclarations({
baseDir: fixtureDir, baseDir: fixtureDir,
distDir: '.next',
imageImportsEnabled, imageImportsEnabled,
hasPagesDir: false, hasPagesDir: false,
hasAppDir: false, hasAppDir: false,
...@@ -90,6 +99,7 @@ describe('find config', () => { ...@@ -90,6 +99,7 @@ describe('find config', () => {
it('should include navigation types if app directory is enabled', async () => { it('should include navigation types if app directory is enabled', async () => {
await writeAppTypeDeclarations({ await writeAppTypeDeclarations({
baseDir: fixtureDir, baseDir: fixtureDir,
distDir: '.next',
imageImportsEnabled, imageImportsEnabled,
hasPagesDir: false, hasPagesDir: false,
hasAppDir: true, hasAppDir: true,
...@@ -101,6 +111,7 @@ describe('find config', () => { ...@@ -101,6 +111,7 @@ describe('find config', () => {
await writeAppTypeDeclarations({ await writeAppTypeDeclarations({
baseDir: fixtureDir, baseDir: fixtureDir,
distDir: '.next',
imageImportsEnabled, imageImportsEnabled,
hasPagesDir: true, hasPagesDir: true,
hasAppDir: true, hasAppDir: true,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment