Unverified Commit f59543e2 authored by Ben Gubler's avatar Ben Gubler Committed by GitHub

[backport] fix: typesafe linking to route handlers and pages API routes (#82858) (#83025)

parent c8cf55f4
......@@ -201,18 +201,24 @@ export function generateLinkTypesFile(
routesManifest: RouteTypesManifest
): string {
// Generate serialized static and dynamic routes for the internal namespace
const allRoutes = {
...routesManifest.appRoutes,
...routesManifest.pageRoutes,
...routesManifest.redirectRoutes,
...routesManifest.rewriteRoutes,
}
// Build a unified set of routes across app/pages/redirect/rewrite as well as
// app route handlers and Pages Router API routes.
const allRoutesSet = new Set<string>([
...Object.keys(routesManifest.appRoutes),
...Object.keys(routesManifest.pageRoutes),
...Object.keys(routesManifest.redirectRoutes),
...Object.keys(routesManifest.rewriteRoutes),
// Allow linking to App Route Handlers (e.g. `/logout/route.ts`)
...Object.keys(routesManifest.appRouteHandlerRoutes),
// Allow linking to Pages Router API routes (e.g. `/api/*`)
...Array.from(routesManifest.pageApiRoutes),
])
const staticRouteTypes: string[] = []
const dynamicRouteTypes: string[] = []
// Process each route using the same logic as the plugin
for (const route of Object.keys(allRoutes)) {
for (const route of allRoutesSet) {
const { isDynamic, routeType } = formatRouteToRouteType(route)
if (isDynamic) {
dynamicRouteTypes.push(routeType)
......
import { NextResponse } from 'next/server'
export function GET() {
return NextResponse.json({ message: 'Hello, world!' })
}
......@@ -15,6 +15,12 @@ describe('typed-links', () => {
expect(dts).toContain(`declare module 'next/link'`)
})
it('should include handler route from app/api-test/route.ts in generated link route definitions', async () => {
const dts = await next.readFile('.next/types/link.d.ts')
// Ensure the app route handler at app/api-test/route.ts ("/api-test") is present
expect(dts).toContain('`/api-test`')
})
if (isNextStart) {
it('should pass type checking with valid routes', async () => {
await next.stop()
......
......@@ -2,7 +2,7 @@ import { nextTestSetup } from 'e2e-utils'
const expectedDts = `
type AppRoutes = "/" | "/_shop/[[...category]]" | "/dashboard" | "/dashboard/settings" | "/docs/[...slug]" | "/gallery/photo/[id]" | "/project/[slug]"
type AppRouteHandlerRoutes = "/api/docs/[...slug]" | "/api/shop/[[...category]]" | "/api/users/[id]"
type AppRouteHandlerRoutes = "/api-test" | "/api/docs/[...slug]" | "/api/shop/[[...category]]" | "/api/users/[id]"
type PageRoutes = "/about" | "/users/[id]"
type LayoutRoutes = "/" | "/dashboard"
type RedirectRoutes = "/blog/[category]/[[...slug]]" | "/project/[slug]"
......
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