Unverified Commit a63b89b1 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Loose types of app routes return value (#55849)

### What

#51394 introduced a pretty strict type of return value of route type
that causing failure with `next build`.
There're few ways of writing a app route, it could contain few return
values based on the usage:

* return a `Response` or promise of it
* return `NextResponse` of promise of it, since it's extended from
`Response`, same type
* use `redirect()` or `notFound(), since it returns `never`, and the
below code is not reached, the handler itself could still return void.
e.g. using `redirect` in a `GET` route

We loosed the type so `redirect()` can be still allowed without
specifying the return value there.
Related typescript issue:
https://github.com/microsoft/TypeScript/issues/16608#issuecomment-309327984

### How
* Re-enable the bail on types / build error in the app-routes tests
* Separate the tests, move runtime erroring ones to
`test/e2e/app-dir/app-routes-errors`
* Add new case to app-routes tests of mixed return value

Closes #55623 
Related #55604
parent adcf6e66
......@@ -107,11 +107,17 @@ if ('${method}' in entry) {
'${method}'
>
>()
${
''
// Adding void to support never return type without explicit return:
// e.g. notFound() will interrupt the execution but the handler return type is inferred as void.
// x-ref: https://github.com/microsoft/TypeScript/issues/16608#issuecomment-309327984
}
checkFields<
Diff<
{
__tag__: '${method}',
__return_type__: Response | Promise<Response>
__return_type__: Response | void | never | Promise<Response | void | never>
},
{
__tag__: '${method}',
......@@ -428,7 +434,7 @@ declare module 'next/link' {
import type { LinkProps as OriginalLinkProps } from 'next/dist/client/link.js'
import type { AnchorHTMLAttributes, DetailedHTMLProps } from 'react'
import type { UrlObject } from 'url'
type LinkRestProps = Omit<
Omit<
DetailedHTMLProps<
......
......@@ -2,7 +2,6 @@ import findUp from 'next/dist/compiled/find-up'
import fsPromise from 'fs/promises'
import child_process from 'child_process'
import assert from 'assert'
// @ts-ignore
import fetch from 'next/dist/compiled/node-fetch'
import os from 'os'
import { createInterface } from 'readline'
......
......@@ -43,6 +43,12 @@ declare module 'next/dist/compiled/@next/react-refresh-utils/dist/ReactRefreshWe
export = m
}
declare module 'next/dist/compiled/node-fetch' {
import fetch from 'node-fetch'
export * from 'node-fetch'
export default fetch
}
declare module 'next/dist/compiled/node-html-parser' {
export * from 'node-html-parser'
}
......
export default function error(req, res) {
throw new Error()
}
export default function uncaughtException(req, res) {
setTimeout(() => {
throw new Error('uncaught exception')
}, 0)
res.send('hello')
}
export default function unhandledRejection(req, res) {
Promise.reject(new Error('unhandled rejection'))
res.send('hello')
}
import stripAnsi from 'next/dist/compiled/strip-ansi'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { check, renderViaHTTP } from 'next-test-utils'
import { join } from 'path'
describe('api-route-errors cli output', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
pages: new FileRef(join(__dirname, 'app/pages')),
},
dependencies: {},
})
})
afterAll(() => next.destroy())
test('error', async () => {
const outputIndex = next.cliOutput.length
await renderViaHTTP(next.url, '/api/error')
await check(() => next.cliOutput.slice(outputIndex), /pages\/api/)
const output = stripAnsi(next.cliOutput.slice(outputIndex))
// Location
expect(output).toContain('pages/api/error.js (2:8) @ error')
// Stack
expect(output).toContain('pages/api/error.js:6:11')
// Source code
expect(output).toContain('1 | export default function error(req, res) {')
})
test('uncaught exception', async () => {
const outputIndex = next.cliOutput.length
await renderViaHTTP(next.url, '/api/uncaught-exception')
await check(() => next.cliOutput.slice(outputIndex), /pages\/api/)
const output = stripAnsi(next.cliOutput.slice(outputIndex))
// Location
expect(output).toContain('pages/api/uncaught-exception.js (3:10) @ Timeout')
// Stack
expect(output).toContain('pages/api/uncaught-exception.js:7:15')
// Source code
expect(output).toContain(
'1 | export default function uncaughtException(req, res) {'
)
})
test('unhandled rejection', async () => {
const outputIndex = next.cliOutput.length
await renderViaHTTP(next.url, '/api/unhandled-rejection')
await check(() => next.cliOutput.slice(outputIndex), /pages\/api/)
const output = stripAnsi(next.cliOutput.slice(outputIndex))
// Location
expect(output).toContain(
'pages/api/unhandled-rejection.js (2:17) @ unhandledRejection'
)
// Stack
expect(output).toContain('pages/api/unhandled-rejection.js:6:20')
// Source code
expect(output).toContain(
'1 | export default function unhandledRejection(req, res) '
)
})
})
export { DELETE as delete } from '../../../hello'
export { OPTIONS as options } from '../../../hello'
const helloHandler = async () => {
if (typeof WebSocket === 'undefined') {
throw new Error('missing WebSocket constructor!!')
}
return new Response('hello, world')
}
export const GET = helloHandler
export const HEAD = helloHandler
export const OPTIONS = helloHandler
export const POST = helloHandler
export const PUT = helloHandler
export const DELETE = helloHandler
export const PATCH = helloHandler
import { createNextDescribe } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'app-dir - app routes errors',
{
files: __dirname,
},
({ next }) => {
describe('bad lowercase exports', () => {
it.each([
['get'],
['head'],
['options'],
['post'],
['put'],
['delete'],
['patch'],
])(
'should print an error when using lowercase %p in dev',
async (method: string) => {
await next.fetch('/lowercase/' + method)
await check(() => {
expect(next.cliOutput).toContain(
`Detected lowercase method '${method}' in`
)
expect(next.cliOutput).toContain(
`Export the uppercase '${method.toUpperCase()}' method name to fix this error.`
)
expect(next.cliOutput).toMatch(
/Detected lowercase method '.+' in '.+\/route\.js'\. Export the uppercase '.+' method name to fix this error\./
)
return 'yes'
}, 'yes')
}
)
})
}
)
......@@ -589,45 +589,25 @@ createNextDescribe(
})
if (isNextDev) {
describe('lowercase exports', () => {
it.each([
['get'],
['head'],
['options'],
['post'],
['put'],
['delete'],
['patch'],
])(
'should print an error when using lowercase %p in dev',
async (method: string) => {
await next.fetch(basePath + '/lowercase/' + method)
await check(() => {
expect(next.cliOutput).toContain(
`Detected lowercase method '${method}' in`
)
expect(next.cliOutput).toContain(
`Export the uppercase '${method.toUpperCase()}' method name to fix this error.`
)
expect(next.cliOutput).toMatch(
/Detected lowercase method '.+' in '.+\/route\.ts'\. Export the uppercase '.+' method name to fix this error\./
)
return 'yes'
}, 'yes')
}
)
})
describe('invalid exports', () => {
beforeAll(async () => {
await next.patchFile(
'app/default/route.ts',
`\
export { GET as default } from '../../handlers/hello'
`
)
})
afterAll(async () => {
await next.deleteFile('app/default/route.ts')
})
it('should print an error when exporting a default handler in dev', async () => {
const res = await next.fetch(basePath + '/default')
// Ensure we get a 405 (Method Not Allowed) response when there is no
// exported handler for the GET method.
expect(res.status).toEqual(405)
await check(async () => {
const res = await next.fetch(basePath + '/default')
await check(() => {
// Ensure we get a 405 (Method Not Allowed) response when there is no
// exported handler for the GET method.
expect(res.status).toEqual(405)
expect(next.cliOutput).toMatch(
/Detected default export in '.+\/route\.ts'\. Export a named export for each HTTP method instead\./
)
......
export { GET as default } from '../../handlers/hello'
export { DELETE as delete } from '../../../handlers/hello'
export { GET as get } from '../../../handlers/hello'
export { HEAD as head } from '../../../handlers/hello'
export { OPTIONS as options } from '../../../handlers/hello'
export { PATCH as patch } from '../../../handlers/hello'
export { POST as post } from '../../../handlers/hello'
export { PUT as put } from '../../../handlers/hello'
import { redirect } from 'next/navigation'
import { NextResponse } from 'next/server'
export async function GET() {
if (process.env.COND_1) {
return NextResponse.json({ a: '1' })
} else if (process.env.COND_2) {
redirect('/no-response')
} else {
return new Response('3')
}
}
......@@ -60,10 +60,10 @@ type Cookies = {
export function getRequestMeta(
headersOrCookies:
| Headers
| import('node-fetch').Headers
| Cookies
| ReadonlyHeaders
| ReadonlyRequestCookies
| import('next/dist/compiled/node-fetch').Headers
): Record<string, any> {
const headerOrCookie = headersOrCookies.get(KEY)
if (!headerOrCookie) return {}
......
/**
* @type {import('next').NextConfig}
*/
const config = {
typescript: {
ignoreBuildErrors: true,
},
}
const config = {}
if (process.env.BASE_PATH) {
config.basePath = process.env.BASE_PATH
......
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