prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
m 'cheerio' describe('app dir rendering', () => { const { next, isNextDev, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, }) if (skipped) { return } it('should serve app/page.server.js at /', async () => { const html = await next.render('/') expect(html).toContain('...
await next.render$('/ssr-only/slow') const endTime = Date.now() const duration = endTime - startTime // Each part takes 5 seconds so it should be below 10 seconds // Using 7 seconds to ensure external factors causing slight slowness
out-message').text()).toBe('hello from layout') expect($('#page-message').text()).toBe('hello from page') }) it('should run data fetch in parallel', async () => { const startTime = Date.now() const $ =
{ "filepath": "test/e2e/app-dir/app-rendering/rendering.test.ts", "language": "typescript", "file_size": 4772, "cut_index": 614, "middle_length": 229 }
' describe('setting cookies', () => { const { next, isNextDeploy, skipped } = nextTestSetup({ files: __dirname, }) if (skipped) return let currentCliOutputIndex = 0 beforeEach(() => { resetCliOutput() }) const getCliOutput = () => { if (next.cliOutput.length < currentCliOutputIndex) { ...
n error occurred in a function passed to `after\(\)`: .+?: Cookies can only be modified in a Server Action or Route Handler\./ describe('stops cookie mutations when changing phases', () => { it('from an action to a page render', async () => {
const resetCliOutput = () => { currentCliOutputIndex = next.cliOutput.length } const EXPECTED_ERROR = /Cookies can only be modified in a Server Action or Route Handler\./ const EXPECTED_ERROR_IN_AFTER = /A
{ "filepath": "test/e2e/app-dir/phase-changes/cookies.test.ts", "language": "typescript", "file_size": 4049, "cut_index": 614, "middle_length": 229 }
@type {string} */ key) { const path = `/timestamp/key/${encodeURIComponent(key)}` const sleepDuration = getSleepDuration() if (sleepDuration > 0) { console.log(`revalidateTimestampPage :: sleeping for ${sleepDuration} ms`) await sleep(sleepDuration) } console.log('revalidateTimestampPage :: revalid...
.parseInt(raw) if (Number.isNaN(parsed)) { throw new Error( `WAIT_BEFORE_REVALIDATING must be a valid number, got: ${JSON.stringify(raw)}` ) } return parsed } function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, m
BEFORE_REVALIDATING_DEFAULT const parsed = Number
{ "filepath": "test/e2e/app-dir/next-after-app-deploy/app/timestamp/revalidate.js", "language": "javascript", "file_size": 920, "cut_index": 606, "middle_length": 52 }
import { Viewport } from 'next' export async function generateViewport({ params, }: { params: Promise<{ color: string }> }): Promise<Viewport> { 'use cache: remote' // Use `eval` to side step compiler errors for using `arguments` in a 'use // cache' function. // eslint-disable-next-line no-eval const un...
though. const { color } = await params return { colorScheme: color === 'white' ? 'light' : 'dark', maximumScale: 1 + Math.random(), } } export default function Layout({ children }: { children: React.ReactNode }) { return <main>{children}<
) } // We're reading params here. This makes the cache function dynamic during // prerendering. It also requires suspense above body, so nothing will // prerendered. The meta tag should still be cached on refreshes
{ "filepath": "test/e2e/app-dir/use-cache/app/(dynamic)/generate-viewport-resume/params-used/[color]/layout.tsx", "language": "tsx", "file_size": 1006, "cut_index": 512, "middle_length": 229 }
t { connection } from 'next/server' async function getRandomValue(offset: number) { 'use cache: remote' return Math.random() + offset } let renderCount = 0 export default async function Page() { await connection() // Create the offsets array based on the render count to force a different // array on each ...
ill create cache // misses if the unused arguments are not properly ignored, because they would // be included in the cache keys. const randomNumbers = await Promise.all(offsets.map(getRandomValue)) return <p id="numbers">{randomNumbers.sort().joi
mValue. This w
{ "filepath": "test/e2e/app-dir/use-cache/app/(dynamic)/unused-args/page.tsx", "language": "tsx", "file_size": 801, "cut_index": 517, "middle_length": 14 }
mport { Button } from './button' async function getCachedValue( iterable: Iterable<number>, fn: () => string ): Promise<[string, () => string]> { 'use cache' // Make sure we're always receiving the arguments the same way, regardless of // whether draft mode is enabled or not. We're asserting that by checkin...
({ params, }: { params: Promise<{ mode: string }> }) { 'use cache' const { mode } = await params const offset = 1000 const cachedClosure = async () => { 'use cache' return new Date(Date.now() + offset).toISOString() } const { isE
use it crossed the "use cache" boundary.' ) } const date = new Date() date.setFullYear(date.getFullYear() + iterable.reduce((sum, n) => sum + n)) return [date.toISOString(), fn] } export default async function Page
{ "filepath": "test/e2e/app-dir/use-cache/app/(partially-static)/draft-mode/[mode]/page.tsx", "language": "tsx", "file_size": 2077, "cut_index": 563, "middle_length": 229 }
a } from 'next' import { connection } from 'next/server' import { Suspense } from 'react' export async function generateMetadata( _: { searchParams: Promise<Record<string, string | string[] | undefined>> }, parent: ResolvingMetadata ): Promise<Metadata> { 'use cache' // Explicitly not reading search params he...
dataBase: metadataBase?.replace('/bar', '/baz'), alternates: { canonical: '/qux' }, } } export default function Page() { return ( <Suspense fallback={<p>Loading...</p>}> <Dynamic /> </Suspense> ) } async function Dynamic() { awa
turn { title: new Date().toISOString(), meta
{ "filepath": "test/e2e/app-dir/use-cache/app/(partially-static)/generate-metadata-resume/nested/page.tsx", "language": "tsx", "file_size": 898, "cut_index": 547, "middle_length": 52 }
mport { Metadata } from 'next' export async function generateMetadata(_: { params: Promise<{ slug: string }> }): Promise<Metadata> { 'use cache' // Explicitly not reading params here. The description should appear in the // partially prerendered page. TODO: When resuming the page, we should get a // cache h...
it causes a cache miss, it's noticeable. await new Promise((resolve) => setTimeout(resolve, 5)) return { description: new Date().toISOString() } } export default function Layout({ children }: { children: React.ReactNode }) { return <>{children}</>
// so that if
{ "filepath": "test/e2e/app-dir/use-cache/app/(partially-static)/generate-metadata-resume/params-unused/[slug]/layout.tsx", "language": "tsx", "file_size": 786, "cut_index": 513, "middle_length": 14 }
ams: Promise<{ slug: string }> }): Promise<Metadata> { 'use cache: remote' // Use `eval` to side step compiler errors for using `arguments` in a 'use // cache' function. // eslint-disable-next-line no-eval const unusedParentArg = eval('arguments')[1] if (unusedParentArg !== undefined) { throw new Error...
uded from the // partially prerendered page. const { slug } = await params return { description: new Date().toISOString(), category: slug } } export default function Layout({ children }: { children: React.ReactNode }) { return <main>{children}</m
rerendering, and thus the description should be excl
{ "filepath": "test/e2e/app-dir/use-cache/app/(partially-static)/generate-metadata-resume/params-used/[slug]/layout.tsx", "language": "tsx", "file_size": 921, "cut_index": 606, "middle_length": 52 }
a } from 'next' import { connection } from 'next/server' import { Suspense } from 'react' export async function generateMetadata( _: { params: Promise<{ slug: string }> }, parent: ResolvingMetadata ): Promise<Metadata> { 'use cache' // We're not reading params here, but we do define a canonical URL, which /...
adataBase?.replace('/bar', '/baz'), alternates: { canonical: '/qux' }, } } export default function Page() { return ( <Suspense fallback={<p>Loading...</p>}> <Dynamic /> </Suspense> ) } async function Dynamic() { await connection
e } = await parent return { metadataBase: met
{ "filepath": "test/e2e/app-dir/use-cache/app/(partially-static)/generate-metadata-resume/canonical/[slug]/page.tsx", "language": "tsx", "file_size": 885, "cut_index": 547, "middle_length": 52 }
nstable_cache } from 'next/cache' import { setTimeout } from 'node:timers/promises' const getUnstableTime = unstable_cache( async () => { // Small artificial delay so the foreground-await is actually in flight when // the prospective prerender decides whether `cacheSignal` is ready. await setTimeout(100)...
background revalidation // prerender. In its prospective phase, the `unstable_cache` lookup hits a stale // entry and foreground-awaits the recompute. The downstream `<Cached />` must // still be reached during prospective so its RDC entry is populated for
( <p> Cached: <span id="cached-time">{new Date().toISOString()}</span> </p> ) } // Awaiting an `unstable_cache` BEFORE rendering a `'use cache'` component. // After the tag is revalidated, the next render runs a
{ "filepath": "test/e2e/app-dir/use-cache/app/(partially-static)/blocked-by-unstable-cache/page.tsx", "language": "tsx", "file_size": 1581, "cut_index": 537, "middle_length": 229 }
-compare */ async function getObject(arg: unknown) { 'use cache' return { arg } } async function getObjectWithBoundArgs(arg: unknown) { async function getCachedObject() { 'use cache' return { arg } } return getCachedObject() } export default async function Page() { return ( <> <h2>Wi...
nt results:{' '} <strong id="different-args"> {String((await getObject(1)) !== (await getObject(2)))} </strong> </p> <h2>With bound args</h2> <p> Two <span style={{ whiteSpace: 'pre' }}>"use cache"</span
"> {String((await getObject(1)) === (await getObject(1)))} </strong> </p> <p> Two <span style={{ whiteSpace: 'pre' }}>"use cache"</span> invocations with different args return differe
{ "filepath": "test/e2e/app-dir/use-cache/app/(partially-static)/referential-equality/page.tsx", "language": "tsx", "file_size": 1663, "cut_index": 537, "middle_length": 229 }
from 'react' import { revalidatePath, updateTag } from 'next/cache' export function RevalidateButtons() { return ( <form> <button id="revalidate-a" formAction={async () => { 'use server' updateTag('a') }} > revalidate a </button>{' '} <...
ync () => { 'use server' updateTag('f') }} > revalidate f </button>{' '} <button id="revalidate-r" formAction={async () => { 'use server' updateTag('r') }}
id="revalidate-c" formAction={async () => { 'use server' updateTag('c') }} > revalidate c </button>{' '} <button id="revalidate-f" formAction={as
{ "filepath": "test/e2e/app-dir/use-cache/app/(partially-static)/cache-tag/buttons.tsx", "language": "tsx", "file_size": 1273, "cut_index": 524, "middle_length": 229 }
from 'e2e-utils' import { check } from 'next-test-utils' describe('app-prefetch-false-loading', () => { const { next, isNextDeploy } = nextTestSetup({ files: __dirname, }) it('should render loading for the initial render', async () => { const $ = await next.render$('/en/testing') expect($('#loading...
owser.hasElementByCssSelector('#loading')).toBeFalsy() await check( () => browser.hasElementByCssSelector('#nested-testing-page'), true ) const newRandomNumber = await browser.elementById('random-number').text() expect(initia
length const browser = await next.browser('/en/testing') let initialRandomNumber = await browser.elementById('random-number').text() await browser.elementByCss('[href="/en/testing/test"]').click() expect(await br
{ "filepath": "test/e2e/app-dir/app-prefetch-false-loading/app-prefetch-false-loading.test.ts", "language": "typescript", "file_size": 1564, "cut_index": 537, "middle_length": 229 }
useState } from 'react' export function LinkAccordion({ href }: { href: string }) { const [isOpen, setIsOpen] = useState(false) return ( <div data-testid="link-accordion" data-href={href} style={{ border: '1px solid #e5e7eb', borderRadius: '12px', padding: '16px', ...
style={{ fontFamily: 'monospace', fontSize: '14px', color: '#374151', fontWeight: '500', flex: 1, }} > {href} </div> {!isOpen && ( <but
cursor: 'pointer', }} > <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: '12px', }} > <div
{ "filepath": "test/e2e/app-dir/interception-dynamic-segment/app/page.client.tsx", "language": "tsx", "file_size": 2284, "cut_index": 563, "middle_length": 229 }
root-param-dynamic-child', () => { const { next, isNextDev } = nextTestSetup({ files: __dirname, }) async function createBrowserActor( url: string, { errorPage = false, waitForPrefetch = false, }: { errorPage?: boolean waitForPrefetch?: boolean } = {} ) { let act...
{ act, browser } } if (waitForPrefetch) { // The page has navigation links that will be automatically prefetched. // Some routes will 404 (like /es which isn't in generateStaticParams), // so we allow 404 status codes. Let's reve
// throttling the CPU to rule out flakiness based on how quickly the page loads cpuThrottleRate: 6, }) // If we're on the error page, we don't have a nav element to wait for. if (errorPage) { return
{ "filepath": "test/e2e/app-dir/parallel-routes-root-param-dynamic-child/parallel-routes-root-param-dynamic-child.test.ts", "language": "typescript", "file_size": 6605, "cut_index": 716, "middle_length": 229 }
'force-dynamic' async function action() { 'use server' // make sure we return an updated version of the page in the response ;(await cookies()).set('pleaseRenderThePage', Date.now() + '') } export default async function Page() { const timestamp = Date.now() const cookieStore = await cookies() const canSet...
eturn false } })() return ( <> <div id="timestamp">{timestamp}</div> <div id="canSetCookies">{JSON.stringify(canSetCookies)}</div> <form action={action}> <button type="submit">Submit</button> </form> </> )
t swallow the error console.error(err) r
{ "filepath": "test/e2e/app-dir/phase-changes/app/cookies/action-to-render/page.tsx", "language": "tsx", "file_size": 916, "cut_index": 606, "middle_length": 52 }
{ Viewport } from 'next' import { connection } from 'next/server' import { Suspense } from 'react' export async function generateViewport({ params, }: { params: Promise<{ color: string }> }): Promise<Viewport> { 'use cache: remote' // Use `eval` to side step compiler errors for using `arguments` in a 'use ...
// prerendered. The meta tag should still be cached on refreshes though. const { color } = await params return { themeColor: color, initialScale: Math.random() } } export default function Page() { return ( <Suspense fallback={<p>Loading...</
parent argument to be omitted. Received: ' + unusedParentArg ) } // We're reading params here. This makes the cache function dynamic during // prerendering. It also requires suspense above body, so nothing will
{ "filepath": "test/e2e/app-dir/use-cache/app/(dynamic)/generate-viewport-resume/params-used/[color]/page.tsx", "language": "tsx", "file_size": 1124, "cut_index": 518, "middle_length": 229 }
acheLife } from 'next/cache' import { Suspense } from 'react' async function revalidateZero() { 'use cache: remote' cacheLife({ revalidate: 0 }) return new Date().toISOString() } async function lowExpire() { 'use cache: remote' cacheLife({ expire: 5 }) return new Date().toISOString() } async function O...
</> ) } async function OuterCacheExplicitShort() { 'use cache: remote' // Explicit short cacheLife - excluded from prerender, becomes a dynamic hole. cacheLife({ revalidate: 0, expire: 5 }) return ( <> <p> Explicit <code>rev
<p> <code>revalidate=0</code>:{' '} <span id="revalidate-zero">{await revalidateZero()}</span> </p> <p> <code>expire=5</code>: <span id="low-expire">{await lowExpire()}</span> </p>
{ "filepath": "test/e2e/app-dir/use-cache/app/(partially-static)/short-lived-caches/page.tsx", "language": "tsx", "file_size": 2274, "cut_index": 563, "middle_length": 229 }
r' import { Suspense } from 'react' export async function generateMetadata(_: { params: Promise<{ slug: string }> }): Promise<Metadata> { 'use cache' // Explicitly not reading params here. The title should appear in the // partially prerendered page. TODO: When resuming the page, we should get a // cache hi...
e. await new Promise((resolve) => setTimeout(resolve, 5)) return { title: new Date().toISOString() } } export default function Page() { return ( <Suspense fallback={<p>Loading...</p>}> <Dynamic /> </Suspense> ) } async function Dyn
// so that if it causes a cache miss, it's noticeabl
{ "filepath": "test/e2e/app-dir/use-cache/app/(partially-static)/generate-metadata-resume/params-unused/[slug]/page.tsx", "language": "tsx", "file_size": 947, "cut_index": 582, "middle_length": 52 }
ort { Metadata } from 'next' import { connection } from 'next/server' import { Suspense } from 'react' export async function generateMetadata({ params, }: { params: Promise<{ slug: string }> }): Promise<Metadata> { 'use cache: remote' // Use `eval` to side step compiler errors for using `arguments` in a 'use ...
ially // prerendered page. const { slug } = await params return { title: new Date().toISOString(), keywords: [slug] } } export default function Page() { return ( <Suspense fallback={<p>Loading...</p>}> <Dynamic /> </Suspense> ) }
d parent argument to be omitted. Received: ' + unusedParentArg ) } // We're reading params here. This makes the cache function dynamic during // prerendering, and thus the title should be excluded from the part
{ "filepath": "test/e2e/app-dir/use-cache/app/(partially-static)/generate-metadata-resume/params-used/[slug]/page.tsx", "language": "tsx", "file_size": 1076, "cut_index": 515, "middle_length": 229 }
import { cacheTag } from 'next/cache' import { RevalidateButtons } from './buttons' async function getCachedWithTag({ tag, fetchCache, }: { tag: string fetchCache?: 'force' | 'revalidate' }) { 'use cache' cacheTag(tag, 'c') // If `force-cache` or `revalidate` is used for the fetch call, it creates //...
orce' ? 'force-cache' : undefined, next: { revalidate: fetchCache === 'revalidate' ? 42 : undefined }, } ) const fetchedValue = await response.text() return [Math.random(), fetchedValue] } export default async function Page() { const a
cached result of `getCachedWithTag` // instead, thus also affected by revalidating 'c'. const response = await fetch( `https://next-data-api-endpoint.vercel.app/api/random?tag=${tag}`, { cache: fetchCache === 'f
{ "filepath": "test/e2e/app-dir/use-cache/app/(partially-static)/cache-tag/page.tsx", "language": "tsx", "file_size": 1569, "cut_index": 537, "middle_length": 229 }
isNextDeploy, isNextDev, nextTestSetup } from 'e2e-utils' import { startExternalServer } from './external-server.mjs' describe('middleware RSC external rewrite', () => { if (isNextDev || isNextDeploy) { test('should not run during dev or deploy test runs', () => {}) return } const { next } = nextTestSe...
t.stop() await externalServerManager?.cleanup() }) test('should forward _rsc parameter to external server on RSC navigation', async () => { const browser = await next.browser('/') try { const homeContent = await browser.elementById(
onst externalPort = await findPort() externalServerManager = await startExternalServer(externalPort) next.env.EXTERNAL_SERVER_PORT = String(externalPort) await next.start() }) afterAll(async () => { await nex
{ "filepath": "test/e2e/app-dir/middleware-rsc-external-rewrite/middleware-rsc-external-rewrite.test.ts", "language": "typescript", "file_size": 2220, "cut_index": 563, "middle_length": 229 }
retry } from 'next-test-utils' const isCacheComponentsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true' describe('revalidatePath with rewrites', () => { const { next } = nextTestSetup({ files: __dirname, buildArgs: [ '--debug-build-paths', isCacheComponentsEnabled ? '!app/legacy/*...
h() const refreshedRandomData = await browser .elementById('random-data') .text() expect(refreshedRandomData).toBe(initialRandomData) // Trigger revalidation via route handler const revalidateRes = await next.fetch(
it next.browser('/static') const initialRandomData = await browser.elementById('random-data').text() expect(initialRandomData).toBeTruthy() // Verify the data is cached after refresh await browser.refres
{ "filepath": "test/e2e/app-dir/revalidate-path-with-rewrites/revalidate-path-with-rewrites.test.ts", "language": "typescript", "file_size": 2365, "cut_index": 563, "middle_length": 229 }
acheLife } from 'next/cache' async function getCachedRandomNumber() { 'use cache' cacheTag('revalidate-tag-test') cacheLife('max') // This should change on each cache refresh return Math.random().toString() } export default async function Page() { const randomNumber = await getCachedRandomNumber() ret...
efresh // The client should continue showing stale data // Fresh data should only appear on next navigation/refresh revalidateTag('revalidate-tag-test', 'max') }} > Revalidate Tag (background)
// This should NOT cause immediate client r
{ "filepath": "test/e2e/app-dir/use-cache/app/(partially-static)/revalidate-tag-no-refresh/page.tsx", "language": "tsx", "file_size": 905, "cut_index": 547, "middle_length": 52 }
rt { cacheLife } from 'next/cache' import { connection } from 'next/server' import { Suspense } from 'react' async function outermost(id: string) { 'use cache' return id + middle('middle') } async function middle(id: string) { 'use cache' return id + innermost('inner') } async function innermost(id: string) ...
'outer') await innermost('inner') return ( <Suspense> <Short id="short" /> </Suspense> ) } export default function Page() { return ( <div> <CachedStuff /> <Suspense> <Dynamic /> </Suspense> </div>
} async function CachedStuff() { await outermost(
{ "filepath": "test/e2e/app-dir/use-cache/app/(partially-static)/rdc/page.tsx", "language": "tsx", "file_size": 829, "cut_index": 516, "middle_length": 52 }
st { next, skipped, isNextDev, isTurbopack } = nextTestSetup({ files: __dirname + '/fixtures/default', skipStart: true, skipDeployment: true, }) if (skipped) { return } it("it should error when using segment configs that aren't supported by cacheComponents", async () => { try { await...
e segment config "revalidate" is not compatible with \`nextConfig.cacheComponents\`. Please remove it."` ) } else { expect(redbox.description).toMatchInlineSnapshot( `" x Route segment config "revalidate" is not compatible
nst redbox = { description: await getRedboxDescription(browser), source: await getRedboxSource(browser), } if (isTurbopack) { expect(redbox.description).toMatchInlineSnapshot( `"Rout
{ "filepath": "test/e2e/app-dir/cache-components-segment-configs/cache-components-segment-configs.test.ts", "language": "typescript", "file_size": 5215, "cut_index": 716, "middle_length": 229 }
React from 'react' import { useActionState } from 'react' import { unstable_isUnrecognizedActionError as isUnrecognizedActionError } from 'next/navigation' export function FormWithArg<T>({ action, argument, id, children, }: { action: (state: string, argument: T) => Promise<string> argument: T id: string ...
e}`}</span> </form> ) } export function Form({ action, }: { action: (state: string, formData: FormData) => Promise<string> }) { const [state, dispatch] = useActionState(action, 'initial-state') return ( <form action={dispatch} id="form-d
lts in a FormData request (state) => action(state, argument), 'initial-state' ) return ( <form id={id} action={dispatch}> <button type="submit">{children}</button> <span className="form-state">{`${stat
{ "filepath": "test/e2e/app-dir/actions-unrecognized/app/nodejs/unrecognized-action/client.tsx", "language": "tsx", "file_size": 1645, "cut_index": 537, "middle_length": 229 }
port { Viewport } from 'next' import { connection } from 'next/server' import { Suspense } from 'react' export async function generateViewport({ params, }: { params: Promise<{ color: string }> }): Promise<Viewport> { 'use cache' // Explicitly not reading params here. The meta tag should appear in the // par...
implemented. return { initialScale: Math.random() } } export default function Page() { return ( <Suspense fallback={<p>Loading...</p>}> <Dynamic /> </Suspense> ) } async function Dynamic() { await connection() return <p>Dynamic
ed) is not yet
{ "filepath": "test/e2e/app-dir/use-cache/app/(partially-static)/generate-viewport-resume/params-unused/[color]/page.tsx", "language": "tsx", "file_size": 791, "cut_index": 514, "middle_length": 14 }
ort { Worker } from 'node:worker_threads' import { NextResponse } from 'next/server' interface PngInfo { url: string width: number height: number } export async function GET() { try { const worker = new Worker('./app/worker-dir/png-worker.ts') const pngInfo = await new Promise<PngInfo>((resolve, reje...
t(new Error(`Worker stopped with exit code ${code}`)) } }) worker.postMessage('get-png-info') }) await worker.terminate() return NextResponse.json({ success: true, pngInfo }) } catch (error) { return NextResponse.js
resolve(msg) }) worker.on('error', (err) => { clearTimeout(timeout) reject(err) }) worker.on('exit', (code) => { if (code !== 0) { clearTimeout(timeout) rejec
{ "filepath": "test/e2e/app-dir/node-worker-threads/app/api/png-worker-test/route.ts", "language": "typescript", "file_size": 1086, "cut_index": 515, "middle_length": 229 }
from 'e2e-utils' import { waitForNoRedbox, retry } from 'next-test-utils' describe('app dir', () => { const { next, isNextDev, isNextStart, skipped } = nextTestSetup({ files: __dirname, // This is skipped when deployed because there are no assertions outside of next start/next dev skipDeployment: true, ...
const browser = await next.browser('/page-with-loading') await retry(async () => { const headline = await browser.elementByCss('h1').text() expect(headline).toBe('hello from slow page') }) const cliOutput
ender$('/page-with-loading') expect($('#loading').text()).toBe('Loading...') }) }) } if (isNextDev) { describe('HMR', () => { it('should not cause error when removing loading.js', async () => {
{ "filepath": "test/e2e/app-dir/app-compilation/index.test.ts", "language": "typescript", "file_size": 1906, "cut_index": 537, "middle_length": 229 }
CLI output to only keep Turbopack error header lines (starting with ⨯ or // standalone file:line:col) to accurately count error occurrences without counting // console.error, stack traces, or forwarded browser logs. function filterToErrorHeaders(output: string): string { return output .split('\n') .filter( ...
so we only test this on Turbopack ;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)( 'cache-components-edge-deduplication', () => { const { next, skipped, isNextDev } = nextTestSetup({ files: __dirname + '/fixtures/edge-deduplicati
includes('at DevServer.') && !line.includes('at DevBundlerService.') && !line.includes('at async ') ) .join('\n') } // Only Turbopack runs the transform on the layout once in edge and non-edge contexts //
{ "filepath": "test/e2e/app-dir/cache-components-segment-configs/cache-components-edge-deduplication.test.ts", "language": "typescript", "file_size": 3491, "cut_index": 614, "middle_length": 229 }
utils' import { retry } from 'next-test-utils' describe('app dir - instant-validation-client', () => { const { next, isNextDev, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, skipStart: true, }) if (skipped) { return } it('should error when a client component exports un...
t.start().catch(() => {}) await next.browser('/').catch(() => {}) await retry(async () => { expect(next.cliOutput).toContain(expectedErrMsg) }) } else { const { cliOutput } = await next.build() expect(cliOutput).to
nt" directive` if (isNextDev) { await nex
{ "filepath": "test/e2e/app-dir/instant-validation-client/instant-validation-client.test.ts", "language": "typescript", "file_size": 893, "cut_index": 547, "middle_length": 52 }
mport { Worker } from 'node:worker_threads' import { NextResponse } from 'next/server' export async function GET() { try { // Test with a relative path instead of __filename const worker = new Worker('./app/worker-dir/simple-worker.ts') const message = await new Promise<string>((resolve, reject) => { ...
stopped with exit code ${code}`)) } }) worker.postMessage('ping') }) await worker.terminate() return NextResponse.json({ success: true, message }) } catch (error) { return NextResponse.json( { success: false,
}) worker.on('error', (err) => { clearTimeout(timeout) reject(err) }) worker.on('exit', (code) => { if (code !== 0) { clearTimeout(timeout) reject(new Error(`Worker
{ "filepath": "test/e2e/app-dir/node-worker-threads/app/api/simple-worker-test/route.ts", "language": "typescript", "file_size": 1056, "cut_index": 513, "middle_length": 229 }
server actions', () => { const { next, isNextDeploy, isNextDev } = nextTestSetup({ files: __dirname, }) let cliOutputPosition: number = 0 beforeEach(() => { cliOutputPosition = next.cliOutput.length }) const getLogs = () => { return next.cliOutput.slice(cliOutputPosition) } // This is dis...
-urlencoded', }, body: 'foo=bar', }) const cliOutput = getLogs() expect(cliOutput).not.toContain('TypeError') expect(cliOutput).not.toContain( 'Missing `origin` header from a forwarded Server Actions request
en POSTing a non-server-action request to a nonexistent page', async () => { const res = await next.fetch('/non-existent-route', { method: 'POST', headers: { 'content-type': 'application/x-www-form
{ "filepath": "test/e2e/app-dir/actions-unrecognized/actions-unrecognized.test.ts", "language": "typescript", "file_size": 7975, "cut_index": 716, "middle_length": 229 }
server' import pino from 'pino' export async function GET() { try { // Create a pino logger with a transport // This internally uses thread-stream which creates worker_threads const logger = pino({ transport: { target: 'pino/file', options: { destination: 1 }, // stdout }, ...
mise((resolve) => process.nextTick(resolve)) return NextResponse.json({ success: true, message: 'pino logger with transport initialized successfully', }) } catch (error) { return NextResponse.json( { success: false, error:
nc initialization of the transport await new Pro
{ "filepath": "test/e2e/app-dir/node-worker-threads/app/api/pino-test/route.ts", "language": "typescript", "file_size": 906, "cut_index": 547, "middle_length": 52 }
const $ = cheerio.load(html) expect(JSON.parse($('#params').text())).toEqual({ slug: ['hello123'], }) }) it('should return normalized dynamic route params for catch-all edge page', async () => { const html = await next.render('/catch-all-edge/a/b/c') const $ = cheerio.load(html) exp...
rch-params').text())).toEqual({ query1: 'value2', }) }) it('should have correct searchParams and params (client)', async () => { const browser = await next.browser( '/dynamic-client/category-1/id-2?query1=value2' ) const ht
render('/dynamic/category-1/id-2?query1=value2') const $ = cheerio.load(html) expect(JSON.parse($('#id-page-params').text())).toEqual({ category: 'category-1', id: 'id-2', }) expect(JSON.parse($('#sea
{ "filepath": "test/e2e/app-dir/app/index.test.ts", "language": "typescript", "file_size": 68095, "cut_index": 3790, "middle_length": 229 }
ver' /** * @param {import('next/server').NextRequest} request * @returns {Promise<NextResponse | undefined>} */ export async function middleware(request) { if (request.nextUrl.pathname === '/searchparams-normalization-bug') { const headers = new Headers(request.headers) headers.set('test', request.nextUrl...
if (request.nextUrl.pathname === '/bootstrap/with-nonce') { // In a real app, crypto.randomUUID() would be used to generate a safe nonce. // React and Webpack use eval() in development mode, so we need to allow it. const csp = `script-src 'n
but-not-routed') { return NextResponse.rewrite(new URL('/dashboard', request.url)) } if (request.nextUrl.pathname === '/middleware-to-dashboard') { return NextResponse.rewrite(new URL('/dashboard', request.url)) }
{ "filepath": "test/e2e/app-dir/app/middleware.js", "language": "javascript", "file_size": 2710, "cut_index": 563, "middle_length": 229 }
xports = { env: { LEGACY_ENV_KEY: '1', }, experimental: { clientRouterFilterRedirects: true, parallelServerCompiles: true, parallelServerBuildTraces: true, webpackBuildWorker: true, }, // output: 'standalone', rewrites: async () => { return { beforeFiles: [ { ...
}, { source: '/search-params-prop-server-rewrite', destination: '/search-params-prop/server?first=value&second=other%20value&third', }, { source: '/after-files-rewrite-with-empty-arra
ewritten-to-dashboard', destination: '/dashboard', }, { source: '/search-params-prop-rewrite', destination: '/search-params-prop?first=value&second=other%20value&third',
{ "filepath": "test/e2e/app-dir/app/next.config.js", "language": "javascript", "file_size": 2142, "cut_index": 563, "middle_length": 229 }
from 'fs-extra' import os from 'os' import path from 'path' import { findPort, initNextServerScript, killApp, fetchViaHTTP, } from 'next-test-utils' if (!(globalThis as any).isNextStart) { it('should skip for non-next start', () => {}) } else { describe('output: standalone with getStaticProps', () => { ...
'pages/gsp.js', ` import useSWR from 'swr' console.log(useSWR) export default function Home() { return <h1>Hello</h1> } export async function getStaticProps() { return
d) { return } beforeAll(async () => { await next.patchFile( 'next.config.js', (await next.readFile('next.config.js')).replace('// output', 'output') ) await next.patchFile(
{ "filepath": "test/e2e/app-dir/app/standalone-gsp.test.ts", "language": "typescript", "file_size": 2047, "cut_index": 563, "middle_length": 229 }
from 'fs-extra' import os from 'os' import path from 'path' import { findPort, initNextServerScript, killApp, fetchViaHTTP, } from 'next-test-utils' if (!(globalThis as any).isNextStart) { it('should skip for non-next start', () => {}) } else { describe('output: standalone with app dir', () => { const...
s correctly for route groups (nodejs only)', async () => { expect(next.cliOutput).not.toContain('Failed to copy traced files') const serverDirPath = path.join( next.testDir, '.next/standalone/.next/server' ) for (con
eforeAll(async () => { await next.patchFile( 'next.config.js', (await next.readFile('next.config.js')).replace('// output', 'output') ) await next.start() }) it('should handle trace file
{ "filepath": "test/e2e/app-dir/app/standalone.test.ts", "language": "typescript", "file_size": 2896, "cut_index": 563, "middle_length": 229 }
{ nextTestSetup } from 'e2e-utils' import { check } from 'next-test-utils' describe('useReportWebVitals hook', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true, env: {}, dependencies: { nanoid: '4.0.1', }, }) beforeAll(async () => { await next.start() }...
fresh will trigger CLS and LCP. When page loads FCP and TTFB will trigger: await browser.refresh() // After interaction LCP and FID will trigger await browser.elementById('btn').click() // Make sure all registered events in performance-re
next.browser('/report-web-vitals', { beforePageLoad: (page) => { page.route('https://example.vercel.sh/vitals', (route) => { eventsCount += 1 route.fulfill() }) }, }) // Re
{ "filepath": "test/e2e/app-dir/app/useReportWebVitals.test.ts", "language": "typescript", "file_size": 1150, "cut_index": 518, "middle_length": 229 }
t from 'next/script' import Client from './client' export default function Page() { return ( <div> <h2>next/script</h2> <Client /> <Script strategy="lazyOnload" src="/test4.js" /> <Script strategy="afterInteractive" src="/test3.js" stylesheets={['/style3.css']} ...
egy="beforeInteractive" id="2.5" dangerouslySetInnerHTML={{ __html: ` ;(window._script_order = window._script_order || []).push(2.5) console.log(window._script_order) `, }} /> <Script
"1.5">{` ;(window._script_order = window._script_order || []).push(1.5) console.log(window._script_order) `}</Script> <Script strategy="beforeInteractive" src="/test2.js" /> <Script strat
{ "filepath": "test/e2e/app-dir/app/app/script/page.js", "language": "javascript", "file_size": 1484, "cut_index": 524, "middle_length": 229 }
t' import { useCallback } from 'react' import { useState } from 'react' export default function Page() { const [success, setSuccess] = useState(false) const [finishedRefresh, setFinishedRefresh] = useState(false) const router = useRouter() const handleClick = useCallback(() => { setSuccess(true) start...
e={{ backgroundColor: success ? '#228B22' : '#ccc', color: 'white', }} > The current page </h1> {finishedRefresh && ( <div id="refreshed">Refreshed page successfully!</div> )} </> )
and setState </button> <h1 styl
{ "filepath": "test/e2e/app-dir/app/app/navigation/refresh/navigate-then-refresh-bug/page-to-refresh/page.js", "language": "javascript", "file_size": 916, "cut_index": 606, "middle_length": 52 }
lient' import { RefObject, Suspense, use, useEffect, useRef } from 'react' // The monaco module uses `window` in the module scope, so when it executes it immediately throws. // In order to avoid executing it on the server it's only imported in the browser. // We leverage `use` to wait for the promise. const maybeMona...
script', automaticLayout: true, }) return () => { monacoEditor.dispose() } } }, [monaco, editorRef]) return null } export function Editor() { const editorRef = useRef<HTMLDivElement>(null) return ( <>
null ? {} : use(maybeMonaco) useEffect(() => { if (monaco && editorRef.current) { const monacoEditor = monaco.editor.create(editorRef.current, { value: "console.log('Hello, world!');", language: 'java
{ "filepath": "test/e2e/app-dir/monaco-editor/components/editor/editor.tsx", "language": "tsx", "file_size": 1188, "cut_index": 518, "middle_length": 229 }
t/anchorSelect.js'; // import 'monaco-editor/esm/vs/editor/contrib/bracketMatching/bracketMatching.js'; // import 'monaco-editor/esm/vs/editor/contrib/caretOperations/caretOperations.js'; // import 'monaco-editor/esm/vs/editor/contrib/caretOperations/transpose.js'; // import 'monaco-editor/esm/vs/editor/contrib/clipboa...
'monaco-editor/esm/vs/editor/contrib/cursorUndo/cursorUndo.js'; // import 'monaco-editor/esm/vs/editor/contrib/dnd/dnd.js'; // import 'monaco-editor/esm/vs/editor/contrib/documentSymbols/documentSymbols.js'; // import "monaco-editor/esm/vs/editor/contrib/
rt 'monaco-editor/esm/vs/editor/contrib/colorPicker/colorContributions.js'; // import 'monaco-editor/esm/vs/editor/contrib/comment/comment.js'; // import 'monaco-editor/esm/vs/editor/contrib/contextmenu/contextmenu.js'; // import
{ "filepath": "test/e2e/app-dir/monaco-editor/components/editor/monaco.ts", "language": "typescript", "file_size": 10733, "cut_index": 921, "middle_length": 229 }
{ nextTestSetup } from 'e2e-utils' describe('ppr-root-param-rsc-fallback', () => { const { next, isNextDev } = nextTestSetup({ files: __dirname, }) if (isNextDev) { it('skipped in dev', () => {}) return } it('does not return HTML for a pregenerated root param full-route rsc request', async () ...
root param full-route rsc request', async () => { const tenant = `tenant-${Date.now()}` const response = await next.fetch(`/${tenant}/samples`, { headers: { RSC: '1', }, }) const body = await response.text() const c
ders.get('content-type') ?? '' expect(response.status).toBe(200) expect(contentType).toContain('text/x-component') expect(body).not.toContain('<!DOCTYPE html>') }) it('does not return HTML for a non-pregenerated
{ "filepath": "test/e2e/app-dir/ppr-root-param-rsc-fallback/ppr-root-param-rsc-fallback.test.ts", "language": "typescript", "file_size": 1210, "cut_index": 518, "middle_length": 229 }
' export function generateStaticParams() { return [{ tenant: 'tenant-a' }, { tenant: 'tenant-b' }] } async function CachedTenantMarker({ params, }: { params: Promise<{ tenant: string }> }) { 'use cache' return ( <div hidden id="cached-tenant-marker"> {(await params).tenant} </div> ) } asyn...
efault function TenantLayout({ children, params, }: { children: ReactNode params: Promise<{ tenant: string }> }) { return ( <> <Suspense>{children}</Suspense> <Suspense fallback={null}> <CachedTenantMarker params={params}
tenant` from params') } return null } export d
{ "filepath": "test/e2e/app-dir/ppr-root-param-rsc-fallback/app/[tenant]/layout.tsx", "language": "tsx", "file_size": 964, "cut_index": 582, "middle_length": 52 }
pense } from 'react' import { cacheLife, cacheTag } from 'next/cache' import { connection } from 'next/server' async function CachedShell({ tenant }: { tenant: string }) { 'use cache' cacheLife({ stale: 300, revalidate: 300, expire: 3600, }) cacheTag(`sample-shell:${tenant}`) return ( <> ...
g>{tenant}</strong>. </p> ) } export default function SamplesPage({ params, }: { params: Promise<{ tenant: string }> }) { const shell = params.then(async ({ tenant }) => ( <CachedShell tenant={tenant} /> )) return ( <main> <
) } async function DynamicRequestContent({ params, }: { params: Promise<{ tenant: string }> }) { const { tenant } = await params await connection() return ( <p id="dynamic"> Request-time content for <stron
{ "filepath": "test/e2e/app-dir/ppr-root-param-rsc-fallback/app/[tenant]/samples/page.tsx", "language": "tsx", "file_size": 1311, "cut_index": 524, "middle_length": 229 }
('custom-cache-control', () => { const { next, isNextDev, isNextDeploy } = nextTestSetup({ files: __dirname, }) if (isNextDeploy) { // customizing these headers won't apply on environments // where headers are applied outside of the Next.js server it('should skip for deploy', () => {}) return...
rol')).toBe( isNextDev ? 'no-cache, must-revalidate' : 's-maxage=31' ) }) ;(process.env.__NEXT_CACHE_COMPONENTS ? it.skip : it)( 'should have default cache-control for app-ssg another', async () => { const res = await next.fetch
isNextDev ? 'no-cache, must-revalidate' : 's-maxage=30' ) }) it('should have custom cache-control for app-ssg lazy', async () => { const res = await next.fetch('/app-ssg/lazy') expect(res.headers.get('cache-cont
{ "filepath": "test/e2e/app-dir/custom-cache-control/custom-cache-control.test.ts", "language": "typescript", "file_size": 2874, "cut_index": 563, "middle_length": 229 }
{import('next').NextConfig} */ const nextConfig = { headers() { return [ { source: '/app-ssg/first', headers: [ { key: 'Cache-Control', value: 's-maxage=30', }, ], }, { source: '/app-ssg/lazy', headers: [ ...
}, ], }, { source: '/pages-ssg/first', headers: [ { key: 'Cache-Control', value: 's-maxage=34', }, ], }, { source: '/pages-ssg/lazy',
'Cache-Control', value: 's-maxage=32', }, ], }, { source: '/pages-auto-static', headers: [ { key: 'Cache-Control', value: 's-maxage=33',
{ "filepath": "test/e2e/app-dir/custom-cache-control/next.config.js", "language": "javascript", "file_size": 1349, "cut_index": 524, "middle_length": 229 }
matcher: [ /* * Match all request paths except for the ones starting with: * - api (API routes) * - _next/static (static files) * - _next/image (image optimization files) * - favicon.ico, sitemap.xml, robots.txt (metadata files) */ '/((?!api|_next/static|_next/image|favicon.ico|sit...
=== '/hello/bob') { return NextResponse.rewrite(new URL('/hello/bobby', url)) } if (url.pathname === '/hello/john') { return NextResponse.rewrite(new URL('/hello/john?key=value', url)) } if (url.pathname === '/hello/vercel') { return
ello/admin?key=value', url)) } if (url.pathname
{ "filepath": "test/e2e/app-dir/rewrite-headers/middleware.js", "language": "javascript", "file_size": 974, "cut_index": 582, "middle_length": 52 }
'?: '0' | '1' | '2' 'next-router-segment-prefetch'?: string } expected: Record<Target, string | null> }[] = [ { name: 'static HTML', pathname: '/', expected: { 'x-nextjs-rewritten-path': null, 'x-nextjs-rewritten-query': null, }, }, { name: 'static RSC', pathname: '/', ...
}, expected: { 'x-nextjs-rewritten-path': null, 'x-nextjs-rewritten-query': null, }, }, { name: 'prerender HTML', pathname: '/hello/world', expected: { 'x-nextjs-rewritten-path': null, 'x-nextjs-rewritten-que
me: '/', headers: { rsc: '1', 'next-router-prefetch': '1', ...(process.env.__NEXT_CACHE_COMPONENTS === 'true' ? { 'next-router-segment-prefetch': '/_tree', } : {}),
{ "filepath": "test/e2e/app-dir/rewrite-headers/rewrite-headers.test.ts", "language": "typescript", "file_size": 13107, "cut_index": 921, "middle_length": 229 }
('turbopack-postcss-multiple-configs', () => { const { next, isTurbopack, skipped } = nextTestSetup({ files: __dirname, // Per-directory PostCSS config resolution is a Turbopack-only feature // (turbopackLocalPostcssConfig). Webpack does not support this feature and // does not accept function-valued ...
oduction mode the CSS minifier may shorten named colors to hex // (e.g. blue → #00f), so we match on patterns that cover both forms. const DIR_COLORS: Record<number, string | RegExp> = { 1: /blue|#00f/, 2: /purple|#800080/, 3: /orange|#ffa5
) return } beforeAll(async () => { await next.start() }) // Each directory's postcss.config.js passes a unique color option to the // shared plugin, which replaces `color: red` with the given color. // In pr
{ "filepath": "test/e2e/app-dir/turbopack-postcss-multiple-configs/turbopack-postcss-multiple-configs.test.ts", "language": "typescript", "file_size": 3043, "cut_index": 563, "middle_length": 229 }
utils' describe('css-chunking', () => { const { next } = nextTestSetup({ files: __dirname }) // this test asserts that all the emitted CSS files for the index page // do not contain styles for the `/other` page, which can happen // when the CSSChunkingPlugin is enabled and styles are shared across // both r...
.each(async (_, element) => { const href = element.attribs.href const result = await next.fetch(href) const css = await result.text() // eslint-disable-next-line jest/no-standalone-expect expect(css).not.toContain('
eets = $('link[rel="stylesheet"]') stylesheets
{ "filepath": "test/e2e/app-dir/css-chunking/css-chunking.test.ts", "language": "typescript", "file_size": 890, "cut_index": 547, "middle_length": 52 }
from 'e2e-utils' import { outdent } from 'outdent' describe('headers-static-bailout', () => { const { next, isNextStart } = nextTestSetup({ files: __dirname, dependencies: { nanoid: '4.0.1', }, }) if (!isNextStart) { it('should skip', () => {}) return } it('should bailout when usi...
async () => { const url = '/page-without-headers' const $ = await next.render$(url) expect($('h1').text()).toBe('Static Page') // Check if the page is not statically generated. const id = $('#nanoid').text() const $2 = await next.
age is not statically generated. 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 headers',
{ "filepath": "test/e2e/app-dir/headers-static-bailout/headers-static-bailout.test.ts", "language": "typescript", "file_size": 1710, "cut_index": 537, "middle_length": 229 }
Link from 'next/link' /** Add your relevant code here for the issue to reproduce */ export default function Home() { return ( <div> <h1>Subpage linking issue reproduction</h1> <p>Reproducing:</p> <ol> <li>Press the "Go to blog" link</li> <li>Press the "Go to post" link</li> ...
<code>/blog</code> to <code>/blog/a-post</code> (<code>/[slug]</code>{' '} where slug is blog and <code>/blog/[slug]</code> where slug is a-post) </p> <Link href="/blog" style={{ display: 'block' }} id="to-blog"> Go to
but never navigates </li> </ol> <p> Reloading and pressing the "Go to another page" link and then going to the blog post does work however, suggesting the issue is navigating from{' '}
{ "filepath": "test/e2e/app-dir/router-stuck-dynamic-static-segment/app/page.tsx", "language": "tsx", "file_size": 1143, "cut_index": 518, "middle_length": 229 }
from 'e2e-utils' describe('app-dir - no server actions', () => { const { next, isNextDeploy } = nextTestSetup({ files: __dirname, }) it('should error when triggering a fetch action on an app with no server actions', async () => { const res = await next.fetch('/', { method: 'POST', headers: {...
ttps://nextjs.org/docs/messages/failed-to-find-server-action' ) } }) it('should error when triggering an MPA action on an app with no server actions', async () => { const formData = new FormData() formData.append('test', 'value')
re not forwarded to the client when deployed. if (!isNextDeploy) { expect(next.cliOutput).toContain( 'Failed to find Server Action "abc123". This request might be from an older or newer deployment.\nRead more: h
{ "filepath": "test/e2e/app-dir/no-server-actions/no-server-actions.test.ts", "language": "typescript", "file_size": 1684, "cut_index": 537, "middle_length": 229 }
} from 'e2e-utils' import { check } from 'next-test-utils' import fs from 'fs' const originalNextConfig = fs.readFileSync( __dirname + '/next.config.js', 'utf8' ) const importMetaResolveNextConfig = `export default { cacheHandler: import.meta.resolve('./cache-handler-esm.js'), }` function runTests( exportType...
ct(next.cliOutput).toContain('cache-handler get') expect(next.cliOutput).toContain('cache-handler set') return 'success' }, 'success') }) }) } describe('app-dir - custom-cache-handler - cjs', () => { const { next, isNextDev,
{ await next.fetch('/') } await check(() => { expect(next.cliOutput).toContain('cache handler - ' + exportType) expect(next.cliOutput).toContain('initialized custom cache-handler') expe
{ "filepath": "test/e2e/app-dir/app-custom-cache-handler/index.test.ts", "language": "typescript", "file_size": 2756, "cut_index": 563, "middle_length": 229 }
retry } from 'next-test-utils' describe('expire-time', () => { const { next, isNextDeploy } = nextTestSetup({ files: __dirname, }) // On Vercel, ISR cache decisions happen at the Proxy layer. The Vercel // builder reads the route's `expire` value (Next.js's `initialExpireSeconds` // in the prerender man...
rves stale with a // background revalidation instead of a blocking prerender. When Proxy is // updated to honor the expire value, this test will start passing in deploy // mode and `it.failing` will itself fail. That's the signal to flip it back //
nted, to read // updated values from Next.js's `stale-while-revalidate` response header on // subsequent revalidations. Today the Proxy ignores the expire value entirely // and treats it as one year. Past `expireTime` it se
{ "filepath": "test/e2e/app-dir/expire-time/expire-time.test.ts", "language": "typescript", "file_size": 2588, "cut_index": 563, "middle_length": 229 }
/ This page is validating that despite multiple unsuccessful responses to the same, potentially cached URLs, // the build locks are resolved and the page is still built successfully. export async function generateStaticParams() { return [ { slug: 'slug-0', }, { slug: 'slug-1', }, { ...
TEST_SERVER_PORT}?status=404` ).then((res) => res.text()) await fetch( `http://localhost:${process.env.TEST_SERVER_PORT}?status=404` ).then((res) => res.text()) return ( <> <p>hello world</p> <p id="data">{data}</p> </> )
${process.env.
{ "filepath": "test/e2e/app-dir/app-fetch-deduping/app/bad-response-page/[slug]/page.js", "language": "javascript", "file_size": 786, "cut_index": 513, "middle_length": 14 }
not actually // used by that server module). // This is a known limitation of flight-client-entry-plugin and we will improve // this in the future. const getAttrs = (elems: Cheerio) => Array.from(elems) .map((elem) => elem.attribs) // There is something weord that causes different machines to have different ...
w FileRef(join(__dirname, 'node_modules')), 'next.config.js': new FileRef(join(__dirname, 'next.config.js')), }, dependencies: { '@next/font': 'canary', }, skipDeployment: true, }) if (skipped) { retur
const { next, isNextDev: isDev, skipped, } = nextTestSetup({ files: { app: new FileRef(join(__dirname, 'app')), fonts: new FileRef(join(__dirname, 'fonts')), node_modules: ne
{ "filepath": "test/e2e/app-dir/next-font/next-font.test.ts", "language": "typescript", "file_size": 16994, "cut_index": 921, "middle_length": 229 }
port { nextTestSetup } from 'e2e-utils' const GENERIC_RSC_ERROR = 'Minified React error #441; visit https://react.dev/errors/441 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.' export function runTest({ next, isNextDev }) { it('should error when passi...
t pass process.env to Client Components since it will leak sensitive data' : GENERIC_RSC_ERROR ) }) } describe('app dir - taint', () => { const { next, isNextDev } = nextTestSetup({ files: __dirname, }) runTest({ next, isNextDev }
? 'Do no
{ "filepath": "test/e2e/app-dir/taint/process-taint.test.ts", "language": "typescript", "file_size": 789, "cut_index": 514, "middle_length": 14 }
eact' import { FormWithArg, Form, UnrecognizedActionBoundary } from './client' const action = async (...args: any[]) => { 'use server' console.log('hello from server', ...args) return 'state-from-server' } // simulate client-side version skew by changing the action ID to something the server won't recognize set...
Submit client form with simple argument </FormWithArg> </UnrecognizedActionBoundary> </div> <div> <UnrecognizedActionBoundary> <FormWithArg action={action} id="form-complex
UnrecognizedActionBoundary> </div> <div> <UnrecognizedActionBoundary> <FormWithArg action={action} id="form-simple-argument" argument={{ foo: 'bar' }} >
{ "filepath": "test/e2e/app-dir/actions-unrecognized/app/nodejs/unrecognized-action/page.tsx", "language": "tsx", "file_size": 1735, "cut_index": 537, "middle_length": 229 }
from 'e2e-utils' import path from 'path' describe('app-root-param-getters - generateStaticParams error', () => { const { next, isNextDev, skipped } = nextTestSetup({ files: path.join(__dirname, 'fixtures', 'generate-static-params-error'), skipStart: true, skipDeployment: true, }) if (skipped) return ...
on": "Route /[lang]/[locale] used \`import('next/root-params').lang()\` inside \`generateStaticParams\`, but the \`lang\` parameter was not provided by a parent \`generateStaticParams\`. In \`generateStaticParams\`, root params are only available for segme
s it - dev', async () => { const browser = await next.browser('/en/us') // TODO: This is not the correct error code. await expect(browser).toDisplayRedbox(` { "code": "E394", "descripti
{ "filepath": "test/e2e/app-dir/app-root-params-getters/generate-static-params-error.test.ts", "language": "typescript", "file_size": 1926, "cut_index": 537, "middle_length": 229 }
ils' describe('app-root-param-getters - multiple roots', () => { const { next, isNextDev, isTurbopack } = nextTestSetup({ files: join(__dirname, 'fixtures', 'multiple-roots'), }) it('should have root params on dashboard pages', async () => { const $ = await next.render$('/dashboard/1') expect($('bod...
added or renamed', async () => { // Start on the dashboard page, which uses root param getters. // This forces the bundler to generate 'next/root-params'. await using sandbox = await createSandbox(next, undefined, `/dashboard/1`) co
const $ = await next.render$('/landing') expect($('body').text()).toContain('Marketing Root') expect($('p').text()).toBe('hello world {}') }) if (isNextDev) { it('should add getters when new root layouts are
{ "filepath": "test/e2e/app-dir/app-root-params-getters/multiple-roots.test.ts", "language": "typescript", "file_size": 5160, "cut_index": 716, "middle_length": 229 }
tTestSetup } from 'e2e-utils' import execa from 'execa' import { join } from 'path' import { retry } from 'next-test-utils' // Each fixture has a typecheck-validation.ts that imports from 'next/root-params' // and uses @ts-expect-error to assert correct and incorrect type assignments. // Running `tsc --noEmit` verifie...
check with generated root-params types', async () => { await retry(async () => { await next.readFile(`${next.distDir}/types/root-params.d.ts`) }) await next.stop() try { const { stdout, stderr } = await execa('pnpm'
$fixture)', ({ fixture }) => { const { next, skipped } = nextTestSetup({ files: join(__dirname, 'fixtures', fixture), skipDeployment: true, }) if (skipped) { return } it('should pass type
{ "filepath": "test/e2e/app-dir/app-root-params-getters/typecheck.test.ts", "language": "typescript", "file_size": 1266, "cut_index": 524, "middle_length": 229 }
This file is NOT a React component — it only exists to validate // the generated root-params.d.ts types via `tsc --noEmit`. // Lines marked @ts-expect-error must produce a type error; if they // don't, tsc itself will fail ("Unused '@ts-expect-error' directive"). import { lang, locale, path } from 'next/root-params' /...
ng | undefined = await locale() // ok // @ts-expect-error — locale() does not return a number const _localeBad: number = await locale() // --- path: Promise<string[] | undefined> --- const _pathVal: string[] | undefined = await path() // ok // @
const _langVal: string | undefined = await lang() // ok // @ts-expect-error — lang() does not return a number const _langBad: number = await lang() // --- locale: Promise<string | undefined> --- const _localeVal: stri
{ "filepath": "test/e2e/app-dir/app-root-params-getters/fixtures/simple/typecheck-validation.ts", "language": "typescript", "file_size": 1108, "cut_index": 515, "middle_length": 229 }
t { lang, locale } from 'next/root-params' import { Suspense } from 'react' export default async function Page({ params }) { return ( <div> <p> root params shouldn't need a suspense a suspense boundary <span id="root-params"> {JSON.stringify({ lang: await lang(), ...
in <code>generateStaticParams</code>) <Suspense> <DynamicSlug params={params} /> </Suspense> </p> </div> ) } async function DynamicSlug({ params }) { const { slug } = await params return <span id="dynamic-params">
ovide a value
{ "filepath": "test/e2e/app-dir/app-root-params-getters/fixtures/simple/app/[lang]/[locale]/other/[slug]/page.tsx", "language": "tsx", "file_size": 803, "cut_index": 517, "middle_length": 14 }
g } from 'next/root-params' import { cacheTag, updateTag } from 'next/cache' import { connection } from 'next/server' import { Suspense } from 'react' let flagValue = false async function getFlag() { 'use cache: remote' cacheTag('flag-tag') return flagValue } async function conditionalOnAnotherCache() { 'use...
lt.lang)}</p> <p id="random">{result.random}</p> <form> <button id="enable-flag" formAction={async () => { 'use server' flagValue = true updateTag('flag-tag') }}
{ lang: await lang(), random } } return { lang: null, random } } async function Runtime() { await connection() const result = await conditionalOnAnotherCache() return ( <div> <p id="lang-value">{String(resu
{ "filepath": "test/e2e/app-dir/app-root-params-getters/fixtures/use-cache-runtime/app/[lang]/[countryCode]/conditional-on-another-cache/page.tsx", "language": "tsx", "file_size": 1443, "cut_index": 524, "middle_length": 229 }
{ lang } from 'next/root-params' import { connection } from 'next/server' import { Suspense } from 'react' async function maybeReadsRootParam(readLang: boolean) { 'use cache: remote' const random = await fetch( 'https://next-data-api-endpoint.vercel.app/api/random' ).then((res) => res.text()) if (readLa...
<p id="with-lang-random">{withLang.random}</p> <p id="with-lang-value">{String(withLang.lang)}</p> <p id="without-lang-random">{withoutLang.random}</p> <p id="without-lang-value">{String(withoutLang.lang)}</p> </div> ) } expor
heHandler` adds `lang` // to `knownRootParamsByFunctionId` before the `false` call's lookup runs. const withLang = await maybeReadsRootParam(true) const withoutLang = await maybeReadsRootParam(false) return ( <div>
{ "filepath": "test/e2e/app-dir/app-root-params-getters/fixtures/use-cache-runtime/app/[lang]/[countryCode]/maybe-reads-root-param/page.tsx", "language": "tsx", "file_size": 1125, "cut_index": 518, "middle_length": 229 }
from 'e2e-utils' describe('tailwind-css', () => { const { next } = nextTestSetup({ files: __dirname, dependencies: { autoprefixer: '10.4.19', postcss: '8.4.38', tailwindcss: '3.4.4', }, }) it('works when importing tailwind/tailwind.css', async () => { const browser = await nex...
.getComputedCss('color') expect(cssBlue).toBe('rgb(37, 99, 235)') expect(next.cliOutput).not.toContain('Module not found') expect(next.cliOutput).not.toContain("Can't resolve") } finally { await browser.close() } })
test-link')
{ "filepath": "test/e2e/app-dir/tailwind-css/tailwind-css.test.ts", "language": "typescript", "file_size": 810, "cut_index": 536, "middle_length": 14 }
120 }, { pathname: '/nested/c', dynamic: true, revalidate: 120 }, { pathname: '/metadata', dynamic: true, revalidate: 120 }, { pathname: '/on-demand/a', dynamic: true }, { pathname: '/on-demand/b', dynamic: true }, { pathname: '/on-demand/c', dynamic: true }, { pathname: '/loading/a', dynamic: true, revali...
'/no-suspense/nested/c', dynamic: true, emptyStaticPart: true }, { pathname: '/dynamic/force-dynamic', dynamic: 'force-dynamic' }, { pathname: '/dynamic/force-dynamic/nested/a', dynamic: 'force-dynamic' }, { pathname: '/dynamic/force-dynamic/nested/
: '/no-suspense', dynamic: true, emptyStaticPart: true }, { pathname: '/no-suspense/nested/a', dynamic: true, emptyStaticPart: true }, { pathname: '/no-suspense/nested/b', dynamic: true, emptyStaticPart: true }, { pathname:
{ "filepath": "test/e2e/app-dir/ppr-full/ppr-full.test.ts", "language": "typescript", "file_size": 32863, "cut_index": 1331, "middle_length": 229 }
const Dynamic = async ({ pathname, fallback = null, params = null }) => { if (fallback) { return <div data-fallback>Dynamic Loading...</div> } const headers = await next.headers() const messages = [] for (const name of ['x-test-input', 'user-agent']) { messages.push({ name, value: headers.get(name) ...
<dt> Header: <code>{name}</code> </dt> <dd>{value ?? `MISSING:${name.toUpperCase()}`}</dd> </React.Fragment> ))} {params && ( <> <dt>Params</dt> <dd data-params={JSON.
value }) => ( <React.Fragment key={name}>
{ "filepath": "test/e2e/app-dir/ppr-full/components/dynamic.jsx", "language": "jsx", "file_size": 976, "cut_index": 582, "middle_length": 52 }
uspense, unstable_postpone as postpone } from 'react' import { Optimistic } from '../../../../components/optimistic' import { ServerHtml } from '../../../../components/server-html' export const dynamic = 'force-dynamic' export default async (props) => { const searchParams = await props.searchParams return ( <...
</Suspense> </> ) } function IncidentalPostpone() { // This component will postpone but is not using // any dynamic APIs so we expect it to simply client render if (typeof window === 'undefined') { postpone('incidentally') } return <d
tpone />
{ "filepath": "test/e2e/app-dir/ppr-full/app/dynamic-data/incidental-postpone/force-dynamic/page.jsx", "language": "jsx", "file_size": 814, "cut_index": 522, "middle_length": 14 }
dent' import { isNextDev, isNextStart, nextTestSetup } from 'e2e-utils' describe('app-fetch-deduping', () => { if (isNextStart) { describe('during static generation', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true }) let externalServerPort: number let externalServer:...
tus" search param, override the response status if (overrideStatus) { res.statusCode = Number(overrideStatus) } else { successfulRequests.push(req.url) } // Generate a response with more than
const parsedUrl = new URL( req.url, `http://localhost:${externalServerPort}` ) const overrideStatus = parsedUrl.searchParams.get('status') // if the requested url has a "sta
{ "filepath": "test/e2e/app-dir/app-fetch-deduping/app-fetch-deduping.test.ts", "language": "typescript", "file_size": 4961, "cut_index": 614, "middle_length": 229 }
nents/app-router-headers' describe('app dir - css - experimental inline css', () => { const { next, isNextDev } = nextTestSetup({ files: __dirname, }) ;(isNextDev ? describe.skip : describe)('Production only', () => { it('should render page with correct styles', async () => { const browser = await ...
await next.fetch(`/a?${NEXT_RSC_UNION_QUERY}`, { method: 'GET', headers: { rsc: '1', }, }) ).text() const style = 'font-size' expect(rscPayload).toContain('__PAGE__') // sanity check
) expect(await p.getComputedCss('color')).toBe('rgb(255, 255, 0)') // yellow }) it('should not return rsc payload with inlined style as a dynamic client nav', async () => { const rscPayload = await (
{ "filepath": "test/e2e/app-dir/app-inline-css/index.test.ts", "language": "typescript", "file_size": 3302, "cut_index": 614, "middle_length": 229 }
eerio from 'cheerio' import { join } from 'path' import { getCacheHeader } from 'next-test-utils' describe('app-root-param-getters - generateStaticParams', () => { const { next } = nextTestSetup({ files: join(__dirname, 'fixtures', 'generate-static-params'), }) it('should be statically prerenderable', async...
{ const params = { lang: 'en', locale: 'us' } const browser = await next.browser( `/${params.lang}/${params.locale}/other/1`, { // prevent streaming (dynamic) content from being inserted into the DOM disableJavaScript: t
er(response)).toBeOneOf(['HIT', 'PRERENDER']) const $ = cheerio.load(await response.text()) expect($('p').text()).toBe(`hello world ${JSON.stringify(params)}`) }) it('should be part of the static shell', async () =>
{ "filepath": "test/e2e/app-dir/app-root-params-getters/generate-static-params.test.ts", "language": "typescript", "file_size": 2074, "cut_index": 563, "middle_length": 229 }
"use cache" - dev', async () => { const browser = await next.browser('/en/us/use-cache') await waitForNoRedbox(browser) expect(await browser.elementById('param').text()).toBe('en us') }) it('should error when using root params within `unstable_cache` - dev', async () => { const browser ...
g]/[countryCode]/unstable_cache/page.tsx (33:28) @ uncachedGetParams > 33 | return { lang: await lang(), countryCode: await countryCode() } | ^", "stack": [ "uncachedGetParams app/[lang]/[
he used \`import('next/root-params').lang()\` inside \`unstable_cache\`. This is not supported. Use \`"use cache"\` instead.", "environmentLabel": "Server", "label": "Runtime Error", "source": "app/[lan
{ "filepath": "test/e2e/app-dir/app-root-params-getters/use-cache.test.ts", "language": "typescript", "file_size": 13714, "cut_index": 921, "middle_length": 229 }
uspense } from 'react' import { lang, countryCode } from 'next/root-params' import { connection } from 'next/server' import { unstable_cache } from 'next/cache' export default async function Page() { return ( <Suspense fallback="..."> <Runtime /> </Suspense> ) } async function Runtime() { await co...
id="param"> {rootParams.lang} {rootParams.countryCode} </span>{' '} <span id="random">{data}</span> </p> ) } const getCachedParams = unstable_cache(async function uncachedGetParams() { return { lang: await lang(), countryCode:
> <span
{ "filepath": "test/e2e/app-dir/app-root-params-getters/fixtures/use-cache-runtime/app/[lang]/[countryCode]/unstable_cache/page.tsx", "language": "tsx", "file_size": 817, "cut_index": 522, "middle_length": 14 }
ng, countryCode } from 'next/root-params' import { connection } from 'next/server' import { Suspense } from 'react' async function getCachedData() { 'use cache' const random = await fetch( 'https://next-data-api-endpoint.vercel.app/api/random' ).then((res) => res.text()) return { lang: await lang(), coun...
<span id="random">{result.random}</span> </p> <Suspense fallback={<p id="fallback">Loading...</p>}> <Dynamic /> </Suspense> </> ) } async function Dynamic() { await connection() return <p id="dynamic">dynamic</p> }
.lang} {result.countryCode} </span>{' '}
{ "filepath": "test/e2e/app-dir/app-root-params-getters/fixtures/use-cache-runtime/app/[lang]/[countryCode]/use-cache-resume/page.tsx", "language": "tsx", "file_size": 832, "cut_index": 523, "middle_length": 52 }
<div className="flex flex-col items-center justify-center min-h-screen py-2"> <main className="flex flex-col items-center justify-center w-full flex-1 px-20 text-center"> <h1 className="text-blue-600 text-6xl font-bold"> Welcome to{' '} <a className="text-blue-600" href="https://nextj...
s.org/docs" className="p-6 mt-6 text-left border w-96 rounded-xl hover:text-blue-600 focus:text-blue-600" > <h3 className="text-2xl font-bold">Documentation &rarr;</h3> <p className="mt-4 text-xl">
ext-lg bg-gray-100 rounded-md"> pages/index.js </code> </p> <div className="flex flex-wrap items-center justify-around max-w-4xl mt-6 sm:w-full"> <a href="https://nextj
{ "filepath": "test/e2e/app-dir/tailwind-css/app/page.tsx", "language": "tsx", "file_size": 2485, "cut_index": 563, "middle_length": 229 }
uspense, unstable_postpone as postpone } from 'react' import { Optimistic } from '../../../../components/optimistic' import { ServerHtml } from '../../../../components/server-html' export const dynamic = 'force-static' export default async (props) => { const searchParams = await props.searchParams return ( <>...
</Suspense> </> ) } function IncidentalPostpone() { // This component will postpone but is not using // any dynamic APIs so we expect it to simply client render if (typeof window === 'undefined') { postpone('incidentally') } return <di
pone />
{ "filepath": "test/e2e/app-dir/ppr-full/app/dynamic-data/incidental-postpone/force-static/page.jsx", "language": "jsx", "file_size": 813, "cut_index": 522, "middle_length": 14 }
from 'e2e-utils' import { retry } from 'next-test-utils' describe('css-modules-scoping', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should not prefix grid areas', async () => { const browser = await next.browser('/grid') // Check grid-area of header await retry(async () =...
main await retry(async () => { expect( await browser.eval( `window.getComputedStyle(document.querySelector('#main')).gridArea` ) ).toBe('main') }) // Check grid-area of footer await retry(async () =>
sidebar await retry(async () => { expect( await browser.eval( `window.getComputedStyle(document.querySelector('#sidebar')).gridArea` ) ).toBe('sidebar') }) // Check grid-area of
{ "filepath": "test/e2e/app-dir/css-modules-scoping/css-modules-scoping.test.ts", "language": "typescript", "file_size": 1780, "cut_index": 537, "middle_length": 229 }
outdent' import { createRequestTracker } from '../../../lib/e2e-utils/request-tracker' describe('app-root-param-getters - simple', () => { let currentCliOutputIndex = 0 beforeEach(() => { resetCliOutput() }) const getCliOutput = () => { if (next.cliOutput.length < currentCliOutputIndex) { // cli...
reading root params', async () => { const params = { lang: 'en', locale: 'us' } const $ = await next.render$(`/${params.lang}/${params.locale}`) expect($('p').text()).toBe(`hello world ${JSON.stringify(params)}`) }) it('should allow readi
t resetCliOutput = () => { currentCliOutputIndex = next.cliOutput.length } const { next, isNextDev, isTurbopack, isNextDeploy } = nextTestSetup({ files: join(__dirname, 'fixtures', 'simple'), }) it('should allow
{ "filepath": "test/e2e/app-dir/app-root-params-getters/simple.test.ts", "language": "typescript", "file_size": 7385, "cut_index": 716, "middle_length": 229 }
import { Suspense } from 'react' async function conditionalOnRootParam() { 'use cache: remote' const random = await fetch( 'https://next-data-api-endpoint.vercel.app/api/random' ).then((res) => res.text()) const currentLang = await lang() if (currentLang === 'en') { return { lang: currentLang, coun...
e">{String(result.lang)}</p> <p id="country-code-value">{String(result.countryCode)}</p> <p id="random">{result.random}</p> </div> ) } export default async function Page() { return ( <Suspense fallback="Loading..."> <Runtime
Param() return ( <div> <p id="lang-valu
{ "filepath": "test/e2e/app-dir/app-root-params-getters/fixtures/use-cache-runtime/app/[lang]/[countryCode]/conditional-on-root-param/page.tsx", "language": "tsx", "file_size": 939, "cut_index": 606, "middle_length": 52 }
nc function getData() { const responses = await Promise.all([ fetch(`http://localhost:${process.env.TEST_SERVER_PORT}`, { headers: { traceparent: '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01', tracestate: 'vendor1=value1', }, }).then((res) => res.text()), fetch(`htt...
ue3', }, }).then((res) => res.text()), ]) return responses } export default async function StaticTracePage() { const data = await getData() return ( <div> <h1>Static Page with Trace Headers</h1> <p>All responses should
, }).then((res) => res.text()), fetch(`http://localhost:${process.env.TEST_SERVER_PORT}`, { headers: { traceparent: '00-2af7651916cd43dd8448eb211c80319c-d7ad6b7169203333-01', tracestate: 'vendor3=val
{ "filepath": "test/e2e/app-dir/app-fetch-deduping/app/trace-headers/page.js", "language": "javascript", "file_size": 1111, "cut_index": 515, "middle_length": 229 }
from 'next/server' import { cookies } from 'next/headers' import { Suspense } from 'react' export default async function Page() { const currentLang = await lang() const currentLocale = await locale() return ( <main> <div> Root params are{' '} <span id="root-params"> {currentLa...
ide the action result const cookieStore = await cookies() cookieStore.set('my-cookie', Date.now() + '') }} > <button type="submit">Submit form</button> </form> </main> ) } async function Timestamp() {
// rerender the page and return it alongs
{ "filepath": "test/e2e/app-dir/app-root-params-getters/fixtures/simple/app/[lang]/[locale]/rerender-after-server-action/page.tsx", "language": "tsx", "file_size": 961, "cut_index": 582, "middle_length": 52 }
d) { return } it('should generate route validation correctly', async () => { if (isNextDev) { await next.start() await next.fetch('/') } else { await next.build() } try { const dts = await next.readFile(`${getDistDir()}/types/validator.ts`) // sanity check that de...
nerated asynchronously after the server starts. // Might take a few tries before all the relevant types exist. await retry(async () => { const { stdout, stderr } = await execa('pnpm', ['tsc', '--noEmit'], { cwd: next.t
ve passing tsc after the server generated types', async () => { if (isNextDev) { await next.start() } else { await next.build() } try { if (isNextDev) { // In dev mode, route types are ge
{ "filepath": "test/e2e/app-dir/typed-routes-validator/typed-routes-validator.test.ts", "language": "typescript", "file_size": 9808, "cut_index": 921, "middle_length": 229 }
nk' export const links = [ { href: '/', tag: 'pre-generated' }, { href: '/metadata', tag: 'pre-generated' }, { href: '/nested/a', tag: 'pre-generated' }, { href: '/nested/b', tag: 'on-demand' }, { href: '/nested/c', tag: 'on-demand' }, { href: '/on-demand/a', tag: 'on-demand, no-gsp' }, { href: '/on-dema...
{ href: '/no-suspense/nested/b', tag: 'no suspense, on-demand' }, { href: '/no-suspense/nested/c', tag: 'no suspense, on-demand' }, { href: '/dynamic/force-dynamic', tag: "dynamic = 'force-dynamic'" }, { href: '/dynamic/force-dynamic/nested/a'
on-demand' }, { href: '/loading/c', tag: 'loading.jsx, on-demand' }, { href: '/static', tag: 'static' }, { href: '/no-suspense', tag: 'no suspense' }, { href: '/no-suspense/nested/a', tag: 'no suspense, pre-generated' },
{ "filepath": "test/e2e/app-dir/ppr-full/components/links.jsx", "language": "jsx", "file_size": 2294, "cut_index": 563, "middle_length": 229 }
ooth scroll optimization', () => { const { next } = nextTestSetup({ files: __dirname + '/fixtures/optimized', }) const getTopScroll = async (browser: any) => await browser.eval('document.documentElement.scrollTop') const waitForScrollToComplete = async (browser: any, expectedY: number) => { await ...
h scroll CSS and data attribute without warning', async () => { const browser = await next.browser('/page1') await scrollTo(browser, 1000) expect(await getTopScroll(browser)).toBe(1000) // Wait for page to be rendered await browser.wa
window.scrollTo(0, ${y})`) // Add a small delay for scroll to complete await browser.eval('new Promise(resolve => setTimeout(resolve, 100))') await waitForScrollToComplete(browser, y) } it('should work with smoot
{ "filepath": "test/e2e/app-dir/router-disable-smooth-scroll/router-disable-smooth-scroll.optimized.test.ts", "language": "typescript", "file_size": 4040, "cut_index": 614, "middle_length": 229 }
connection } from 'next/server' /// Page is suspended and being caught by the layout Suspense boundary export default function Page() { return ( <div className="container"> <SuspendedComponent /> </div> ) } async function SuspendedComponent() { await connection() await new Promise((resolve) => ...
Timeout(resolve, 500)) return <div>nested suspended component</div> } export async function generateMetadata() { // Slow but static metadata await new Promise((resolve) => setTimeout(resolve, 2 * 1000)) return { title: 'dynamic-page - partial'
it connection() await new Promise((resolve) => set
{ "filepath": "test/e2e/app-dir/ppr-metadata-streaming/app/dynamic-page/partial/page.tsx", "language": "tsx", "file_size": 836, "cut_index": 520, "middle_length": 52 }
mport { nextTestSetup } from 'e2e-utils' describe('rewrite-with-search-params', () => { const { next, isNextDeploy } = nextTestSetup({ files: __dirname, }) it('should not contain params in search params after rewrite', async () => { const deploymentHost = isNextDeploy ? new URL(next.url).hostname : null...
ON.parse($('#search-params-value').text()) const params = JSON.parse($('#params-value').text()) expect(searchParams).toEqual({ param: 'value', }) expect(params).toEqual({ domain: expect.stringMatching(/[\w-]+/), section:
, { param: 'value', }, { headers: shouldForceHostHeader ? { host: 'vercel-test.vercel.app', } : undefined, } ) const searchParams = JS
{ "filepath": "test/e2e/app-dir/rewrite-with-search-params/rewrite-with-search-params.test.ts", "language": "typescript", "file_size": 1036, "cut_index": 513, "middle_length": 229 }
dboxTotalErrorCount, } from 'next-test-utils' import stripAnsi from 'strip-ansi' const expectedTimeoutErrorMessage = 'Filling a cache during prerender timed out, likely because request-specific arguments such as params, searchParams, cookies() or dynamic data were used inside "use cache".' describe('use-cache-hangi...
meout', async () => { const outputIndex = next.cliOutput.length const browser = await next.browser('/uncached-promise') // The request is pending while we stall on the hanging inputs, and // playwright will wait for the loa
ped) { return } if (isNextDev) { // TODO(restart-on-cache-miss): reenable when fixed describe.skip('when an uncached promise is used inside of "use cache"', () => { it('should show an error toast after a ti
{ "filepath": "test/e2e/app-dir/use-cache-hanging-inputs/use-cache-hanging-inputs.test.ts", "language": "typescript", "file_size": 6969, "cut_index": 716, "middle_length": 229 }
rt { nextTestSetup } from 'e2e-utils' import { ElementHandle } from 'playwright' describe('scripts', () => { const { next } = nextTestSetup({ files: __dirname, }) // TODO: fix test case in webpack // It's failing with `Could not find the module ".../app/client#component.tsx#" in the React Client Manifest....
cript' )) as ElementHandle<HTMLScriptElement>[] expect(scripts.length).toBeGreaterThan(0) for (const script of scripts) { const src = await script.evaluate((script) => script.src) expect(src).not.toContain('#') exp
terType) => { const browser = await next.browser(routerType === 'app' ? '/' : '/pages') expect(await browser.elementByCss('p').text()).toBe('hello world') const scripts = (await browser.elementsByCss( 's
{ "filepath": "test/e2e/app-dir/resource-url-encoding/resource-url-encoding.test.ts", "language": "typescript", "file_size": 2295, "cut_index": 563, "middle_length": 229 }
{ nextTestSetup } from 'e2e-utils' describe('app-dir static-generation-status', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should render the page using notFound with status 404', async () => { const { status } = await next.fetch('/not-found-page') expect(status).toBe(404) }...
}) it('should respond with 308 status code if permanent flag is set', async () => { const { status } = await next.fetch('/redirect-permanent', { redirect: 'manual', }) expect(status).toBe(308) }) it('should render the non existed
oBe(307) }) it('should render the client page using redirect with status 307', async () => { const { status } = await next.fetch('/redirect-client-page', { redirect: 'manual', }) expect(status).toBe(307)
{ "filepath": "test/e2e/app-dir/static-generation-status/index.test.ts", "language": "typescript", "file_size": 1125, "cut_index": 518, "middle_length": 229 }
' import { getPrerenderOutput } from './utils' import { retry } from 'next-test-utils' describe('Cache Components Errors', () => { const { next, isTurbopack, isNextStart, skipped } = nextTestSetup({ files: __dirname + '/fixtures/console-patch', skipDeployment: true, skipStart: !isNextDev, env: { ...
warn about sync IO if console.log is patched to call new Date() internally', async () => { await next.fetch('/404') // Wait for after 404 is rendered to the console. await retry(async () => { expect(next.cliOutput
gth }) afterEach(async () => { if (isNextStart) { await next.stop() } }) describe('Sync IO in console methods', () => { describe('Console Patching', () => { if (isNextDev) { it('does not
{ "filepath": "test/e2e/app-dir/cache-components-errors/cache-components-console-patch.test.ts", "language": "typescript", "file_size": 2567, "cut_index": 563, "middle_length": 229 }
f (skipped) { return } describe('Warning for Bypassing Caches in Dev', () => { async function enableDraftMode() { const draftRes = await next.fetch('/api/draft/enable', { redirect: 'manual', }) const setCookie = draftRes.headers.get('set-cookie') const cookie = setCookie?.sp...
'/', { headers: { 'cache-control': 'no-cache' }, }) expect(stripGetLines(next.cliOutput.slice(from))) .toMatchInlineSnapshot(` "Route / is rendering with server caches disabled. For this navigation, Component M
c () => { // Wait for pages to be loaded to ensure the logging for the test page is the only thing that can be logged. await next.fetch('/404') const from = next.cliOutput.length await next.fetch(
{ "filepath": "test/e2e/app-dir/cache-components-errors/cache-components-dev-cache-bypass.test.ts", "language": "typescript", "file_size": 6699, "cut_index": 716, "middle_length": 229 }
} = nextTestSetup({ files: __dirname + '/fixtures/http-access-fallback-prerender', skipStart: !isNextDev, skipDeployment: true, }) if (skipped) { return } let cliOutputLength: number beforeEach(() => { cliOutputLength = next.cliOutput.length }) afterEach(async () => { if (isNex...
der', }) } if (!prerenderMode || prerenderMode === 'false') { testCases.push({ isDebugPrerender: false, name: 'Build Without --debug-prerender', }) } } describe.each(testCases)('$name', ({ isDebugPrerender
' }) } else { const prerenderMode = process.env.NEXT_TEST_DEBUG_PRERENDER if (!prerenderMode || prerenderMode === 'true') { testCases.push({ isDebugPrerender: true, name: 'Build With --debug-preren
{ "filepath": "test/e2e/app-dir/cache-components-errors/cache-components-errors.http-access-fallback-prerender.test.ts", "language": "typescript", "file_size": 8054, "cut_index": 716, "middle_length": 229 }
tTestSetup } from 'e2e-utils' describe('Lazy Module Init', () => { const { next, isNextDev, skipped } = nextTestSetup({ files: __dirname + '/fixtures/lazy-module-init', skipStart: true, skipDeployment: true, }) if (skipped) { return } if (isNextDev) { it('does not run in dev', () => {})...
xpect(next.cliOutput).toContain('◐ /[dyn]') let $ $ = await next.render$('/server') expect($('#id').text().length).toBeGreaterThan(0) $ = await next.render$('/client') expect($('#id').text().length).toBeGreaterThan(0) $ = await n
Error('expected build not to fail for fully static project') } expect(next.cliOutput).toContain('○ /server') expect(next.cliOutput).toContain('○ /client') expect(next.cliOutput).toContain('○ /client-page') e
{ "filepath": "test/e2e/app-dir/cache-components-errors/cache-components-errors.module-scope.test.ts", "language": "typescript", "file_size": 1305, "cut_index": 524, "middle_length": 229 }