Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions packages/next/src/server/lib/router-utils/typegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -565,7 +565,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 }
Expand Down Expand Up @@ -611,18 +611,25 @@ 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
// Do not edit this file manually
// This file validates that all pages and layouts export the correct types

${routeImportStatement}
${metadataImport}${nextRequestImport}
${nextTypesImport}${nextRequestImport}
${typeDefinitions}
${appPageValidations}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
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
Loading