Unverified Commit bfed3985 authored by Steven's avatar Steven Committed by GitHub

fix: show error for api route handler with `output: export` (#47219)

In the case when the user configured `output: export` and used an API Route Handler that cannot be converted to static, Next.js must throw an error.

fix NEXT-823 ([link](https://linear.app/vercel/issue/NEXT-823))
parent 4e96e044
......@@ -181,6 +181,7 @@ export function getEdgeServerEntry(opts: {
absolutePagePath: opts.absolutePagePath,
page: opts.page,
appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'),
nextConfigOutput: opts.config.output,
}
return `next-edge-app-route-loader?${stringify(loaderParams)}!`
......
......@@ -2,14 +2,21 @@ import {
WebNextRequest,
WebNextResponse,
} from '../../../../server/base-http/web'
import { NextConfig } from '../../../../server/config-shared'
import { AppRouteRouteHandler } from '../../../../server/future/route-handlers/app-route-route-handler'
import { RouteKind } from '../../../../server/future/route-kind'
import { AppRouteRouteMatcher } from '../../../../server/future/route-matchers/app-route-route-matcher'
import { normalizeAppPath } from '../../../../shared/lib/router/utils/app-paths'
import { removeTrailingSlash } from '../../../../shared/lib/router/utils/remove-trailing-slash'
export function getHandle({ page, mod }: any) {
const appRouteRouteHandler = new AppRouteRouteHandler()
type HandleProps = {
page: string
mod: any
nextConfigOutput: NextConfig['output']
}
export function getHandle({ page, mod, nextConfigOutput }: HandleProps) {
const appRouteRouteHandler = new AppRouteRouteHandler(nextConfigOutput)
const appRouteRouteMatcher = new AppRouteRouteMatcher({
kind: RouteKind.APP_ROUTE,
pathname: normalizeAppPath(page),
......
import { getModuleBuildInfo } from '../get-module-build-info'
import { stringifyRequest } from '../../stringify-request'
import { NextConfig } from '../../../../server/config-shared'
export type EdgeAppRouteLoaderQuery = {
absolutePagePath: string
page: string
appDirLoader: string
nextConfigOutput: NextConfig['output']
}
export default async function edgeAppRouteLoader(this: any) {
......@@ -12,7 +14,8 @@ export default async function edgeAppRouteLoader(this: any) {
page,
absolutePagePath,
appDirLoader: appDirLoaderBase64,
} = this.getOptions()
nextConfigOutput,
} = this.getOptions() as EdgeAppRouteLoaderQuery
const appDirLoader = Buffer.from(
appDirLoaderBase64 || '',
......@@ -48,6 +51,9 @@ export default async function edgeAppRouteLoader(this: any) {
const render = getHandle({
mod,
page: ${JSON.stringify(page)},
nextConfigOuput: ${
nextConfigOutput ? JSON.stringify(nextConfigOutput) : 'undefined'
}
})
export const ComponentMod = mod
......
......@@ -85,6 +85,7 @@ interface ExportPageInput {
isrMemoryCacheSize?: NextConfigComplete['experimental']['isrMemoryCacheSize']
fetchCache?: boolean
incrementalCacheHandlerPath?: string
nextConfigOuput?: NextConfigComplete['output']
}
interface ExportPageResults {
......@@ -143,6 +144,7 @@ export default async function exportPage({
isrMemoryCacheSize,
fetchCache,
incrementalCacheHandlerPath,
nextConfigOuput,
}: ExportPageInput): Promise<ExportPageResults> {
setHttpClientAndAgentOptions({
httpAgentOptions,
......@@ -392,7 +394,7 @@ export default async function exportPage({
}
try {
const routeHandler = new AppRouteRouteHandler()
const routeHandler = new AppRouteRouteHandler(nextConfigOuput)
const response: Response = await routeHandler.handle(
{
params: query,
......
......@@ -37,6 +37,7 @@ import { IncrementalCache } from '../../lib/incremental-cache'
import { AppConfig } from '../../../build/utils'
import { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies'
import { NextURL } from '../../web/next-url'
import { NextConfig } from '../../config-shared'
// TODO-APP: This module has a dynamic require so when bundling for edge it causes issues.
const NodeModuleLoader =
......@@ -341,6 +342,7 @@ function proxyRequest(req: NextRequest, module: AppRouteModule): NextRequest {
export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
constructor(
private readonly nextConfigOutput: NextConfig['output'] = undefined,
private readonly requestAsyncLocalStorageWrapper: AsyncStorageWrapper<
RequestStore,
RequestContext
......@@ -484,6 +486,19 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
)
}
if (this.nextConfigOutput === 'export') {
if (
!module.handlers.dynamic ||
module.handlers.dynamic === 'auto'
) {
module.handlers.dynamic = 'error'
} else if (module.handlers.dynamic === 'force-dynamic') {
throw new Error(
`export const dynamic = "force-dynamic" on route handler "${handle.name}" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export`
)
}
}
switch (module.handlers.dynamic) {
case 'force-dynamic':
staticGenerationStore.forceDynamic = true
......@@ -492,8 +507,10 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
case 'force-static':
staticGenerationStore.forceStatic = true
break
case 'error':
staticGenerationStore.dynamicShouldError = true
break
default:
// TODO: implement
break
}
......
......@@ -254,9 +254,13 @@ export default class NextNodeServer extends BaseServer {
protected getRoutes() {
const routes = super.getRoutes()
const nextConfigOutput = this.nextConfig.output
if (this.hasAppDir) {
routes.handlers.set(RouteKind.APP_ROUTE, new AppRouteRouteHandler())
routes.handlers.set(
RouteKind.APP_ROUTE,
new AppRouteRouteHandler(nextConfigOutput)
)
}
return routes
......
export const dynamic = 'force-static'
export async function GET() {
return Response.json({ answer: 42 })
}
......@@ -6,6 +6,7 @@ import fs from 'fs-extra'
import webdriver from 'next-webdriver'
import globOrig from 'glob'
import {
fetchViaHTTP,
File,
findPort,
killApp,
......@@ -23,15 +24,18 @@ const distDir = join(__dirname, '.next')
const exportDir = join(appDir, 'out')
const nextConfig = new File(join(appDir, 'next.config.js'))
const slugPage = new File(join(appDir, 'app/another/[slug]/page.js'))
const apiJson = new File(join(appDir, 'app/api/json/route.js'))
async function runTests({
isDev,
trailingSlash,
dynamic,
dynamicPage,
dynamicApiRoute,
}: {
isDev?: boolean
trailingSlash?: boolean
dynamic?: string
dynamicPage?: string
dynamicApiRoute?: string
}) {
if (trailingSlash) {
nextConfig.replace(
......@@ -39,10 +43,16 @@ async function runTests({
`trailingSlash: ${trailingSlash},`
)
}
if (dynamic) {
if (dynamicPage) {
slugPage.replace(
`const dynamic = 'force-static'`,
`const dynamic = ${dynamic}`
`const dynamic = ${dynamicPage}`
)
}
if (dynamicApiRoute) {
apiJson.replace(
`const dynamic = 'force-static'`,
`const dynamic = ${dynamicApiRoute}`
)
}
await fs.remove(distDir)
......@@ -61,7 +71,6 @@ async function runTests({
}
try {
const a = (n: number) => `li:nth-child(${n}) a`
console.log('[navigate]')
const browser = await webdriver(appPort, '/')
expect(await browser.elementByCss('h1').text()).toBe('Home')
expect(await browser.elementByCss(a(1)).text()).toBe(
......@@ -117,10 +126,18 @@ async function runTests({
expect(await browser.elementByCss(a(2)).getAttribute('href')).toContain(
'/test.3f1a293b.png'
)
const res1 = await fetchViaHTTP(appPort, '/api/json')
expect(res1.status).toBe(200)
expect(await res1.json()).toEqual({ answer: 42 })
const res2 = await fetchViaHTTP(appPort, '/api/txt')
expect(res2.status).toBe(200)
expect(await res2.text()).toEqual('this is plain text')
} finally {
await stopOrKill()
nextConfig.restore()
slugPage.restore()
apiJson.restore()
}
}
......@@ -140,8 +157,8 @@ describe('app dir with output export', () => {
{ dynamic: 'undefined' },
{ dynamic: "'error'" },
{ dynamic: "'force-static'" },
])('should work with dynamic $dynamic', async ({ dynamic }) => {
await runTests({ dynamic })
])('should work with dynamic $dynamic on page', async ({ dynamic }) => {
await runTests({ dynamicPage: dynamic })
const opts = { cwd: exportDir, nodir: true }
const files = ((await glob('**/*', opts)) as string[])
.filter((f) => !f.startsWith('_next/static/chunks/'))
......@@ -168,7 +185,7 @@ describe('app dir with output export', () => {
'robots.txt',
])
})
it("should throw when dynamic 'force-dynamic'", async () => {
it("should throw when dynamic 'force-dynamic' on page", async () => {
slugPage.replace(
`const dynamic = 'force-static'`,
`const dynamic = 'force-dynamic'`
......@@ -181,10 +198,41 @@ describe('app dir with output export', () => {
} finally {
nextConfig.restore()
slugPage.restore()
apiJson.restore()
}
expect(result.code).toBe(1)
expect(result.stderr).toContain(
'export const dynamic = "force-dynamic" on page "/another/[slug]" cannot be used with "output: export".'
)
})
it.each([
{ dynamic: 'undefined' },
{ dynamic: "'error'" },
{ dynamic: "'force-static'" },
])(
'should work with dynamic $dynamic on route handler',
async ({ dynamic }) => {
await runTests({ dynamicApiRoute: dynamic })
}
)
it("should throw when dynamic 'force-dynamic' on route handler", async () => {
apiJson.replace(
`const dynamic = 'force-static'`,
`const dynamic = 'force-dynamic'`
)
await fs.remove(distDir)
await fs.remove(exportDir)
let result = { code: 0, stderr: '' }
try {
result = await nextBuild(appDir, [], { stderr: true })
} finally {
nextConfig.restore()
slugPage.restore()
apiJson.restore()
}
expect(result.code).toBe(1)
expect(result.stderr).toContain(
'export const dynamic = "force-dynamic" on page "/api/json" cannot be used with "output: export".'
)
})
})
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