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