Skip to content

Commit db56d77

Browse files
authored
[backport] fix: validation return types of pages API routes (#83069) (#83580)
I don't think this fix ever got backported to Next 15.5! @huozhi @ijjk @ztanner
1 parent 7a80623 commit db56d77

File tree

2 files changed

+17
-11
lines changed

2 files changed

+17
-11
lines changed

packages/next/src/server/lib/router-utils/typegen.ts

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -566,7 +566,7 @@ export function generateValidatorFile(
566566

567567
if (pagesApiRouteValidations) {
568568
typeDefinitions += `type ApiRouteConfig = {
569-
default: (req: any, res: any) => Promise<Response | void> | Response | void
569+
default: (req: any, res: any) => ReturnType<NextApiHandler>
570570
config?: {
571571
api?: {
572572
bodyParser?: boolean | { sizeLimit?: string }
@@ -612,18 +612,25 @@ export function generateValidatorFile(
612612
? "import type { NextRequest } from 'next/server.js'\n"
613613
: ''
614614

615-
// Only import metadata types if there are App Router pages or layouts that might use them
616-
const metadataImport =
617-
appPageValidations || layoutValidations
618-
? 'import type { ResolvingMetadata, ResolvingViewport } from "next/dist/lib/metadata/types/metadata-interface.js"\n'
615+
// Conditionally import types from next/types, merged into a single statement
616+
const nextTypes: string[] = []
617+
if (pagesApiRouteValidations) {
618+
nextTypes.push('NextApiHandler')
619+
}
620+
if (appPageValidations || layoutValidations) {
621+
nextTypes.push('ResolvingMetadata', 'ResolvingViewport')
622+
}
623+
const nextTypesImport =
624+
nextTypes.length > 0
625+
? `import type { ${nextTypes.join(', ')} } from "next/types.js"\n`
619626
: ''
620627

621628
return `// This file is generated automatically by Next.js
622629
// Do not edit this file manually
623630
// This file validates that all pages and layouts export the correct types
624631
625632
${routeImportStatement}
626-
${metadataImport}${nextRequestImport}
633+
${nextTypesImport}${nextRequestImport}
627634
${typeDefinitions}
628635
${appPageValidations}
629636
Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1-
import type { NextApiRequest, NextApiResponse } from 'next/types'
1+
import type { NextApiHandler } from 'next/types'
22

33
type ResponseData = {
44
message: string
55
}
66

7-
export default function handler(
8-
req: NextApiRequest,
9-
res: NextApiResponse<ResponseData>
10-
) {
7+
const handler: NextApiHandler<ResponseData> = (req, res) => {
118
res.status(200).json({ message: 'Hello from Next.js!' })
129
}
10+
11+
export default handler

0 commit comments

Comments
 (0)