Unverified Commit cc0da4bd authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Opt-in to dynamic rendering when reading searchParams (#46205)

Ensures that using `searchParams` opts into dynamic rendering.

Fixes #43077 
fix NEXT-601 ([link](https://linear.app/vercel/issue/NEXT-601))

<!--
Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:
-->

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent dbdf47cf
...@@ -423,6 +423,10 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -423,6 +423,10 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
export { requestAsyncStorage } from 'next/dist/client/components/request-async-storage' export { requestAsyncStorage } from 'next/dist/client/components/request-async-storage'
export { staticGenerationBailout } from 'next/dist/client/components/static-generation-bailout'
export { default as StaticGenerationSearchParamsBailoutProvider } from 'next/dist/client/components/static-generation-searchparams-bailout-provider'
export { createSearchParamsBailoutProxy } from 'next/dist/client/components/searchparams-bailout-proxy'
export * as serverHooks from 'next/dist/client/components/hooks-server-context' export * as serverHooks from 'next/dist/client/components/hooks-server-context'
export { renderToReadableStream } from 'next/dist/compiled/react-server-dom-webpack/server.edge' export { renderToReadableStream } from 'next/dist/compiled/react-server-dom-webpack/server.edge'
......
import { staticGenerationBailout } from './static-generation-bailout'
export function createSearchParamsBailoutProxy() {
return new Proxy(
{},
{
get(_target, prop) {
// React adds some properties on the object when serializing for client components
if (typeof prop === 'string') {
staticGenerationBailout(`searchParams.${prop}`)
}
},
}
)
}
'use client'
import React from 'react'
import { createSearchParamsBailoutProxy } from './searchparams-bailout-proxy'
export default function StaticGenerationSearchParamsBailoutProvider({
Component,
propsForComponent,
}: {
Component: React.ComponentType<any>
propsForComponent: any
}) {
const searchParams = createSearchParamsBailoutProxy()
return <Component searchParams={searchParams} {...propsForComponent} />
}
...@@ -734,12 +734,21 @@ export async function renderToHTMLOrFlight( ...@@ -734,12 +734,21 @@ export async function renderToHTMLOrFlight(
? crypto.randomUUID() ? crypto.randomUUID()
: require('next/dist/compiled/nanoid').nanoid() : require('next/dist/compiled/nanoid').nanoid()
const searchParamsProps = { searchParams: query }
const LayoutRouter = const LayoutRouter =
ComponentMod.LayoutRouter as typeof import('../../client/components/layout-router').default ComponentMod.LayoutRouter as typeof import('../../client/components/layout-router').default
const RenderFromTemplateContext = const RenderFromTemplateContext =
ComponentMod.RenderFromTemplateContext as typeof import('../../client/components/render-from-template-context').default ComponentMod.RenderFromTemplateContext as typeof import('../../client/components/render-from-template-context').default
const createSearchParamsBailoutProxy =
ComponentMod.createSearchParamsBailoutProxy as typeof import('../../client/components/searchparams-bailout-proxy').createSearchParamsBailoutProxy
const StaticGenerationSearchParamsBailoutProvider =
ComponentMod.StaticGenerationSearchParamsBailoutProvider as typeof import('../../client/components/static-generation-searchparams-bailout-provider').default
const isStaticGeneration = staticGenerationStore.isStaticGeneration
// During static generation we need to call the static generation bailout when reading searchParams
const providedSearchParams = isStaticGeneration
? createSearchParamsBailoutProxy()
: query
const searchParamsProps = { searchParams: providedSearchParams }
/** /**
* Server Context is specifically only available in Server Components. * Server Context is specifically only available in Server Components.
...@@ -1278,6 +1287,8 @@ export async function renderToHTMLOrFlight( ...@@ -1278,6 +1287,8 @@ export async function renderToHTMLOrFlight(
} }
} }
const isClientComponent = isClientReference(layoutOrPageMod)
const props = { const props = {
...parallelRouteComponents, ...parallelRouteComponents,
// TODO-APP: params and query have to be blocked parallel route names. Might have to add a reserved name list. // TODO-APP: params and query have to be blocked parallel route names. Might have to add a reserved name list.
...@@ -1285,11 +1296,19 @@ export async function renderToHTMLOrFlight( ...@@ -1285,11 +1296,19 @@ export async function renderToHTMLOrFlight(
// If you have a `/dashboard/[team]/layout.js` it will provide `team` as a param but not anything further down. // If you have a `/dashboard/[team]/layout.js` it will provide `team` as a param but not anything further down.
params: currentParams, params: currentParams,
// Query is only provided to page // Query is only provided to page
...(isPage ? searchParamsProps : {}), ...(() => {
if (isClientComponent && isStaticGeneration) {
return {}
}
if (isPage) {
return searchParamsProps
}
})(),
} }
// Eagerly execute layout/page component to trigger fetches early. // Eagerly execute layout/page component to trigger fetches early.
if (!isClientReference(layoutOrPageMod)) { if (!isClientComponent) {
Component = await Promise.resolve().then(() => Component = await Promise.resolve().then(() =>
preloadComponent(Component, props) preloadComponent(Component, props)
) )
...@@ -1300,7 +1319,14 @@ export async function renderToHTMLOrFlight( ...@@ -1300,7 +1319,14 @@ export async function renderToHTMLOrFlight(
return ( return (
<> <>
{/* <Component /> needs to be the first element because we use `findDOMONode` in layout router to locate it. */} {/* <Component /> needs to be the first element because we use `findDOMONode` in layout router to locate it. */}
<Component {...props} /> {isPage && isClientComponent && isStaticGeneration ? (
<StaticGenerationSearchParamsBailoutProvider
propsForComponent={props}
Component={Component}
/>
) : (
<Component {...props} />
)}
{preloadedFontFiles?.length === 0 ? ( {preloadedFontFiles?.length === 0 ? (
<link <link
data-next-font={ data-next-font={
......
...@@ -9,7 +9,7 @@ module.exports = function (plop) { ...@@ -9,7 +9,7 @@ module.exports = function (plop) {
type: 'confirm', type: 'confirm',
name: 'appDir', name: 'appDir',
message: 'Is this test for the app directory?', message: 'Is this test for the app directory?',
default: false, default: true,
}, },
{ {
type: 'input', type: 'input',
......
'use client'
import { nanoid } from 'nanoid'
export default function Page({ searchParams }) {
return (
<>
<h1>Parameter: {searchParams.search}</h1>
<p id="nanoid">{nanoid()}</p>
</>
)
}
'use client'
import { nanoid } from 'nanoid'
export default function Page() {
return (
<>
<h1>No searchParams used</h1>
<p id="nanoid">{nanoid()}</p>
</>
)
}
'use client'
export default function ClientComponent({ searchParams }) {
return (
<>
<h1>Parameter: {searchParams.search}</h1>
</>
)
}
import { nanoid } from 'nanoid'
import ClientComponent from './component'
export default function Page({ searchParams }) {
return (
<>
<ClientComponent searchParams={searchParams} />
<p id="nanoid">{nanoid()}</p>
</>
)
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { nanoid } from 'nanoid'
export default function Page({ searchParams }) {
return (
<>
<h1>Parameter: {searchParams.search}</h1>
<p id="nanoid">{nanoid()}</p>
</>
)
}
import { nanoid } from 'nanoid'
export default function Page() {
return (
<>
<h1>No searchParams used</h1>
<p id="nanoid">{nanoid()}</p>
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: { appDir: true },
}
module.exports = nextConfig
import { createNextDescribe } from 'e2e-utils'
createNextDescribe(
'searchparams-static-bailout',
{
files: __dirname,
dependencies: {
nanoid: '4.0.1',
},
},
({ next, isNextStart }) => {
describe('server component', () => {
it('should bailout when using searchParams', async () => {
const url = '/server-component-page?search=hello'
const $ = await next.render$(url)
expect($('h1').text()).toBe('Parameter: hello')
// Check if the page is not statically generated.
if (isNextStart) {
const id = $('#nanoid').text()
const $2 = await next.render$(url)
const id2 = $2('#nanoid').text()
expect(id).not.toBe(id2)
}
})
it('should not bailout when not using searchParams', async () => {
const url = '/server-component-without-searchparams?search=hello'
const $ = await next.render$(url)
expect($('h1').text()).toBe('No searchParams used')
// Check if the page is not statically generated.
if (isNextStart) {
const id = $('#nanoid').text()
const $2 = await next.render$(url)
const id2 = $2('#nanoid').text()
expect(id).toBe(id2)
}
})
})
describe('client component', () => {
it('should bailout when using searchParams', async () => {
const url = '/client-component-page?search=hello'
const $ = await next.render$(url)
expect($('h1').text()).toBe('Parameter: hello')
// Check if the page is not statically generated.
if (isNextStart) {
const id = $('#nanoid').text()
const $2 = await next.render$(url)
const id2 = $2('#nanoid').text()
expect(id).not.toBe(id2)
}
})
it('should bailout when using searchParams is passed to client component', async () => {
const url = '/client-component?search=hello'
const $ = await next.render$(url)
expect($('h1').text()).toBe('Parameter: hello')
// Check if the page is not statically generated.
if (isNextStart) {
const id = $('#nanoid').text()
const $2 = await next.render$(url)
const id2 = $2('#nanoid').text()
expect(id).not.toBe(id2)
}
})
it('should not bailout when not using searchParams', async () => {
const url = '/client-component-without-searchparams?search=hello'
const $ = await next.render$(url)
expect($('h1').text()).toBe('No searchParams used')
// Check if the page is not statically generated.
if (isNextStart) {
const id = $('#nanoid').text()
const $2 = await next.render$(url)
const id2 = $2('#nanoid').text()
expect(id).toBe(id2)
}
})
})
}
)
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"plugins": [
{
"name": "next"
}
]
},
"include": ["next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
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