Unverified Commit 1d596ca9 authored by Hannes Bornö's avatar Hannes Bornö Committed by GitHub

Pathname and search params SSG (#41247)

Bailout to client rendering when using useSearchParams and usePathName
during SSG.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see `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`
- [ ] Integration 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`

## Documentation / Examples

- [ ] Make sure the linting passes by running `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 2277eb92
import { DynamicServerError } from './hooks-server-context'
import { requestAsyncStorage } from './request-async-storage' import { requestAsyncStorage } from './request-async-storage'
import { staticGenerationAsyncStorage } from './static-generation-async-storage' import { staticGenerationBailout } from './static-generation-bailout'
function staticGenerationBailout(reason: string) {
const staticGenerationStore =
staticGenerationAsyncStorage && 'getStore' in staticGenerationAsyncStorage
? staticGenerationAsyncStorage?.getStore()
: staticGenerationAsyncStorage
if (staticGenerationStore?.isStaticGeneration) {
// TODO: honor the dynamic: 'force-static'
if (staticGenerationStore) {
staticGenerationStore.revalidate = 0
}
throw new DynamicServerError(reason)
}
}
export function headers() { export function headers() {
staticGenerationBailout('headers') staticGenerationBailout('headers')
......
...@@ -12,6 +12,7 @@ import { ...@@ -12,6 +12,7 @@ import {
PathnameContext, PathnameContext,
// LayoutSegmentsContext, // LayoutSegmentsContext,
} from './hooks-client-context' } from './hooks-client-context'
import { staticGenerationBailout } from './static-generation-bailout'
const INTERNAL_URLSEARCHPARAMS_INSTANCE = Symbol( const INTERNAL_URLSEARCHPARAMS_INSTANCE = Symbol(
'internal for urlsearchparams readonly' 'internal for urlsearchparams readonly'
...@@ -69,6 +70,7 @@ class ReadonlyURLSearchParams { ...@@ -69,6 +70,7 @@ 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)
const readonlySearchParams = useMemo(() => { const readonlySearchParams = useMemo(() => {
return new ReadonlyURLSearchParams(searchParams) return new ReadonlyURLSearchParams(searchParams)
...@@ -80,6 +82,7 @@ export function useSearchParams() { ...@@ -80,6 +82,7 @@ export function useSearchParams() {
* Get the current pathname. For example usePathname() on /dashboard?foo=bar would return "/dashboard" * Get the current pathname. For example usePathname() on /dashboard?foo=bar would return "/dashboard"
*/ */
export function usePathname(): string { export function usePathname(): string {
staticGenerationBailout('usePathname')
return useContext(PathnameContext) return useContext(PathnameContext)
} }
......
import { DynamicServerError } from './hooks-server-context'
import { staticGenerationAsyncStorage } from './static-generation-async-storage'
export function staticGenerationBailout(reason: string) {
const staticGenerationStore =
staticGenerationAsyncStorage && 'getStore' in staticGenerationAsyncStorage
? staticGenerationAsyncStorage?.getStore()
: staticGenerationAsyncStorage
if (staticGenerationStore?.isStaticGeneration) {
// TODO: honor the dynamic: 'force-static'
if (staticGenerationStore) {
staticGenerationStore.revalidate = 0
}
throw new DynamicServerError(reason)
}
}
...@@ -10,6 +10,8 @@ import webdriver from 'next-webdriver' ...@@ -10,6 +10,8 @@ import webdriver from 'next-webdriver'
const glob = promisify(globOrig) const glob = promisify(globOrig)
describe('app-dir static/dynamic handling', () => { describe('app-dir static/dynamic handling', () => {
const isDev = (global as any).isNextDev
if ((global as any).isNextDeploy) { if ((global as any).isNextDeploy) {
it('should skip next deploy for now', () => {}) it('should skip next deploy for now', () => {})
return return
...@@ -56,6 +58,8 @@ describe('app-dir static/dynamic handling', () => { ...@@ -56,6 +58,8 @@ 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',
'hooks/use-pathname/[slug]/page.js',
'hooks/use-search-params/[slug]/page.js',
'ssr-auto/cache-no-store/page.js', 'ssr-auto/cache-no-store/page.js',
'ssr-auto/fetch-revalidate-zero/page.js', 'ssr-auto/fetch-revalidate-zero/page.js',
'ssr-forced/page.js', 'ssr-forced/page.js',
...@@ -359,9 +363,79 @@ describe('app-dir static/dynamic handling', () => { ...@@ -359,9 +363,79 @@ describe('app-dir static/dynamic handling', () => {
expect(secondDate).not.toBe(initialDate) expect(secondDate).not.toBe(initialDate)
}) })
describe('hooks', () => {
describe('useSearchParams', () => {
if (isDev) {
it('should bail out to client rendering during SSG', async () => {
const res = await fetchViaHTTP(
next.url,
'/hooks/use-search-params/slug'
)
const html = await res.text()
expect(html).toInclude('<html id="__next_error__">')
})
}
it('should have the correct values', async () => {
const browser = await webdriver(
next.url,
'/hooks/use-search-params/slug?first=value&second=other&third'
)
expect(await browser.elementByCss('#params-first').text()).toBe('value')
expect(await browser.elementByCss('#params-second').text()).toBe(
'other'
)
expect(await browser.elementByCss('#params-third').text()).toBe('')
expect(await browser.elementByCss('#params-not-real').text()).toBe(
'N/A'
)
})
it('should have values from canonical url on rewrite', async () => {
const browser = await webdriver(
next.url,
'/rewritten-use-search-params?first=a&second=b&third=c'
)
expect(await browser.elementByCss('#params-first').text()).toBe('a')
expect(await browser.elementByCss('#params-second').text()).toBe('b')
expect(await browser.elementByCss('#params-third').text()).toBe('c')
expect(await browser.elementByCss('#params-not-real').text()).toBe(
'N/A'
)
})
})
describe('usePathname', () => {
if (isDev) {
it('should bail out to client rendering during SSG', async () => {
const res = await fetchViaHTTP(next.url, '/hooks/use-pathname/slug')
const html = await res.text()
expect(html).toInclude('<html id="__next_error__">')
})
}
it('should have the correct values', async () => {
const browser = await webdriver(next.url, '/hooks/use-pathname/slug')
expect(await browser.elementByCss('#pathname').text()).toBe(
'/hooks/use-pathname/slug'
)
})
it('should have values from canonical url on rewrite', async () => {
const browser = await webdriver(next.url, '/rewritten-use-pathname')
expect(await browser.elementByCss('#pathname').text()).toBe(
'/rewritten-use-pathname'
)
})
})
it('should show a message to leave feedback for `appDir`', async () => { it('should show a message to leave feedback for `appDir`', async () => {
expect(next.cliOutput).toContain( expect(next.cliOutput).toContain(
`Thank you for testing \`appDir\` please leave your feedback at https://nextjs.link/app-feedback` `Thank you for testing \`appDir\` please leave your feedback at https://nextjs.link/app-feedback`
) )
}) })
})
}) })
export default function Layout({ children }) {
return children
}
export function generateStaticParams() {
return [{ slug: 'slug' }]
}
'use client'
import { usePathname } from 'next/navigation'
export const config = {
dynamicParams: false,
}
export default function Page() {
const pathname = usePathname()
return <p id="pathname">{pathname}</p>
}
export default function Layout({ children }) {
return children
}
export function generateStaticParams() {
return [{ slug: 'slug' }]
}
'use client'
import { useSearchParams } from 'next/navigation'
export const config = {
dynamicParams: false,
}
export default function Page() {
const params = useSearchParams()
return (
<>
<p id="params-first">{params.get('first') ?? 'N/A'}</p>
<p id="params-second">{params.get('second') ?? 'N/A'}</p>
<p id="params-third">{params.get('third') ?? 'N/A'}</p>
<p id="params-not-real">{params.get('notReal') ?? 'N/A'}</p>
</>
)
}
...@@ -11,6 +11,15 @@ module.exports = { ...@@ -11,6 +11,15 @@ module.exports = {
source: '/rewritten-to-dashboard', source: '/rewritten-to-dashboard',
destination: '/dashboard', destination: '/dashboard',
}, },
{
source: '/rewritten-use-search-params',
destination:
'/hooks/use-search-params/slug?first=value&second=other%20value&third',
},
{
source: '/rewritten-use-pathname',
destination: '/hooks/use-pathname/slug',
},
], ],
} }
}, },
......
...@@ -8,7 +8,7 @@ export default function Page() { ...@@ -8,7 +8,7 @@ export default function Page() {
return ( return (
<> <>
<h1 id="pathname" data-pathname={pathname}> <h1 id="pathname" data-pathname={pathname}>
hello from /hooks/use-pathname hello from {pathname}
</h1> </h1>
</> </>
) )
......
...@@ -7,15 +7,10 @@ export default function Page() { ...@@ -7,15 +7,10 @@ export default function Page() {
return ( return (
<> <>
<h1 <p id="params-first">{params.get('first') ?? 'N/A'}</p>
id="params" <p id="params-second">{params.get('second') ?? 'N/A'}</p>
data-param-first={params.get('first') ?? 'N/A'} <p id="params-third">{params.get('third') ?? 'N/A'}</p>
data-param-second={params.get('second') ?? 'N/A'} <p id="params-not-real">{params.get('notReal') ?? 'N/A'}</p>
data-param-third={params.get('third') ?? 'N/A'}
data-param-not-real={params.get('notReal') ?? 'N/A'}
>
hello from /hooks/use-search-params
</h1>
</> </>
) )
} }
'use client'
export default function Page({ searchParams }) {
return (
<h1
id="params"
data-param-first={searchParams.first ?? 'N/A'}
data-param-second={searchParams.second ?? 'N/A'}
data-param-third={searchParams.third ?? 'N/A'}
data-param-not-real={searchParams.notReal ?? 'N/A'}
>
hello from searchParams prop client
</h1>
)
}
export default function Page({ searchParams }) {
return (
<h1
id="params"
data-param-first={searchParams.first ?? 'N/A'}
data-param-second={searchParams.second ?? 'N/A'}
data-param-third={searchParams.third ?? 'N/A'}
data-param-not-real={searchParams.notReal ?? 'N/A'}
>
hello from searchParams prop server
</h1>
)
}
...@@ -42,4 +42,24 @@ export function middleware(request) { ...@@ -42,4 +42,24 @@ export function middleware(request) {
return NextResponse[method](new URL('/internal/success', request.url)) return NextResponse[method](new URL('/internal/success', request.url))
} }
if (request.nextUrl.pathname === '/search-params-prop-middleware-rewrite') {
return NextResponse.rewrite(
new URL(
'/search-params-prop?first=value&second=other%20value&third',
request.url
)
)
}
if (
request.nextUrl.pathname === '/search-params-prop-server-middleware-rewrite'
) {
return NextResponse.rewrite(
new URL(
'/search-params-prop/server?first=value&second=other%20value&third',
request.url
)
)
}
} }
...@@ -12,6 +12,25 @@ module.exports = { ...@@ -12,6 +12,25 @@ module.exports = {
source: '/rewritten-to-dashboard', source: '/rewritten-to-dashboard',
destination: '/dashboard', destination: '/dashboard',
}, },
{
source: '/search-params-prop-rewrite',
destination:
'/search-params-prop?first=value&second=other%20value&third',
},
{
source: '/search-params-prop-server-rewrite',
destination:
'/search-params-prop/server?first=value&second=other%20value&third',
},
{
source: '/rewritten-use-search-params',
destination:
'/hooks/use-search-params?first=value&second=other%20value&third',
},
{
source: '/rewritten-use-pathname',
destination: '/hooks/use-pathname',
},
{ {
source: '/hooks/use-selected-layout-segment/rewritten', source: '/hooks/use-selected-layout-segment/rewritten',
destination: destination:
......
...@@ -1133,6 +1133,17 @@ describe('app dir', () => { ...@@ -1133,6 +1133,17 @@ describe('app dir', () => {
'/hooks/use-pathname' '/hooks/use-pathname'
) )
}) })
it('should have the canonical url pathname on rewrite', async () => {
const html = await renderViaHTTP(
next.url,
'/rewritten-use-pathname'
)
const $ = cheerio.load(html)
expect($('#pathname').attr('data-pathname')).toBe(
'/rewritten-use-pathname'
)
})
}) })
describe('useSearchParams', () => { describe('useSearchParams', () => {
...@@ -1142,11 +1153,22 @@ describe('app dir', () => { ...@@ -1142,11 +1153,22 @@ describe('app dir', () => {
'/hooks/use-search-params?first=value&second=other%20value&third' '/hooks/use-search-params?first=value&second=other%20value&third'
) )
const $ = cheerio.load(html) const $ = cheerio.load(html)
const el = $('#params') expect($('#params-first').text()).toBe('value')
expect(el.attr('data-param-first')).toBe('value') expect($('#params-second').text()).toBe('other value')
expect(el.attr('data-param-second')).toBe('other value') expect($('#params-third').text()).toBe('')
expect(el.attr('data-param-third')).toBe('') expect($('#params-not-real').text()).toBe('N/A')
expect(el.attr('data-param-not-real')).toBe('N/A') })
it('should have the canonical url search params on rewrite', async () => {
const html = await renderViaHTTP(
next.url,
'/rewritten-use-search-params?first=a&second=b&third=c'
)
const $ = cheerio.load(html)
expect($('#params-first').text()).toBe('a')
expect($('#params-second').text()).toBe('b')
expect($('#params-third').text()).toBe('c')
expect($('#params-not-real').text()).toBe('N/A')
}) })
}) })
...@@ -1384,6 +1406,91 @@ describe('app dir', () => { ...@@ -1384,6 +1406,91 @@ describe('app dir', () => {
}) })
}) })
}) })
describe('searchParams prop', () => {
describe('client component', () => {
it('should have the correct search params', async () => {
const html = await renderViaHTTP(
next.url,
'/search-params-prop?first=value&second=other%20value&third'
)
const $ = cheerio.load(html)
const el = $('#params')
expect(el.attr('data-param-first')).toBe('value')
expect(el.attr('data-param-second')).toBe('other value')
expect(el.attr('data-param-third')).toBe('')
expect(el.attr('data-param-not-real')).toBe('N/A')
})
it('should have the correct search params on rewrite', async () => {
const html = await renderViaHTTP(
next.url,
'/search-params-prop-rewrite'
)
const $ = cheerio.load(html)
const el = $('#params')
expect(el.attr('data-param-first')).toBe('value')
expect(el.attr('data-param-second')).toBe('other value')
expect(el.attr('data-param-third')).toBe('')
expect(el.attr('data-param-not-real')).toBe('N/A')
})
it('should have the correct search params on middleware rewrite', async () => {
const html = await renderViaHTTP(
next.url,
'/search-params-prop-middleware-rewrite'
)
const $ = cheerio.load(html)
const el = $('#params')
expect(el.attr('data-param-first')).toBe('value')
expect(el.attr('data-param-second')).toBe('other value')
expect(el.attr('data-param-third')).toBe('')
expect(el.attr('data-param-not-real')).toBe('N/A')
})
})
describe('server component', () => {
it('should have the correct search params', async () => {
const html = await renderViaHTTP(
next.url,
'/search-params-prop/server?first=value&second=other%20value&third'
)
const $ = cheerio.load(html)
const el = $('#params')
expect(el.attr('data-param-first')).toBe('value')
expect(el.attr('data-param-second')).toBe('other value')
expect(el.attr('data-param-third')).toBe('')
expect(el.attr('data-param-not-real')).toBe('N/A')
})
it('should have the correct search params on rewrite', async () => {
const html = await renderViaHTTP(
next.url,
'/search-params-prop-server-rewrite'
)
const $ = cheerio.load(html)
const el = $('#params')
expect(el.attr('data-param-first')).toBe('value')
expect(el.attr('data-param-second')).toBe('other value')
expect(el.attr('data-param-third')).toBe('')
expect(el.attr('data-param-not-real')).toBe('N/A')
})
it('should have the correct search params on middleware rewrite', async () => {
const html = await renderViaHTTP(
next.url,
'/search-params-prop-server-middleware-rewrite'
)
const $ = cheerio.load(html)
const el = $('#params')
expect(el.attr('data-param-first')).toBe('value')
expect(el.attr('data-param-second')).toBe('other value')
expect(el.attr('data-param-third')).toBe('')
expect(el.attr('data-param-not-real')).toBe('N/A')
})
})
})
describe('sass support', () => { describe('sass support', () => {
describe('server layouts', () => { describe('server layouts', () => {
it('should support global sass/scss inside server layouts', async () => { it('should support global sass/scss inside server layouts', async () => {
......
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