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

[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
parent 7a806231
......@@ -566,7 +566,7 @@ export function generateValidatorFile(
if (pagesApiRouteValidations) {
typeDefinitions += `type ApiRouteConfig = {
default: (req: any, res: any) => Promise<Response | void> | Response | void
default: (req: any, res: any) => ReturnType<NextApiHandler>
config?: {
api?: {
bodyParser?: boolean | { sizeLimit?: string }
......@@ -612,10 +612,17 @@ export function generateValidatorFile(
? "import type { NextRequest } from 'next/server.js'\n"
: ''
// Only import metadata types if there are App Router pages or layouts that might use them
const metadataImport =
appPageValidations || layoutValidations
? 'import type { ResolvingMetadata, ResolvingViewport } from "next/dist/lib/metadata/types/metadata-interface.js"\n'
// Conditionally import types from next/types, merged into a single statement
const nextTypes: string[] = []
if (pagesApiRouteValidations) {
nextTypes.push('NextApiHandler')
}
if (appPageValidations || layoutValidations) {
nextTypes.push('ResolvingMetadata', 'ResolvingViewport')
}
const nextTypesImport =
nextTypes.length > 0
? `import type { ${nextTypes.join(', ')} } from "next/types.js"\n`
: ''
return `// This file is generated automatically by Next.js
......@@ -623,7 +630,7 @@ export function generateValidatorFile(
// This file validates that all pages and layouts export the correct types
${routeImportStatement}
${metadataImport}${nextRequestImport}
${nextTypesImport}${nextRequestImport}
${typeDefinitions}
${appPageValidations}
......
import type { NextApiRequest, NextApiResponse } from 'next/types'
import type { NextApiHandler } from 'next/types'
type ResponseData = {
message: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<ResponseData>
) {
const handler: NextApiHandler<ResponseData> = (req, res) => {
res.status(200).json({ message: 'Hello from Next.js!' })
}
export default handler
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