Unverified Commit abd5a843 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add force-static handling for app dir (#43061)

Fixes: https://github.com/vercel/next.js/issues/42932
x-ref: [slack
thread](https://vercel.slack.com/archives/C03S8ED1DKM/p1668639343426429?thread_ts=1668631260.554489&cid=C03S8ED1DKM)

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have a helpful link attached, see `contributing.md`
parent 37d5abaa
import { RequestCookies } from '../../server/web/spec-extension/cookies'
import { requestAsyncStorage } from './request-async-storage' import { requestAsyncStorage } from './request-async-storage'
import { staticGenerationBailout } from './static-generation-bailout' import { staticGenerationBailout } from './static-generation-bailout'
export function headers() { export function headers() {
staticGenerationBailout('headers') if (staticGenerationBailout('headers')) {
return new Headers({})
}
const requestStore = const requestStore =
requestAsyncStorage && 'getStore' in requestAsyncStorage requestAsyncStorage && 'getStore' in requestAsyncStorage
? requestAsyncStorage.getStore()! ? requestAsyncStorage.getStore()!
...@@ -12,7 +16,10 @@ export function headers() { ...@@ -12,7 +16,10 @@ export function headers() {
} }
export function previewData() { export function previewData() {
staticGenerationBailout('previewData') if (staticGenerationBailout('previewData')) {
return {}
}
const requestStore = const requestStore =
requestAsyncStorage && 'getStore' in requestAsyncStorage requestAsyncStorage && 'getStore' in requestAsyncStorage
? requestAsyncStorage.getStore()! ? requestAsyncStorage.getStore()!
...@@ -21,7 +28,9 @@ export function previewData() { ...@@ -21,7 +28,9 @@ export function previewData() {
} }
export function cookies() { export function cookies() {
staticGenerationBailout('cookies') if (staticGenerationBailout('cookies')) {
return new RequestCookies(new Headers({}))
}
const requestStore = const requestStore =
requestAsyncStorage && 'getStore' in requestAsyncStorage requestAsyncStorage && 'getStore' in requestAsyncStorage
? requestAsyncStorage.getStore()! ? requestAsyncStorage.getStore()!
......
...@@ -70,16 +70,20 @@ class ReadonlyURLSearchParams { ...@@ -70,16 +70,20 @@ class ReadonlyURLSearchParams {
* Learn more about URLSearchParams here: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams * Learn more about URLSearchParams here: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
*/ */
export function useSearchParams() { export function useSearchParams() {
staticGenerationBailout('useSearchParams')
const searchParams = useContext(SearchParamsContext) const searchParams = useContext(SearchParamsContext)
if (!searchParams) {
throw new Error('invariant expected search params to be mounted')
}
const readonlySearchParams = useMemo(() => { const readonlySearchParams = useMemo(() => {
return new ReadonlyURLSearchParams(searchParams) return new ReadonlyURLSearchParams(searchParams || new URLSearchParams())
}, [searchParams]) }, [searchParams])
if (staticGenerationBailout('useSearchParams')) {
return readonlySearchParams
}
if (!searchParams) {
throw new Error('invariant expected search params to be mounted')
}
return readonlySearchParams return readonlySearchParams
} }
......
...@@ -6,6 +6,7 @@ export interface StaticGenerationStore { ...@@ -6,6 +6,7 @@ export interface StaticGenerationStore {
revalidate?: number revalidate?: number
fetchRevalidate?: number fetchRevalidate?: number
isStaticGeneration?: boolean isStaticGeneration?: boolean
forceStatic?: boolean
} }
export let staticGenerationAsyncStorage: export let staticGenerationAsyncStorage:
......
...@@ -7,8 +7,11 @@ export function staticGenerationBailout(reason: string) { ...@@ -7,8 +7,11 @@ export function staticGenerationBailout(reason: string) {
? staticGenerationAsyncStorage?.getStore() ? staticGenerationAsyncStorage?.getStore()
: staticGenerationAsyncStorage : staticGenerationAsyncStorage
if (staticGenerationStore?.forceStatic) {
return true
}
if (staticGenerationStore?.isStaticGeneration) { if (staticGenerationStore?.isStaticGeneration) {
// TODO: honor the dynamic: 'force-static'
if (staticGenerationStore) { if (staticGenerationStore) {
staticGenerationStore.fetchRevalidate = 0 staticGenerationStore.fetchRevalidate = 0
} }
......
...@@ -43,6 +43,7 @@ import { ...@@ -43,6 +43,7 @@ import {
NEXT_ROUTER_STATE_TREE, NEXT_ROUTER_STATE_TREE,
RSC, RSC,
} from '../client/components/app-router-headers' } from '../client/components/app-router-headers'
import type { StaticGenerationStore } from '../client/components/static-generation-async-storage'
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge' const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
...@@ -273,9 +274,13 @@ function patchFetch(ComponentMod: any) { ...@@ -273,9 +274,13 @@ function patchFetch(ComponentMod: any) {
(typeof fetchRevalidate === 'undefined' || (typeof fetchRevalidate === 'undefined' ||
next.revalidate < fetchRevalidate) next.revalidate < fetchRevalidate)
) { ) {
staticGenerationStore.fetchRevalidate = next.revalidate const forceDynamic = staticGenerationStore.forceDynamic
if (next.revalidate === 0) { if (!forceDynamic || next.revalidate !== 0) {
staticGenerationStore.fetchRevalidate = next.revalidate
}
if (!forceDynamic && next.revalidate === 0) {
throw new DynamicServerError( throw new DynamicServerError(
`revalidate: ${next.revalidate} fetch ${input}${ `revalidate: ${next.revalidate} fetch ${input}${
pathname ? ` ${pathname}` : '' pathname ? ` ${pathname}` : ''
...@@ -791,7 +796,7 @@ export async function renderToHTMLOrFlight( ...@@ -791,7 +796,7 @@ export async function renderToHTMLOrFlight(
// we wrap the render in an AsyncLocalStorage context // we wrap the render in an AsyncLocalStorage context
const wrappedRender = async () => { const wrappedRender = async () => {
const staticGenerationStore = const staticGenerationStore: StaticGenerationStore =
'getStore' in staticGenerationAsyncStorage 'getStore' in staticGenerationAsyncStorage
? staticGenerationAsyncStorage.getStore() ? staticGenerationAsyncStorage.getStore()
: staticGenerationAsyncStorage : staticGenerationAsyncStorage
...@@ -1101,6 +1106,17 @@ export async function renderToHTMLOrFlight( ...@@ -1101,6 +1106,17 @@ export async function renderToHTMLOrFlight(
? [DefaultNotFound] ? [DefaultNotFound]
: [] : []
if (typeof layoutOrPageMod?.dynamic === 'string') {
// the nested most config wins so we only force-static
// if it's configured above any parent that configured
// otherwise
if (layoutOrPageMod.dynamic === 'force-static') {
staticGenerationStore.forceStatic = true
} else {
staticGenerationStore.forceStatic = false
}
}
if (typeof layoutOrPageMod?.revalidate === 'number') { if (typeof layoutOrPageMod?.revalidate === 'number') {
defaultRevalidate = layoutOrPageMod.revalidate defaultRevalidate = layoutOrPageMod.revalidate
......
...@@ -53,6 +53,12 @@ describe('app-dir static/dynamic handling', () => { ...@@ -53,6 +53,12 @@ describe('app-dir static/dynamic handling', () => {
'blog/tim/first-post.rsc', 'blog/tim/first-post.rsc',
'dynamic-no-gen-params-ssr/[slug]/page.js', 'dynamic-no-gen-params-ssr/[slug]/page.js',
'dynamic-no-gen-params/[slug]/page.js', 'dynamic-no-gen-params/[slug]/page.js',
'force-static/[slug]/page.js',
'force-static/first.html',
'force-static/first.rsc',
'force-static/page.js',
'force-static/second.html',
'force-static/second.rsc',
'hooks/use-pathname/[slug]/page.js', 'hooks/use-pathname/[slug]/page.js',
'hooks/use-pathname/slug.html', 'hooks/use-pathname/slug.html',
'hooks/use-pathname/slug.rsc', 'hooks/use-pathname/slug.rsc',
...@@ -121,6 +127,16 @@ describe('app-dir static/dynamic handling', () => { ...@@ -121,6 +127,16 @@ describe('app-dir static/dynamic handling', () => {
initialRevalidateSeconds: false, initialRevalidateSeconds: false,
srcRoute: '/hooks/use-pathname/[slug]', srcRoute: '/hooks/use-pathname/[slug]',
}, },
'/force-static/first': {
dataRoute: '/force-static/first.rsc',
initialRevalidateSeconds: false,
srcRoute: '/force-static/[slug]',
},
'/force-static/second': {
dataRoute: '/force-static/second.rsc',
initialRevalidateSeconds: false,
srcRoute: '/force-static/[slug]',
},
}) })
expect(manifest.dynamicRoutes).toEqual({ expect(manifest.dynamicRoutes).toEqual({
'/blog/[author]/[slug]': { '/blog/[author]/[slug]': {
...@@ -141,10 +157,94 @@ describe('app-dir static/dynamic handling', () => { ...@@ -141,10 +157,94 @@ describe('app-dir static/dynamic handling', () => {
fallback: null, fallback: null,
routeRegex: '^\\/hooks\\/use\\-pathname\\/([^\\/]+?)(?:\\/)?$', routeRegex: '^\\/hooks\\/use\\-pathname\\/([^\\/]+?)(?:\\/)?$',
}, },
'/force-static/[slug]': {
dataRoute: '/force-static/[slug].rsc',
dataRouteRegex: '^\\/force\\-static\\/([^\\/]+?)\\.rsc$',
fallback: null,
routeRegex: '^\\/force\\-static\\/([^\\/]+?)(?:\\/)?$',
},
}) })
}) })
} }
it('should force SSR correctly for headers usage', async () => {
const res = await fetchViaHTTP(next.url, '/force-static', undefined, {
headers: {
Cookie: 'myCookie=cookieValue',
another: 'header',
},
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect(JSON.parse($('#headers').text())).toIncludeAllMembers([
'cookie',
'another',
])
expect(JSON.parse($('#cookies').text())).toEqual([
{
name: 'myCookie',
value: 'cookieValue',
},
])
const firstTime = $('#now').text()
if (!(global as any).isNextDev) {
const res2 = await fetchViaHTTP(next.url, '/force-static')
expect(res2.status).toBe(200)
const $2 = cheerio.load(await res2.text())
expect(firstTime).not.toBe($2('#now').text())
}
})
it('should honor dynamic = "force-static" correctly', async () => {
const res = await fetchViaHTTP(next.url, '/force-static/first')
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect(JSON.parse($('#params').text())).toEqual({ slug: 'first' })
expect(JSON.parse($('#headers').text())).toEqual([])
expect(JSON.parse($('#cookies').text())).toEqual([])
const firstTime = $('#now').text()
if (!(global as any).isNextDev) {
const res2 = await fetchViaHTTP(next.url, '/force-static/first')
expect(res2.status).toBe(200)
const $2 = cheerio.load(await res2.text())
expect(firstTime).toBe($2('#now').text())
}
})
it('should honor dynamic = "force-static" correctly (lazy)', async () => {
const res = await fetchViaHTTP(next.url, '/force-static/random')
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect(JSON.parse($('#params').text())).toEqual({ slug: 'random' })
expect(JSON.parse($('#headers').text())).toEqual([])
expect(JSON.parse($('#cookies').text())).toEqual([])
const firstTime = $('#now').text()
if (!(global as any).isNextDev) {
const res2 = await fetchViaHTTP(next.url, '/force-static/random')
expect(res2.status).toBe(200)
const $2 = cheerio.load(await res2.text())
expect(firstTime).toBe($2('#now').text())
}
})
it('should handle dynamicParams: false correctly', async () => { it('should handle dynamicParams: false correctly', async () => {
const validParams = ['tim', 'seb', 'styfle'] const validParams = ['tim', 'seb', 'styfle']
......
// force-static should override the `headers()` usage
// in parent layout
export const dynamic = 'force-static'
export function generateStaticParams() {
return [{ slug: 'first' }, { slug: 'second' }]
}
export default function Page({ params }) {
return (
<>
<p id="page">/force-static/[slug]</p>
<p id="params">{JSON.stringify(params)}</p>
<p id="now">{Date.now()}</p>
</>
)
}
import { cookies, headers } from 'next/headers'
export default function Layout({ children }) {
const curHeaders = headers()
const curCookies = cookies()
return (
<>
<p id="headers">{JSON.stringify([...curHeaders.keys()])}</p>
<p id="cookies">{JSON.stringify([...curCookies.getAll()])}</p>
{children}
</>
)
}
// this should be dynamic as it doesn't specify force-static
// and the parent layout uses `headers()`
export default function Page() {
return (
<>
<p id="page">/force-static</p>
<p id="now">{Date.now()}</p>
</>
)
}
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