Unverified Commit 6f9c4720 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

[Breaking] Disable automatic static generation for route handlers (#65825)

## Background

Currently route handlers will be attempted to statically generate the
same as normal pages in app router. If a route handler accessed dynamic
data such as `cookies()`, `headers()`, `req.url`, or similar we would
bail from this static generation but this didn't handle the case where
you would do data fetching via a non-fetch based library e.g. `redis` or
even using `Date.now()` or `Math.random()` so users would expect these
to be run every request like normal API endpoints but they would be
static so wouldn't be executed again after a build.


## New Behavior

As discussed this disable the default static generation handling for
route handlers as we've seen this confuse our users since in most cases
when creating a route handler you are handling dynamic workloads. This
doesn't remove the ability to static generate route handlers though as
you can still manually specify:

If you specify `export const revalidate = 1` we will still bail if
dynamic data is accessed to prevent accidental `revalidate` configuring
but this can be avoided via `force-static` being used as well.
 
```js
export const dynamic = 'force-static'
// or
export const dynamic = 'error'
// or
export const revalidate = false
// or
export const revalidate = 1 // value great than 0
// or 
export const generateStaticParams() {}
```

---------
Co-authored-by: 's avatarZack Tanner <1939140+ztanner@users.noreply.github.com>
parent 49c1e127
...@@ -49,9 +49,14 @@ In addition to supporting native [Request](https://developer.mozilla.org/docs/We ...@@ -49,9 +49,14 @@ In addition to supporting native [Request](https://developer.mozilla.org/docs/We
### Caching ### Caching
Route Handlers are cached by default when using the `GET` method with the `Response` object. Route Handlers are dynamic by default as of Next.js v15. To opt-in to caching for GET requests in route handlers you can specify via the following config:
```ts filename="app/items/route.ts" switcher ```ts filename="app/items/route.ts" switcher
// opt in to caching the route handler
export const dynamic = 'force-static' // or 'error'
// or
export const revalidate = false // or a value > 0
export async function GET() { export async function GET() {
const res = await fetch('https://data.mongodb-api.com/...', { const res = await fetch('https://data.mongodb-api.com/...', {
headers: { headers: {
......
...@@ -23,6 +23,7 @@ import type { ...@@ -23,6 +23,7 @@ import type {
import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error' import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error'
import { SERVER_DIRECTORY } from '../../shared/lib/constants' import { SERVER_DIRECTORY } from '../../shared/lib/constants'
import { hasNextSupport } from '../../telemetry/ci-info' import { hasNextSupport } from '../../telemetry/ci-info'
import { isStaticGenEnabled } from '../../server/future/route-modules/app-route/helpers/is-static-gen-enabled'
import type { ExperimentalConfig } from '../../server/config-shared' import type { ExperimentalConfig } from '../../server/config-shared'
export const enum ExportedAppRouteFiles { export const enum ExportedAppRouteFiles {
...@@ -87,6 +88,12 @@ export async function exportAppRoute( ...@@ -87,6 +88,12 @@ export async function exportAppRoute(
try { try {
// Route module loading and handling. // Route module loading and handling.
const module = await RouteModuleLoader.load<AppRouteRouteModule>(filename) const module = await RouteModuleLoader.load<AppRouteRouteModule>(filename)
const userland = module.userland
if (!isStaticGenEnabled(userland)) {
return { revalidate: 0 }
}
const response = await module.handle(request, context) const response = await module.handle(request, context)
const isValidStatus = response.status < 400 || response.status === 404 const isValidStatus = response.status < 400 || response.status === 404
......
import type { AppRouteModule } from '../module.compiled'
// route handlers are only statically optimized if they define
// one of these top-level configs manually
// - dynamic = 'force-static'
// - dynamic = 'error'
// - revalidate > 0
// - revalidate = false
// - generateStaticParams
export function isStaticGenEnabled(
mod: AppRouteModule['routeModule']['userland']
) {
return (
mod.dynamic === 'force-static' ||
mod.dynamic === 'error' ||
mod.revalidate === false ||
(mod.revalidate !== undefined && mod.revalidate > 0) ||
typeof mod.generateStaticParams == 'function'
)
}
...@@ -50,6 +50,7 @@ import { getIsServerAction } from '../../../lib/server-action-request-meta' ...@@ -50,6 +50,7 @@ import { getIsServerAction } from '../../../lib/server-action-request-meta'
import { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies' import { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies'
import { cleanURL } from './helpers/clean-url' import { cleanURL } from './helpers/clean-url'
import { StaticGenBailoutError } from '../../../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../../../client/components/static-generation-bailout'
import { isStaticGenEnabled } from './helpers/is-static-gen-enabled'
/** /**
* The AppRouteModule is the type of the module exported by the bundled App * The AppRouteModule is the type of the module exported by the bundled App
...@@ -178,12 +179,16 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -178,12 +179,16 @@ export class AppRouteRouteModule extends RouteModule<
// Get the dynamic property from the userland module. // Get the dynamic property from the userland module.
this.dynamic = this.userland.dynamic this.dynamic = this.userland.dynamic
if (this.nextConfigOutput === 'export') { if (this.nextConfigOutput === 'export') {
if (!this.dynamic || this.dynamic === 'auto') { if (this.dynamic === 'force-dynamic') {
this.dynamic = 'error'
} else if (this.dynamic === 'force-dynamic') {
throw new Error( throw new Error(
`export const dynamic = "force-dynamic" on page "${definition.pathname}" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export` `export const dynamic = "force-dynamic" on page "${definition.pathname}" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export`
) )
} else if (!isStaticGenEnabled(this.userland) && this.userland['GET']) {
throw new Error(
`export const dynamic = "force-static"/export const revalidate not configured on route "${definition.pathname}" with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export`
)
} else {
this.dynamic = 'error'
} }
} }
......
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
export const revalidate = 1
export const GET = async () => { export const GET = async () => {
cookies().set('foo', 'foo1') cookies().set('foo', 'foo1')
cookies().set('bar', 'bar1') cookies().set('bar', 'bar1')
......
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from 'next/server'
export const revalidate = 1
export const GET = (req: NextRequest) => { export const GET = (req: NextRequest) => {
return NextResponse.json({ return NextResponse.json({
pathname: req.nextUrl.pathname, pathname: req.nextUrl.pathname,
......
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
export const revalidate = false
export async function GET() { export async function GET() {
console.log('Load data') console.log('Load data')
return NextResponse.json({ return NextResponse.json({
......
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
export const revalidate = 1
export async function GET(req: NextRequest) { export async function GET(req: NextRequest) {
const path = req.nextUrl.searchParams.get('path') || '/' const path = req.nextUrl.searchParams.get('path') || '/'
try { try {
......
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
export const revalidate = 10
export async function GET() { export async function GET() {
const data360 = await fetch( const data360 = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random', 'https://next-data-api-endpoint.vercel.app/api/random',
......
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
export const revalidate = false
export function GET() { export function GET() {
const res = new NextResponse() const res = new NextResponse()
res.cookies.set('theme', 'light') res.cookies.set('theme', 'light')
......
export const revalidate = 1
export const GET = async (request) => { export const GET = async (request) => {
try { try {
const body = JSON.stringify({ pathname: request.nextUrl.toString() }) const body = JSON.stringify({ pathname: request.nextUrl.toString() })
......
export const revalidate = 1
export const GET = async (request) => { export const GET = async (request) => {
try { try {
const body = JSON.stringify({ url: request.url }) const body = JSON.stringify({ url: request.url })
......
export const revalidate = false
export async function GET() { export async function GET() {
return new Response('this is plain text') return new Response('this is plain text')
} }
...@@ -5,7 +5,11 @@ describe('app dir - with output export - dynamic api route dev', () => { ...@@ -5,7 +5,11 @@ describe('app dir - with output export - dynamic api route dev', () => {
'development mode', 'development mode',
() => { () => {
it.each([ it.each([
{ dynamicApiRoute: 'undefined' }, {
dynamicApiRoute: 'undefined',
expectedErrMsg:
'export const dynamic = "force-static"/export const revalidate not configured on route',
},
{ dynamicApiRoute: "'error'" }, { dynamicApiRoute: "'error'" },
{ dynamicApiRoute: "'force-static'" }, { dynamicApiRoute: "'force-static'" },
{ {
......
...@@ -5,7 +5,11 @@ describe('app dir - with output export - dynamic api route prod', () => { ...@@ -5,7 +5,11 @@ describe('app dir - with output export - dynamic api route prod', () => {
'production mode', 'production mode',
() => { () => {
it.each([ it.each([
{ dynamicApiRoute: 'undefined' }, {
dynamicApiRoute: 'undefined',
expectedErrMsg:
'export const dynamic = "force-static"/export const revalidate not configured on route',
},
{ dynamicApiRoute: "'error'" }, { dynamicApiRoute: "'error'" },
{ dynamicApiRoute: "'force-static'" }, { dynamicApiRoute: "'force-static'" },
{ {
......
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