prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
/* eslint-env jest */ import path from 'path' import { nextTestSetup, FileRef } from 'e2e-utils' describe('app dir - with proxy in src dir', () => { const { next } = nextTestSetup({ files: { 'src/app': new FileRef(path.join(__dirname, 'app')), 'next.config.js': new FileRef(path.join(__dirname, 'next....
') await browser.addCookie({ name: 'test-cookie', value: 'test-cookie-response', }) await browser.refresh() const html = await browser.eval('document.documentElement.innerHTML') expect(html).toContain('test-cookie-response
cookie = (await cookies()).get('test-cookie') return NextResponse.json({ cookie }) } `, }, }) it('works without crashing when using RequestStore', async () => { const browser = await next.browser('/
{ "filepath": "test/e2e/app-dir/app-middleware-proxy/app-middleware-proxy-in-src-dir.test.ts", "language": "typescript", "file_size": 1008, "cut_index": 512, "middle_length": 229 }
t.browser('/') expect(next.cliOutput).toMatch( /GET \/ 200 in .* \(next\.js:.*, proxy\.ts:.*, application-code:.*\)/ ) }) } it('should filter correctly after proxy rewrite', async () => { const browser = await next.browser('/start') await browser.eval('window.beforeNav = 1') aw...
oJson: (res: Response) => res.json(), }, { title: 'next/headers', path: '/headers', toJson: async (res: Response) => { const $ = cheerio.load(await res.text()) return JSON.parse($('#headers').text()) }, }
.each([ { title: 'Serverless Functions', path: '/api/dump-headers-serverless', toJson: (res: Response) => res.json(), }, { title: 'Edge Functions', path: '/api/dump-headers-edge', t
{ "filepath": "test/e2e/app-dir/app-middleware-proxy/app-middleware-proxy.test.ts", "language": "typescript", "file_size": 9975, "cut_index": 921, "middle_length": 229 }
{ unstable_cache } from 'next/cache' import { headers as nextHeaders } from 'next/headers' const getCachedValue = unstable_cache( async () => Math.random().toString(), ['proxy-cache-probe'] ) /** * @param {import('next/server').NextRequest} request */ export async function proxy(request) { const headersFromRe...
) { throw new Error('Expected headers from client to match') } // Cannot set draftMode in nodejs runtime // TODO: Investigate https://github.com/vercel/next.js/pull/85174 // if (request.nextUrl.searchParams.get('draft')) { // ;(await draf
lo-from-proxy') // make sure headers() from `next/headers` is behaving properly if ( headersFromRequest.get('x-from-client') && headersFromNext.get('x-from-client') !== headersFromRequest.get('x-from-client')
{ "filepath": "test/e2e/app-dir/app-middleware-proxy/proxy.js", "language": "javascript", "file_size": 2995, "cut_index": 563, "middle_length": 229 }
mport { nextTestSetup } from 'e2e-utils' import { retry } from 'next-test-utils' describe('instrumentation-order', () => { const { next } = nextTestSetup({ files: __dirname, skipDeployment: true, }) it('should work', async () => { await next.fetch('/') await retry(async () => { // `next.c...
on:register:timeout', 'instrumentation:register:end', 'global-side-effect:app-router-page', ] const searchedLines = cliOutputLines.filter((line) => ORDERED_LOGS.includes(line.trim()) ) expect(searchedLines).
verLog = next.cliOutput.split('Ready in')[1] const cliOutputLines = serverLog.split('\n') const ORDERED_LOGS = [ 'instrumentation:side-effect', 'instrumentation:register:begin', 'instrumentati
{ "filepath": "test/e2e/app-dir/instrumentation-order/instrumentation-order.test.ts", "language": "typescript", "file_size": 1035, "cut_index": 513, "middle_length": 229 }
Setup } from 'e2e-utils' describe('next-config-ts-type-error-cjs', () => { // TODO: Remove this once we bump minimum Node.js version to v22 if (!(process.features as any).typescript) { it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {}) return } const { next...
ait next.start() const $ = await next.render$('/') expect($('p').text()).toBe('foo') } else { const { cliOutput } = await next.build() await expect(cliOutput).toContain( `Type 'string' is not assignable to type 'number'.
(CJS)', async () => { if (isNextDev) { aw
{ "filepath": "test/e2e/app-dir/next-config-ts-native-ts/type-error/next-config-ts-type-error-cjs.test.ts", "language": "typescript", "file_size": 861, "cut_index": 529, "middle_length": 52 }
utils' describe('next-config-ts-type-error-esm', () => { // TODO: Remove this once we bump minimum Node.js version to v22 if (!(process.features as any).typescript) { it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {}) return } const { next, isNextDev, skipp...
if (isNextDev) { await next.start() const $ = await next.render$('/') expect($('p').text()).toBe('foo') } else { const { cliOutput } = await next.build() await expect(cliOutput).toContain( `Type 'string' is no
throw with type error on build (ESM)', async () => {
{ "filepath": "test/e2e/app-dir/next-config-ts-native-ts/type-error/next-config-ts-type-error-esm.test.ts", "language": "typescript", "file_size": 909, "cut_index": 547, "middle_length": 52 }
import { nextTestSetup } from 'e2e-utils' describe('next-config-ts-import-js-extensions-esm', () => { // TODO: Remove this once we bump minimum Node.js version to v22 if (!(process.features as any).typescript) { it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {}) ...
ender$('/') const text = $('p').text() expect(text).toContain('jsESM') expect(text).toContain('cjs') expect(text).toContain('mjs') expect(text).toContain('cts') expect(text).toContain('mts') expect(text).toContain('ts') }) })
= await next.r
{ "filepath": "test/e2e/app-dir/next-config-ts-native-ts/import-js-extensions-esm/next-config-ts-import-js-extensions-esm.test.ts", "language": "typescript", "file_size": 782, "cut_index": 512, "middle_length": 14 }
this inside of retry in case button event handler // isn't ready yet await browser.elementById('increment-button-1').click() const counterDisplay1 = await browser.elementById('counter-display-1') expect(await counterDisplay1.text()).toBe('Count: 1') }) await browser.elementById('increm...
2 = await browser.elementById('counter-display-2') await incrementButton2.click() await incrementButton2.click() await incrementButton2.click() await incrementButton2.click() await incrementButton2.click() await incrementButton2.cli
ate some state here, too. const linkToPage2 = await browser.elementByCss('a[href="/page/2"]') await linkToPage2.click() const incrementButton2 = await browser.elementById('increment-button-2') const counterDisplay
{ "filepath": "test/e2e/app-dir/back-forward-cache/back-forward-cache.test.ts", "language": "typescript", "file_size": 10756, "cut_index": 921, "middle_length": 229 }
These tests * use the experimental.exposeTestingApiInProductionBuild flag to enable the * API in production mode for testing purposes. */ import { NextInstance, nextTestSetup } from 'e2e-utils' import { instant } from '@next/playwright' import type * as Playwright from 'playwright' import { join } from 'node:path' ...
NextInstance, url: string, options?: { cookies?: Array<{ name: string; value: string }> } ): Promise<Playwright.Page> { let page: Playwright.Page await next.browser(url, { beforePageLoad(p) { page = p if (options?.cookies) {
tual Playwright helper package. The * Next.js test infra wraps Playwright with its own BrowserInterface, but * the Instant Navigation Testing API is designed to work with native Playwright. */ async function openPage( next:
{ "filepath": "test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts", "language": "typescript", "file_size": 31766, "cut_index": 1331, "middle_length": 229 }
on HomePage() { return ( <div> <h1 data-testid="home-title">Instant Navigation API Test</h1> <Link href="/target-page" id="link-to-target"> Go to target page </Link> <Link href="/runtime-prefetch-target?myParam=testValue" id="link-to-runtime-prefetch" > ...
</Link> <Link href="/dynamic-params/hello" id="link-to-static-dynamic-params"> Go to static dynamic params page </Link> <Link href="/ungenerated-params/anything" id="link-to-ungenerated-params"> Go to ungenerated params
rget </Link> <Link href="/cookies-page" id="link-to-cookies-page"> Go to cookies page </Link> <Link href="/dynamic-params/unknown" id="link-to-dynamic-params"> Go to dynamic params page
{ "filepath": "test/e2e/app-dir/instant-navigation-testing-api/fixtures/default/app/page.tsx", "language": "tsx", "file_size": 2298, "cut_index": 563, "middle_length": 229 }
t { Suspense } from 'react' type SearchParams = { [key: string]: string | string[] | undefined } export default function SearchParamsPage({ searchParams, }: { searchParams: Promise<SearchParams> }) { return ( <div> <h1 data-testid="search-params-title">Search Params Page</h1> <Suspense f...
ense> </div> ) } async function SearchParamContent({ searchParams, }: { searchParams: Promise<SearchParams> }) { const params = await searchParams const foo = params.foo return <div data-testid="search-param-content">foo: {foo ?? 'not set
> </Susp
{ "filepath": "test/e2e/app-dir/instant-navigation-testing-api/fixtures/default/app/search-params-page/page.tsx", "language": "tsx", "file_size": 798, "cut_index": 517, "middle_length": 14 }
{ Suspense } from 'react' import { connection } from 'next/server' export const unstable_instant = { unstable_samples: [{ searchParams: { myParam: 'testValue' } }], } export const unstable_prefetch = 'force-runtime' type SearchParams = { [key: string]: string | string[] | undefined } export default async function...
/div> } > <DynamicContent /> </Suspense> </div> ) } async function RuntimePrefetchableContent({ searchParams, }: { searchParams: Promise<SearchParams> }) { const params = await searchParams const myParam = params.
tid="outer-loading">Loading...</div>}> <RuntimePrefetchableContent searchParams={searchParams} /> </Suspense> <Suspense fallback={ <div data-testid="inner-loading">Loading dynamic content...<
{ "filepath": "test/e2e/app-dir/instant-navigation-testing-api/fixtures/default/app/runtime-prefetch-target/page.tsx", "language": "tsx", "file_size": 1219, "cut_index": 518, "middle_length": 229 }
import { Suspense } from 'react' // Intentionally no generateStaticParams — this exercises the fallback-shell // path for a dynamic route whose URL is not covered by static params. export default function UngeneratedParamsPage({ params, }: { params: Promise<{ slug: string }> }) { return ( <div> <h1 dat...
<ParamContent params={params} /> </Suspense> </div> ) } async function ParamContent({ params }: { params: Promise<{ slug: string }> }) { const { slug } = await params return <div data-testid="ungenerated-param-value">slug: {slug}</div> }
>
{ "filepath": "test/e2e/app-dir/instant-navigation-testing-api/fixtures/default/app/ungenerated-params/[slug]/page.tsx", "language": "tsx", "file_size": 785, "cut_index": 512, "middle_length": 14 }
{ Suspense } from 'react' // Same shape as `ungenerated-params/[slug]` (no `generateStaticParams`), but // this route opts into runtime prefetching. The prefetch therefore includes // the resolved `slug`, so the param should be visible inside the instant // scope instead of suspending. export const unstable_instant: ...
Suspense fallback={ <div data-testid="ungenerated-params-runtime-fallback"> Loading params... </div> } > <ParamContent params={params} /> </Suspense> </div> ) } async function Param
ion UngeneratedParamsRuntimePage({ params, }: { params: Promise<{ slug: string }> }) { return ( <div> <h1 data-testid="ungenerated-params-runtime-title"> Ungenerated Params Runtime Page </h1> <
{ "filepath": "test/e2e/app-dir/instant-navigation-testing-api/fixtures/default/app/ungenerated-params-runtime/[slug]/page.tsx", "language": "tsx", "file_size": 1178, "cut_index": 518, "middle_length": 229 }
nst hasAudienceHome = async () => { await check( () => browser.waitForElementByCss('#audience-home').text(), 'Audience home' ) } const hasDemographics = async () => { await check( () => browser.waitForElementByCss('#demographics').text(),...
}` ) } // Initial page const step1 = async () => { await hasHome() await hasViewsHome() await hasAudienceHome() await checkUrlPath('') } await step1() cons
'Subscribers' ) } const checkUrlPath = async (path: string) => { await check( () => browser.url(), `${next.url}/parallel-tab-bar${path}${trailingSlash ? '/' : ''
{ "filepath": "test/e2e/app-dir/parallel-routes-and-interception/parallel-routes-and-interception.test.ts", "language": "typescript", "file_size": 35251, "cut_index": 2151, "middle_length": 229 }
k from 'next/link' export default function Layout({ children, modal }) { return ( <div> <h1>intercepting-siblings</h1> <div style={{ border: '1px solid black', padding: '1rem' }}> {children} </div> <hr /> <div style={{ border: '1px solid black', padding: '1rem' }}>{modal}</d...
cepting-siblings/1</Link> </li> <li> <Link href="/intercepting-siblings/2">/intercepting-siblings/2</Link> </li> <li> <Link href="/intercepting-siblings/3">/intercepting-siblings/3</Link> </li>
ings/1">/inter
{ "filepath": "test/e2e/app-dir/parallel-routes-and-interception/app/intercepting-siblings/layout.js", "language": "javascript", "file_size": 819, "cut_index": 522, "middle_length": 14 }
Link from 'next/link' function AudienceNav() { return ( <ul> <li> <Link id="home-link-audience" href="/parallel-tab-bar"> Home </Link> </li> <li> <Link id="demographics-link" href="/parallel-tab-bar/demographics"> Demographics </Link> <...
</Link> </li> <li> <Link id="view-duration-link" href="/parallel-tab-bar/view-duration"> View Duration </Link> </li> </ul> ) } export default function Layout({ children, audience, views }) { retur
<ul> <li> <Link id="home-link-views" href="/parallel-tab-bar"> Home </Link> </li> <li> <Link id="impressions-link" href="/parallel-tab-bar/impressions"> Impressions
{ "filepath": "test/e2e/app-dir/parallel-routes-and-interception/app/parallel-tab-bar/layout.js", "language": "javascript", "file_size": 1194, "cut_index": 518, "middle_length": 229 }
te (e.g., /groups/123) to a deeper route // (e.g., /groups/123/new) should trigger the modal interception. // // The bug was that the regex pattern used [^/]+ which only matched single segments, // so interception failed when the source route had multiple segments like /groups/123 const browser = aw...
(async () => { const modalText = await browser.elementById('modal').text() expect(modalText).toContain('Modal: New item for group 123') }) // The children should still show the group page await retry(async () => { const child
Group 123') expect(text).toContain('New Item') }) // Navigate from /groups/123 to /groups/123/new // This should trigger the modal interception await browser.elementById('new-link').click() await retry
{ "filepath": "test/e2e/app-dir/interception-dynamic-single-segment/interception-dynamic-single-segment.test.ts", "language": "typescript", "file_size": 11756, "cut_index": 921, "middle_length": 229 }
stDataServer } from 'test-data-service/writer' import { createTestLog } from 'test-log' describe('avoid-popstate-flash', () => { if ((global as any).isNextDev || (global as any).isNextDeploy) { // this is skipped in dev because PPR is not enabled in dev // and in deploy we can't rely on this test data servic...
server = createTestDataServer(async (key, res) => { TestLog.log('REQUEST: ' + key) if (autoresolveRequests) { res.resolve() return } if (pendingRequests.has(key)) { throw new Error('Request already pending
server?.close() }) test('does not flash back to partial PPR data during back/forward navigation', async () => { const TestLog = createTestLog() let autoresolveRequests = true let pendingRequests = new Map()
{ "filepath": "test/e2e/app-dir/ppr-navigations/avoid-popstate-flash/avoid-popstate-flash.test.ts", "language": "typescript", "file_size": 3268, "cut_index": 614, "middle_length": 229 }
er-only' import { unstable_noStore } from 'next/cache' // NOTE: I've intentionally not yet moved these helpers into a shared module, to // avoid early abstraction. I will if/when we start using them for other tests. // They are based on the testing patterns we use all over the React codebase, so // I'm reasonably con...
inning up a // data server. await new Promise<void>((resolve) => setTimeout(() => resolve(), ARTIFICIAL_DELAY) ) if (!isStatic) { unstable_noStore() } return key } const response = await fetch( TEST_DATA_SERVICE_
onst searchParams = new URLSearchParams({ key, }) if (!TEST_DATA_SERVICE_URL) { // If environment variable is not set, resolve automatically after a delay. // This is so you can run the test app locally without sp
{ "filepath": "test/e2e/app-dir/ppr-navigations/avoid-popstate-flash/app/test-data-service.ts", "language": "typescript", "file_size": 1446, "cut_index": 524, "middle_length": 229 }
lient' import { Component, createContext, use, useState } from 'react' const ShouldFallbackThrowContext = createContext(false) export function ShouldFallbackThrowContainer({ children }) { const [shouldFallbackThrow, setShouldFallbackThrow] = useState(false) return ( <> <label> Throw if fallback...
allback({ children }) { if (use(ShouldFallbackThrowContext)) { throw new Error('Unexpected fallback') } return children } class ErrorBoundary extends Component<{ children: React.ReactNode }> { state = { error: null } static getDerivedStateFr
d)} /> </label> <ShouldFallbackThrowContext.Provider value={shouldFallbackThrow}> <ErrorBoundary>{children}</ErrorBoundary> </ShouldFallbackThrowContext.Provider> </> ) } export function F
{ "filepath": "test/e2e/app-dir/ppr-navigations/avoid-popstate-flash/app/some-page/client.tsx", "language": "tsx", "file_size": 1191, "cut_index": 518, "middle_length": 229 }
ribe.skip('search-params', () => { if ((global as any).isNextDev) { test('ppr is disabled in dev', () => {}) return } const { next } = nextTestSetup({ files: __dirname, }) test( 'updates page data during a nav even if no shared layouts have changed ' + '(e.g. updating a search param on...
firm that the page re-rendered with the new search params. const searchParamsContainer = await browser.elementById('search-params') expect(await searchParamsContainer.innerText()).toBe( 'Search params: {"blazing":"good"}' ) }
entByCss('a') await link.click() // Con
{ "filepath": "test/e2e/app-dir/ppr-navigations/search-params/search-params.test.ts", "language": "typescript", "file_size": 921, "cut_index": 606, "middle_length": 52 }
NAR-423): Migrate to Cache Components. describe.skip('prefetch-navigation', () => { const { next, isNextDev } = nextTestSetup({ files: __dirname, }) if (isNextDev) { it('is skipped in dev because there are no prefetches', () => {}) return } it('should render the prefetch without waiting for the ...
const pathname = url.pathname if (headers['rsc'] === '1' && !headers['next-router-prefetch']) { // Create a promise that will be resolved by the later test code let resolvePromise: () => void const promise = n
eforePageLoad(page) { page.route('**/catch-all/**', async (route) => { const request = route.request() const headers = await request.allHeaders() const url = new URL(request.url())
{ "filepath": "test/e2e/app-dir/ppr-navigations/prefetch-navigation/prefetch-navigation.test.ts", "language": "typescript", "file_size": 3038, "cut_index": 563, "middle_length": 229 }
stDataServer } from 'test-data-service/writer' import { createTestLog } from 'test-log' describe('stale-prefetch-entry', () => { if ((global as any).isNextDev || (global as any).isNextDeploy) { // this is skipped in dev because PPR is not enabled in dev // and in deploy we can't rely on this test data servic...
't contain dynamic holes. This // prevented the dynamic data from ever streaming in. test( 'works if a prefetched route entry has become stale (too much ' + 'time has elapsed since it was prefetched)', async () => { const TestLog =
server?.close() }) // This is a regression test where a condition that checked whether a cached // route entry was stale accidentally caused the router to treat prefetched // data as if it were complete data that didn
{ "filepath": "test/e2e/app-dir/ppr-navigations/stale-prefetch-entry/stale-prefetch-entry.test.ts", "language": "typescript", "file_size": 3776, "cut_index": 614, "middle_length": 229 }
er-only' import { unstable_noStore } from 'next/cache' // NOTE: I've intentionally not yet moved these helpers into a shared module, to // avoid early abstraction. I will if/when we start using them for other tests. // They are based on the testing patterns we use all over the React codebase, so // I'm reasonably con...
inning up a // data server. await new Promise<void>((resolve) => setTimeout(() => resolve(), ARTIFICIAL_DELAY) ) if (!isStatic) { unstable_noStore() } return key } const response = await fetch( TEST_DATA_SERVICE_
onst searchParams = new URLSearchParams({ key, }) if (!TEST_DATA_SERVICE_URL) { // If environment variable is not set, resolve automatically after a delay. // This is so you can run the test app locally without sp
{ "filepath": "test/e2e/app-dir/ppr-navigations/stale-prefetch-entry/app/test-data-service.ts", "language": "typescript", "file_size": 1446, "cut_index": 524, "middle_length": 229 }
hit a separate lambda instance that won't share the same reference if (!isNextDeploy) { it('should submit the action and revalidate the page data', async () => { const browser = await next.browser('/') await check(() => browser.hasElementByCssSelector('#create-entry'), false) // there shouldn't...
xpect((await browser.elementsByCss('#entries li')).length).toBe(1) }) await browser.elementById('create-entry').click() // we created an entry and called revalidate, so we should have 2 entries await retry(async () => { ex
ser.hasElementByCssSelector('#create-entry'), true) await browser.elementById('create-entry').click() // we created an entry and called revalidate, so we should have 1 entry await retry(async () => { e
{ "filepath": "test/e2e/app-dir/parallel-routes-revalidation/parallel-routes-revalidation.test.ts", "language": "typescript", "file_size": 16994, "cut_index": 921, "middle_length": 229 }
ync function Home() { const data = await getData() const randomNumber = await fetch( 'https://next-data-api-endpoint.vercel.app/api/random' ).then((res) => res.text()) return ( <div id="root-page"> <Link href="/revalidate-modal">Open Revalidate Modal</Link> <Link href="/refresh-modal">Open ...
id="clear-entries">Clear Entries</button> </form> <div> <h1>Current Data</h1> <ul id="entries"> {data.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> </div> </div>
div> <form action={clearData}> <button
{ "filepath": "test/e2e/app-dir/parallel-routes-revalidation/app/page.tsx", "language": "tsx", "file_size": 920, "cut_index": 606, "middle_length": 52 }
use client' import { useRouter } from 'next/navigation' import { revalidateAction } from './action' export default function Page() { const router = useRouter() const handleRevalidateSubmit = async () => { const result = await revalidateAction() if (result.success) { close() } } const close ...
</button> </div> <form action={handleRevalidateSubmit}> <button type="submit" className="bg-sky-600 text-white p-2 rounded" id="modal-submit-button" > Revalidate Submit </bu
ween"> <h2 id="modal">Modal</h2> <button type="button" id="modal-close-button" onClick={() => close()} className="bg-gray-100 border p-2 rounded" > close
{ "filepath": "test/e2e/app-dir/parallel-routes-revalidation/app/nested-revalidate/@modal/modal/page.tsx", "language": "tsx", "file_size": 1035, "cut_index": 513, "middle_length": 229 }
import Link from 'next/link' import { useRouter } from 'next/navigation' import { revalidateAction } from '../../@modal/modal/action' export default function Page() { const router = useRouter() const handleRevalidateSubmit = async () => { const result = await revalidateAction() if (result.success) { ...
se </button> <p className="mt-4">Drawer</p> <div className="mt-4 flex flex-col gap-2"> <Link href="/nested-revalidate/modal" className="bg-sky-600 text-white p-2 rounded" > Open modal
r">Drawer</h2> <p id="drawer-now">{Date.now()}</p> <button type="button" id="drawer-close-button" onClick={() => close()} className="bg-gray-100 border p-2 rounded" > clo
{ "filepath": "test/e2e/app-dir/parallel-routes-revalidation/app/nested-revalidate/@drawer/drawer/page.tsx", "language": "tsx", "file_size": 1312, "cut_index": 524, "middle_length": 229 }
utton } from '../../../../components/RefreshButton' import { RevalidateButton } from '../../../../components/RevalidateButton' import { UpdateSearchParamsButton } from '../../../../components/UpdateSearchParamsButton' const getRandom = async () => Math.random() export default async function Page(props) { const sear...
<div> <span>Modal Page</span> <span id="modal-random">{someProp}</span> </div> <RefreshButton /> <RevalidateButton /> <UpdateSearchParamsButton searchParams={searchParams} id="modal" /> </div>
display: 'flex', flexDirection: 'column' }}>
{ "filepath": "test/e2e/app-dir/parallel-routes-revalidation/app/dynamic-refresh/[dynamic]/@modal/(.)login/page.tsx", "language": "tsx", "file_size": 854, "cut_index": 529, "middle_length": 52 }
tTestSetup } from 'e2e-utils' // TODO-APP: fix test as it's failing randomly describe.skip('app-dir back button download bug', () => { describe('app-dir back button download bug', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, }) if (skipped) { ...
lick() .waitForElementByCss('#post-page') .text() expect(text).toBe('This is the post page') await browser.back() expect(await browser.waitForElementByCss('#home-page').text()).toBe( 'Home!' ) }) }) }
1') .c
{ "filepath": "test/e2e/app-dir/back-button-download-bug/back-button-download-bug.test.ts", "language": "typescript", "file_size": 796, "cut_index": 524, "middle_length": 14 }
from 'e2e-utils' import { check } from 'next-test-utils' describe('route-page-manifest-bug', () => { const { next } = nextTestSetup({ files: __dirname, }) // Recommended for tests that check HTML. Cheerio is a HTML parser that has a jQuery like API. it('should work when requesting route handler after page...
ody.textContent'), '{"url":"https://www.example.com"}' ) await browser.refresh() await check( () => browser.eval('document.body.textContent'), '{"url":"https://www.example.com"}' ) await browser.refresh() await che
ow.location.href = "/abc"') await check( () => browser.eval('document.body.textContent'), '{"url":"https://www.example.com"}' ) await browser.refresh() await check( () => browser.eval('document.b
{ "filepath": "test/e2e/app-dir/route-page-manifest-bug/route-page-manifest-bug.test.ts", "language": "typescript", "file_size": 1549, "cut_index": 537, "middle_length": 229 }
ignore import { ImageResponse as ImageResponse2 } from '@vercel/og' // Edge: Using @vercel/og external package, and should be aliased to "next/server" ImageResponse // @ts-ignore if (ImageResponse2.displayName !== ImageResponse.displayName) // @ts-ignore throw new Error('ImageResponse2 mismatch: ' + ImageResponse2...
display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 128, background: 'lavender', }} > Twitter Image </div> ), size ) } export const runtime = 'ed
width: '100%', height: '100%',
{ "filepath": "test/e2e/app-dir/metadata-dynamic-routes/app/twitter-image2.tsx", "language": "tsx", "file_size": 871, "cut_index": 559, "middle_length": 52 }
geResponse } from 'next/og' export async function generateImageMetadata({ params }) { return [ { contentType: 'image/png', size: { width: 48, height: 48 }, id: 'small', }, { contentType: 'image/png', size: { width: 72, height: 72 }, id: 'medium', }, ] } export d...
: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 88, background: '#fff', color: '#000', }} > Icon {size} {iconId} </div> ) ) }
height
{ "filepath": "test/e2e/app-dir/metadata-dynamic-routes/app/(group)/dynamic/[size]/icon.tsx", "language": "tsx", "file_size": 795, "cut_index": 524, "middle_length": 14 }
pe * as Playwright from 'playwright' import { createRouterAct } from 'router-act' describe('mismatching prefetch', () => { const { next, isNextDev } = nextTestSetup({ files: __dirname, }) if (isNextDev) { test('disabled in development', () => {}) return } function relativeHref(href: string) { ...
RouterAct(page) // Reveal the link to trigger a prefetch of page A. const toggle = await browser.elementByCss( 'input[data-link-accordion="/mismatching-prefetch/dynamic-page/a?mismatch-rewrite=./b"]' ) await act(async () =>
', async () => { let page: Playwright.Page const browser = await next.browser('/mismatching-prefetch', { beforePageLoad(p: Playwright.Page) { page = p }, }) const act = create
{ "filepath": "test/e2e/app-dir/concurrent-navigations/mismatching-prefetch.test.ts", "language": "typescript", "file_size": 2916, "cut_index": 563, "middle_length": 229 }
from 'e2e-utils' import { retry } from 'next-test-utils' describe('server patch - history entry', () => { const { next, isNextDev } = nextTestSetup({ files: __dirname, }) if (isNextDev) { test('skipped in dev mode', () => {}) return } // When a navigation suspends and then triggers a server pat...
st browser = await next.browser('/push-search-params') await retry(async () => { const homePage = await browser.elementById('home-page') expect(await homePage.text()).toContain('Home') }) // Navigate to the same page with differen
the retry inherits its navigate type so // that pushState still runs when the entangled transitions eventually // commit together. it('server patch preserves the push intent of a suspended transition', async () => { con
{ "filepath": "test/e2e/app-dir/concurrent-navigations/server-patch-history.test.ts", "language": "typescript", "file_size": 1734, "cut_index": 537, "middle_length": 229 }
Setup } from 'e2e-utils' describe('next-config-ts-type-error-cjs', () => { // TODO: Remove this once we bump minimum Node.js version to v22 if (!(process.features as any).typescript) { it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {}) return } const { next...
ait next.start() const $ = await next.render$('/') expect($('p').text()).toBe('foo') } else { const { cliOutput } = await next.build() await expect(cliOutput).toContain( `Type 'string' is not assignable to type 'number'.
(CJS)', async () => { if (isNextDev) { aw
{ "filepath": "test/e2e/app-dir/next-config-ts-native-mts/type-error/next-config-ts-type-error-cjs.test.ts", "language": "typescript", "file_size": 861, "cut_index": 529, "middle_length": 52 }
utils' describe('next-config-ts-type-error-esm', () => { // TODO: Remove this once we bump minimum Node.js version to v22 if (!(process.features as any).typescript) { it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {}) return } const { next, isNextDev, skipp...
if (isNextDev) { await next.start() const $ = await next.render$('/') expect($('p').text()).toBe('foo') } else { const { cliOutput } = await next.build() await expect(cliOutput).toContain( `Type 'string' is no
throw with type error on build (ESM)', async () => {
{ "filepath": "test/e2e/app-dir/next-config-ts-native-mts/type-error/next-config-ts-type-error-esm.test.ts", "language": "typescript", "file_size": 909, "cut_index": 547, "middle_length": 52 }
{ nextTestSetup } from 'e2e-utils' import { renderViaHTTP, startCleanStaticServer } from 'next-test-utils' import { join } from 'path' import { AddressInfo, Server } from 'net' describe('use-cache-output-export', () => { const { next, isNextStart } = nextTestSetup({ files: __dirname, skipDeployment: true, ...
'Server Actions are not supported with static export.' ) server = await startCleanStaticServer(join(next.testDir, 'out')) const { port } = server.address() as AddressInfo html = await renderViaHTTP(port, '/') } else {
put: 'export'`. }) } it('should work', async () => { let html: string let server: Server | undefined if (isNextStart) { const { cliOutput } = await next.build() expect(cliOutput).not.toInclude(
{ "filepath": "test/e2e/app-dir/use-cache-output-export/use-cache-output-export.test.ts", "language": "typescript", "file_size": 1185, "cut_index": 518, "middle_length": 229 }
TADATA_BASE_WARN_STRING = 'metadataBase property in metadata export is not set for resolving social open graph or twitter images,' describe('app dir - metadata missing metadataBase', () => { const { next, isNextDev, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, overrideFiles: { ...
ess. // If it's development mode, we get the logs after request function getCliOutput(logStartPosition: number) { return isNextDev ? next.cliOutput.slice(logStartPosition) : next.cliOutput } it('should not show warning in output in default bui
export const metadata = { metadataBase: new URL('https://example.com'), } `, }, }) if (skipped) { return } // If it's start mode, we get the whole logs since they're from build proc
{ "filepath": "test/e2e/app-dir/metadata-warnings/metadata-warnings-with-metadatabase.test.ts", "language": "typescript", "file_size": 2889, "cut_index": 563, "middle_length": 229 }
esume-data-cache', () => { const { next, isNextDev } = nextTestSetup({ files: __dirname, }) if (isNextDev) { it('is skipped', () => {}) return } it.each([ { name: 'use cache', id: 'random-number' }, { name: 'fetch cache', id: 'another-random-number' }, ])( 'should have consistent d...
://localhost') url.searchParams.set( '_rsc', await computeCacheBustingSearchParam( '1', '/__PAGE__', undefined, undefined ) ) const rsc = await next
t.render$('/') const first = $(`p#${id}`).text() // Then get the Prefetch RSC and validate that it also contains the same // random number. await retry(async () => { const url = new URL('/', 'http
{ "filepath": "test/e2e/app-dir/resume-data-cache/resume-data-cache.test.ts", "language": "typescript", "file_size": 9086, "cut_index": 716, "middle_length": 229 }
ort React, { Suspense } from 'react' import { cacheTag } from 'next/cache' import { refreshAction } from '../actions' async function getCachedRandomNumber() { 'use cache' cacheTag('server-action-test') await new Promise((resolve) => setTimeout(resolve, 100)) return Math.random() } async function getUncached...
( <> <p id="cached-random">{cachedNumber}</p> <form action={refreshAction}> <button id="refresh-button" type="submit"> Refresh </button> </form> <Suspense fallback={<p id="uncached-random">Loading...</
cComponent() { const uncachedNumber = await getUncachedRandomNumber() return <p id="uncached-random">{uncachedNumber}</p> } export default async function Page() { const cachedNumber = await getCachedRandomNumber() return
{ "filepath": "test/e2e/app-dir/resume-data-cache/app/server-action/page.tsx", "language": "tsx", "file_size": 1066, "cut_index": 515, "middle_length": 229 }
ltCacheHandler = require('next/dist/server/lib/cache-handlers/default.external').default const { AsyncLocalStorage } = require('node:async_hooks') const snapshot = AsyncLocalStorage.snapshot() /** * @type {import('next/dist/server/lib/cache-handlers/types').CacheHandler} */ const cacheHandler = { async get(cache...
lidate}, expire: ${expire}, tags: ${tags}\n ${cacheKey}` ) }) }) return defaultCacheHandler.set(cacheKey, pendingEntry) }, async refreshTags() { console.log('ModernCustomCacheHandler::refreshTags') return defaultCacheHa
sole.log('ModernCustomCacheHandler::set', cacheKey) pendingEntry.then(({ revalidate, expire, tags }) => { snapshot(() => { console.log( `ModernCustomCacheHandler::set-resolved-entry revalidate: ${reva
{ "filepath": "test/e2e/app-dir/use-cache-custom-handler/handler.js", "language": "javascript", "file_size": 1535, "cut_index": 537, "middle_length": 229 }
from 'e2e-utils' describe('turbopack-loader-content-type', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, }) if (skipped) return it('should apply loader based on contentType glob pattern', async () => { const $ = await next.render$('/') const text =...
('#js').text() expect(text).toBe('Hello from loader') }) it('should apply loader based on contentType regex', async () => { const $ = await next.render$('/') const text = $('#image').text() expect(text).toMatch(/^IMAGE:\d+ bytes$/) }
const text = $
{ "filepath": "test/e2e/app-dir/turbopack-loader-content-type/turbopack-loader-content-type.test.ts", "language": "typescript", "file_size": 811, "cut_index": 536, "middle_length": 14 }
tils' describe('useSelectedLayoutSegment(s)', () => { const { next } = nextTestSetup({ files: new FileRef(__dirname), }) let browser: Playwright beforeEach(async () => { browser = await next.browser( '/segment-name/value1/segment-name2/value2/value3/value4' ) }) it('should return correc...
async () => { expect( await browser.elementByCss('#before-static > .segments').text() ).toMatchInlineSnapshot(`"["segment-name2","value2","value3/value4"]"`) expect( await browser.elementByCss('#before-static > .segment').text()
"value2","value3/value4"]"` ) expect( await browser.elementByCss('#root > .segment').text() ).toMatchInlineSnapshot(`""segment-name""`) }) it('should return correct values in layout before static segment',
{ "filepath": "test/e2e/app-dir/use-selected-layout-segment-s/use-selected-layout-segment-s.test.ts", "language": "typescript", "file_size": 4379, "cut_index": 614, "middle_length": 229 }
rt { ImageResponse } from 'next/og' import { ImageResponse as ImageResponse2 } from '@vercel/og' // Node.js: Using @vercel/og external package, and should be aliased to "next/server" ImageResponse // @ts-ignore if (ImageResponse2.displayName !== ImageResponse.displayName) // @ts-ignore throw new Error('ImageRespon...
%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 128, background: 'lavender', }} > Twitter Image </div> ), size
( <div style={{ width: '100
{ "filepath": "test/e2e/app-dir/metadata-dynamic-routes/app/twitter-image.tsx", "language": "tsx", "file_size": 828, "cut_index": 516, "middle_length": 52 }
geResponse } from 'next/og' export async function generateImageMetadata({ params }) { return [ { contentType: 'image/png', size: { width: 48, height: 48 }, id: 'small', }, { contentType: 'image/png', size: { width: 72, height: 72 }, id: 'medium', }, ] } export d...
: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 88, background: '#fff', color: '#000', }} > Icon {size} {iconId} </div> ) ) }
height
{ "filepath": "test/e2e/app-dir/metadata-dynamic-routes/app/gsp/icon.tsx", "language": "tsx", "file_size": 795, "cut_index": 524, "middle_length": 14 }
import { NextRequest, NextResponse } from 'next/server' // Simulates what might happen if a proxy or firewall modifies the // request based on a condition that changes after the prefetch but before // the actual navigation. // // The proxy modifies the request based on special search parameters, but only // during a n...
tResponse.redirect(new URL(mismatchRedirect, req.url)) } const mismatchRewrite = req.nextUrl.searchParams.get('mismatch-rewrite') if (mismatchRewrite) { // Rewrite to the given URL. return NextResponse.rewrite(new URL(mismatchRewrite, req.ur
refetch' }], }, ], } export default function proxy(req: NextRequest) { const mismatchRedirect = req.nextUrl.searchParams.get('mismatch-redirect') if (mismatchRedirect) { // Redirect to the given URL. return Nex
{ "filepath": "test/e2e/app-dir/concurrent-navigations/proxy.ts", "language": "typescript", "file_size": 1009, "cut_index": 512, "middle_length": 229 }
import { nextTestSetup } from 'e2e-utils' describe('next-config-ts-import-js-extensions-esm', () => { // TODO: Remove this once we bump minimum Node.js version to v22 if (!(process.features as any).typescript) { it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {}) ...
ender$('/') const text = $('p').text() expect(text).toContain('jsESM') expect(text).toContain('cjs') expect(text).toContain('mjs') expect(text).toContain('cts') expect(text).toContain('mts') expect(text).toContain('ts') }) })
= await next.r
{ "filepath": "test/e2e/app-dir/next-config-ts-native-mts/import-js-extensions-esm/next-config-ts-import-js-extensions-esm.test.ts", "language": "typescript", "file_size": 782, "cut_index": 512, "middle_length": 14 }
retry } from 'next-test-utils' describe('app dir - dynamic css', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, }) if (skipped) { return } it('should preload all chunks of dynamic component during SSR', async () => { const $ = await next.render$('/...
ait next.browser('/ssr') await retry(async () => { expect( await browser.eval( `window.getComputedStyle(document.querySelector('.text')).color` ) ).toBe('rgb(255, 0, 0)') // Default border width, which is not
expect(preloadJsChunks.attr('as')).toBe('script') expect(preloadJsChunks.attr('fetchpriority')).toContain(`low`) }) it('should only apply corresponding css for page loaded that /ssr', async () => { const browser = aw
{ "filepath": "test/e2e/app-dir/dynamic-css/index.test.ts", "language": "typescript", "file_size": 2626, "cut_index": 563, "middle_length": 229 }
Suspense } from 'react' import { connection } from 'next/server' import { cacheTag } from 'next/cache' import { RevalidateButton } from './revalidate-button' async function getCachedRandom() { 'use cache' cacheTag('revalidate-action-test') return Math.random() } async function DynamicContent() { // Make the ...
{ const cachedValue = await getCachedRandom() return ( <div> <p id="cached-value">{cachedValue}</p> <Suspense fallback={<p id="uncached-value">Loading...</p>}> <DynamicContent /> </Suspense> <RevalidateButton />
dValue}</p> } export default async function Page()
{ "filepath": "test/e2e/app-dir/resume-data-cache/app/revalidate-action/page.tsx", "language": "tsx", "file_size": 842, "cut_index": 520, "middle_length": 52 }
port { connection } from 'next/server' import { RevalidateButton } from './revalidate-button' async function DynamicContent() { // Make the page dynamic/PPR by accessing connection() await connection() // Generate uncached value after dynamic access const uncachedValue = Math.random() return <p id="uncached-...
evalidate-fetch-action-test'] } } ).then((res) => res.text()) return ( <div> <p id="cached-value">{cachedValue}</p> <Suspense fallback={<p id="uncached-value">Loading...</p>}> <DynamicContent /> </Suspense> <Revalid
ndom', { cache: 'force-cache', next: { tags: ['r
{ "filepath": "test/e2e/app-dir/resume-data-cache/app/revalidate-fetch-action/page.tsx", "language": "tsx", "file_size": 885, "cut_index": 547, "middle_length": 52 }
st { next, skipped, isNextStart } = nextTestSetup({ files: __dirname, // Skip deployment so we can test the custom cache handlers log output skipDeployment: true, }) if (skipped) return let outputIndex: number beforeEach(() => { outputIndex = next.cliOutput.length }) it('should use a mod...
andler::get \["(development|[A-Za-z0-9_-]+)","([0-9a-f]{2})+",\[\]\] \[ '_N_T_\/layout', '_N_T_\/page', '_N_T_\/', '_N_T_\/index' \]/ ) expect(next.cliOutput.slice(outputIndex)).toMatch( /ModernCustomCacheHandler::set \["(development|[A-Za-z
h(isoDateRegExp) const cliOutput = next.cliOutput.slice(outputIndex) expect(cliOutput).toContain('ModernCustomCacheHandler::refreshTags') expect(next.cliOutput.slice(outputIndex)).toMatch( /ModernCustomCacheH
{ "filepath": "test/e2e/app-dir/use-cache-custom-handler/use-cache-custom-handler.test.ts", "language": "typescript", "file_size": 5350, "cut_index": 716, "middle_length": 229 }
ort { MetadataRoute } from 'next' export default function sitemap(): MetadataRoute.Sitemap { return [ { url: 'https://example.com/about', videos: [ { title: 'example', thumbnail_loc: 'https://example.com/image.jpg', description: 'this is the description', ...
restriction: { relationship: 'allow', content: 'IE GB US CA', }, platform: { relationship: 'allow', content: 'web', }, uploader: { info: 'https://www.examp
tag: 'summer', rating: 4, expiration_date: '2025-09-16', publication_date: '2024-09-16', family_friendly: 'yes', requires_subscription: 'no', live: 'no',
{ "filepath": "test/e2e/app-dir/metadata-dynamic-routes/app/sitemap-video/sitemap.ts", "language": "typescript", "file_size": 1123, "cut_index": 515, "middle_length": 229 }
port { nextTestSetup } from 'e2e-utils' describe('app-dir - metadata-non-standard-custom-routes', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should work with custom sitemap route', async () => { const res = await next.fetch('/sitemap') expect(res.status).toBe(200) expect(r...
schemas/sitemap/0.9"> <url> <loc>https://example.com</loc> <lastmod>2021-01-01</lastmod> <changefreq>weekly</changefreq> <priority>0.5</priority> </url> </urlset>" `)
.sitemaps.org/
{ "filepath": "test/e2e/app-dir/metadata-non-standard-custom-routes/metadata-non-standard-custom-routes.test.ts", "language": "typescript", "file_size": 791, "cut_index": 514, "middle_length": 14 }
./components/link-accordion' export default function Page() { return ( <div> <p> Tests what happens if a navigation resolves to a different route than the one that was prefetched. </p> <div> <ul> <li> <LinkAccordion href="/mismatching-prefetch/dynam...
ion href="/mismatching-prefetch/dynamic-page/a?mismatch-rewrite=./b"> <code>{`/mismatching-prefetch/dynamic-page/a ──[ rewrites to ]──→ /mismatching-prefetch/dynamic-page/b`}</code> </LinkAccordion> </li> </ul>
</li> <li> <LinkAccord
{ "filepath": "test/e2e/app-dir/concurrent-navigations/app/mismatching-prefetch/page.tsx", "language": "tsx", "file_size": 904, "cut_index": 547, "middle_length": 52 }
es: __dirname, skipDeployment: true, env: { NEXT_TEST_LOG_VALIDATION: '1', }, }) if (skipped) return if (!isNextDev) { it.skip('Only implemented in dev', () => {}) return } let currentCliOutputIndex = 0 beforeEach(() => { currentCliOutputIndex = next.cliOutput.length }) f...
t[] { const messageRe = /<VALIDATION_MESSAGE>(.*?)<\/VALIDATION_MESSAGE>/g const events: ValidationEvent[] = [] let match: RegExpExecArray | null while ((match = messageRe.exec(output)) !== null) { try { events.push(JSON.parse
} type ValidationEvent = | { type: 'validation_start'; requestId: string; url: string } | { type: 'validation_end'; requestId: string; url: string } function parseValidationMessages(output: string): ValidationEven
{ "filepath": "test/e2e/app-dir/instant-validation-causes/instant-validation-causes.test.ts", "language": "typescript", "file_size": 7286, "cut_index": 716, "middle_length": 229 }
expect(text).toMatchInlineSnapshot(` "User-Agent: Googlebot Allow: / User-Agent: Applebot User-Agent: Bingbot Disallow: / Crawl-delay: 2 Host: https://example.com Sitemap: https://example.com/sitemap.xml " `) }) }) describe('sitema...
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>https://example.com</loc> <lastmod>2021-01-01</lastmod> <changefreq>weekly</changefreq> <priority>0.5</priority>
get('content-type')).toBe('application/xml') expect(res.headers.get('cache-control')).toBe(CACHE_HEADERS.REVALIDATE) expect(text).toMatchInlineSnapshot(` "<?xml version="1.0" encoding="UTF-8"?>
{ "filepath": "test/e2e/app-dir/metadata-dynamic-routes/index.test.ts", "language": "typescript", "file_size": 20305, "cut_index": 1331, "middle_length": 229 }
le_cache, updateTag } from 'next/cache' import { connection } from 'next/server' import { Suspense } from 'react' export function generateStaticParams() { return [{ slug: '🎉' }] } async function Cached({ params }: { params: Promise<{ slug: string }> }) { 'use cache' const { slug } = await params cacheTag('🎂...
], { tags: ['🌶'], revalidate: false } ) export default async function Page({ params, }: { params: Promise<{ slug: string }> }) { const fetched = await fetch( 'https://next-data-api-endpoint.vercel.app/api/random', { next: { tags: ['🌮'], re
connection() return ( <p> Dynamic: <span id="dynamic-time">{new Date().toISOString()}</span> </p> ) } const getUnstableCached = unstable_cache( async () => new Date().toISOString(), ['unstable-cache-time'
{ "filepath": "test/e2e/app-dir/non-ascii-cache-tags/app/[slug]/page.tsx", "language": "tsx", "file_size": 1687, "cut_index": 537, "middle_length": 229 }
from 'e2e-utils' import { waitForRedbox, getRedboxHeader, retry } from 'next-test-utils' describe('revalidateTag-rsc', () => { const { next, isNextDev, isNextDeploy } = nextTestSetup({ files: __dirname, }) it('should revalidate fetch cache if revalidateTag invoked via server action', async () => { const...
mber3).not.toEqual(randomNumber) }) }) if (!isNextDeploy) { // skipped in deploy because it uses `next.cliOutput` it('should error if revalidateTag is called during render', async () => { const browser = await next.browser('/')
t() expect(randomNumber).toEqual(randomNumber2) await browser.elementByCss('#submit-form').click() await retry(async () => { const randomNumber3 = await browser.elementById('data').text() expect(randomNu
{ "filepath": "test/e2e/app-dir/revalidatetag-rsc/revalidatetag-rsc.test.ts", "language": "typescript", "file_size": 1620, "cut_index": 537, "middle_length": 229 }
check } from 'next-test-utils' describe('parallel-route-not-found', () => { const { next, isNextDeploy } = nextTestSetup({ files: __dirname, }) it('should behave correctly without any errors', async () => { const browser = await next.browser('/en') // Deploy doesn't have access to runtime logs ...
tain('Locale: en') await browser.elementByCss("[href='/en/show']").click() // Deploy doesn't have access to runtime logs if (!isNextDeploy) { await check(() => { if ( next.cliOutput.includes('TypeError') || n
ors' } return 'success' }, 'success') } expect(await browser.elementByCss('body').text()).not.toContain( 'Interception Modal' ) expect(await browser.elementByCss('body').text()).toCon
{ "filepath": "test/e2e/app-dir/parallel-route-not-found-params/parallel-route-not-found-params.test.ts", "language": "typescript", "file_size": 2084, "cut_index": 563, "middle_length": 229 }
` outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache` const isCacheComponentsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true' describe('use-cache-search-params', () => { c...
=> { const outputIndex = next.cliOutput.length const browser = await next.browser(`${route}?foo=1`) if (isCacheComponentsEnabled) { await expect(browser).toDisplayRedbox(` { "code": "E842",
if (isNextDev) { let route: string describe('when searchParams are used inside of "use cache"', () => { beforeAll(() => { route = '/search-params-used' }) it('should show an error', async ()
{ "filepath": "test/e2e/app-dir/use-cache-search-params/use-cache-search-params.test.ts", "language": "typescript", "file_size": 14971, "cut_index": 921, "middle_length": 229 }
, isNextDev } = nextTestSetup({ files: __dirname, }) // TODO: adjust the test to work with the new error it.skip('should handle a layout that attempts to render a missing parallel route', async () => { const browser = await next.browser('/no-bar-slot') const logs = await browser.log() expect(awai...
') } else { expect(warnings.length).toBe(0) } }) // TODO: adjust the test to work with the new error it.skip('should handle multiple missing parallel routes', async () => { const browser = await next.browser('/both-slots-missing')
ct(warnings.length).toBe(1) expect(warnings[0].message).toContain( 'No default component was found for a parallel route rendered on this page' ) expect(warnings[0].message).toContain('Missing slots: @bar
{ "filepath": "test/e2e/app-dir/parallel-route-not-found/parallel-route-not-found.test.ts", "language": "typescript", "file_size": 4424, "cut_index": 614, "middle_length": 229 }
ype Playwright } from 'e2e-utils' import { retry } from 'next-test-utils' describe('router autoscrolling on navigation with css modules', () => { const { next } = nextTestSetup({ files: __dirname, }) const getTopScroll = async (browser: Playwright) => await browser.eval('document.documentElement.scrollTo...
top: options.y, left: options.x }) }) } const scrollTo = async ( browser: Playwright, options: { x: number; y: number } ) => { await browser.eval(`window.scrollTo(${options.x}, ${options.y})`) await waitForScrollToComplete(browse
options: { x: number; y: number } ) => { await retry(async function expectScrolledTo() { const top = await getTopScroll(browser) const left = await getLeftScroll(browser) expect({ top, left }).toEqual({
{ "filepath": "test/e2e/app-dir/autoscroll-with-css-modules/index.test.ts", "language": "typescript", "file_size": 1944, "cut_index": 537, "middle_length": 229 }
tTestSetup } from 'e2e-utils' // TODO: Test didn't (or maybe) never ran in CI but it should. describe.skip('app dir - next-image (with https)', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, startCommand: `pnpm next dev --experimental-https`, }) if (skipped...
esponse.ok()) { console.log(`Request failed: ${url}`) failCount++ } }) }, }) const image = browser.elementByCss('#app-page') const src = await image.getAttribute('src') if (process.env.IS_TUR
onse', (response) => { const url = response.url() if (!url.includes('/_next/image')) return const status = response.status() console.log(`URL: ${url} Status: ${status}`) if (!r
{ "filepath": "test/e2e/app-dir/next-image/next-image-https.test.ts", "language": "typescript", "file_size": 1352, "cut_index": 524, "middle_length": 229 }
' import httpProxy from 'http-proxy' import fs from 'fs' import { nextTestSetup } from 'e2e-utils' let proxyPort let proxyServer: https.Server describe('next-image-proxy', () => { const { next, skipped } = nextTestSetup({ files: __dirname, // This test is skipped when deployed because it relies on a proxy s...
rget: `http://localhost:${next.appPort}`, ssl, secure: false, }) proxyServer = https.createServer(ssl, async (req, res) => { proxy.web(req, res) }) proxy.on('error', (err) => { throw new Error('Failed to proxy: ' +
certificates/localhost-key.pem'), 'utf8' ), cert: fs.readFileSync( join(__dirname, 'certificates/localhost.pem'), 'utf8' ), } const proxy = httpProxy.createProxyServer({ ta
{ "filepath": "test/e2e/app-dir/next-image/next-image-proxy.test.ts", "language": "typescript", "file_size": 3183, "cut_index": 614, "middle_length": 229 }
ges') await fs.remove(imagesDir).catch(() => {}) const $ = await next.render$('/') const imageUrl = $('#app-layout').attr('src') const headRes = await next.fetch(imageUrl, { method: 'HEAD' }) expect(headRes.status).toBe(200) expect(headRes.headers.get('content-type')).t...
(getRes.headers.get('content-type')).toMatch(/^image\//) expect(getRes.headers.get('X-Nextjs-Cache')).toBe('HIT') const getContentLength = getRes.headers.get('content-length') expect(Number(getContentLength || '0')).toBeGreaterThan
| '0')).toBeGreaterThan(0) const headBody = await headRes.arrayBuffer() expect(headBody.byteLength).toBe(0) const getRes = await next.fetch(imageUrl) expect(getRes.status).toBe(200) expect
{ "filepath": "test/e2e/app-dir/next-image/next-image.test.ts", "language": "typescript", "file_size": 14725, "cut_index": 921, "middle_length": 229 }
from 'e2e-utils' ;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)( 'ecmascript-features turbopack', () => { const { next } = nextTestSetup({ files: __dirname, }) // Recommended for tests that check HTML. Cheerio is a HTML parser that has a jQuery like API. it('should work using che...
next.render$('/export-as-string') expect(JSON.parse($1('#values-to-check').text())).toEqual({ exportAsString: 1, }) }) // Recommended for tests that need a full browser it('should work using browser', async () => { co
privateStaticFieldWithInitializer: 12, privateStaticMethod: 12, privateMethodInThis: true, exportAs: 1, // regex: true, importWith: 'Hello World', }) const $1 = await
{ "filepath": "test/e2e/app-dir/ecmascript-features/turbopack/ecmascript-features-turbopack.test.ts", "language": "typescript", "file_size": 1657, "cut_index": 537, "middle_length": 229 }
server and client compilation of ECMAScript features. import { abc } from './export-as' import json from './file.json' with { type: 'json' } class ClassWithPrivate { #privateField #privateFieldWithInitializer = 11 #privateMethod() { this.#privateField = 10 } static #privateStaticFieldWithInitializer =...
) { return ClassWithPrivate.#privateStaticMethod() } isPrivateMethodAvailable() { return #privateField in this } } // Not supported in Node.js yet. // let regex = /abc/v export default function Page() { const instance = new ClassWithPriva
eld } getPrivateFieldWithInitializer() { return this.#privateFieldWithInitializer } getPrivateStaticFieldWithInitializer() { return ClassWithPrivate.#privateStaticFieldWithInitializer } getPrivateStaticMethod(
{ "filepath": "test/e2e/app-dir/ecmascript-features/turbopack/app/page.tsx", "language": "tsx", "file_size": 1791, "cut_index": 537, "middle_length": 229 }
from 'e2e-utils' ;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)( 'ecmascript-features webpack', () => { const { next } = nextTestSetup({ files: __dirname, }) // Recommended for tests that check HTML. Cheerio is a HTML parser that has a jQuery like API. it('should work using cheer...
x as "abc" }` (export as string) is not supported in webpack yet. // const $1 = await next.render$('/export-as-string') // expect(JSON.parse($1('#values-to-check').text())).toEqual({ // exportAsString: 1, // }) }) // Reco
privateStaticFieldWithInitializer: 12, privateStaticMethod: 12, privateMethodInThis: true, exportAs: 1, // regex: true, importWith: 'Hello World', }) // TODO: `export {
{ "filepath": "test/e2e/app-dir/ecmascript-features/webpack/ecmascript-features-webpack.test.ts", "language": "typescript", "file_size": 1867, "cut_index": 537, "middle_length": 229 }
server and client compilation of ECMAScript features. import { abc } from './export-as' import json from './file.json' with { type: 'json' } class ClassWithPrivate { #privateField #privateFieldWithInitializer = 11 #privateMethod() { this.#privateField = 10 } static #privateStaticFieldWithInitializer =...
) { return ClassWithPrivate.#privateStaticMethod() } isPrivateMethodAvailable() { return #privateField in this } } // Not supported in Node.js yet. // let regex = /abc/v export default function Page() { const instance = new ClassWithPriva
eld } getPrivateFieldWithInitializer() { return this.#privateFieldWithInitializer } getPrivateStaticFieldWithInitializer() { return ClassWithPrivate.#privateStaticFieldWithInitializer } getPrivateStaticMethod(
{ "filepath": "test/e2e/app-dir/ecmascript-features/webpack/app/page.tsx", "language": "tsx", "file_size": 1791, "cut_index": 537, "middle_length": 229 }
s' describe('bfcache-regression', () => { const { next, isTurbopack } = nextTestSetup({ files: __dirname, }) it('should preserve interactivity after navigating back from another page via MPA navigation', async () => { // In webpack dev, compiling a new route on demand while another page is // open t...
null, ]) // Verify initial state and that the counter is interactive. await browser.elementById('increment').click() await retry(async () => { expect(await browser.elementById('count').text()).toBe('Count: 1') }) // Navigat
o it's already compiled by the // time we click the link. const [browser] = await Promise.all([ next.browser('/', { pushErrorAsConsoleLog: true }), !isTurbopack ? next.render('/target-page').catch(() => {}) :
{ "filepath": "test/e2e/app-dir/bfcache-regression/bfcache-regression.test.ts", "language": "typescript", "file_size": 3305, "cut_index": 614, "middle_length": 229 }
from 'e2e-utils' import { check, retry } from 'next-test-utils' import { join } from 'path' describe('custom-app-server-action-redirect', () => { const { next, skipped } = nextTestSetup({ files: join(__dirname, 'custom-server'), skipDeployment: true, startCommand: 'node server.js', serverReadyPattern...
browser.elementByCss('#increase-count').click().click() await retry(async () => { expect(await getCount()).toBe('Count: 2') }) await browser.elementById('submit-server-action-redirect').click() expect(await browser.waitForElementBy
handler uses `redirect`', async () => { const browser = await next.browser('/base') const getCount = async () => browser.elementByCss('#current-count').text() // Increase count to track if the page reloaded await
{ "filepath": "test/e2e/app-dir/app-basepath-custom-server/index.test.ts", "language": "typescript", "file_size": 1948, "cut_index": 537, "middle_length": 229 }
http = require('http') const { parse } = require('url') const next = require('next') const getPort = require('get-port') async function main() { const dev = process.env.NEXT_TEST_MODE === 'dev' process.env.NODE_ENV = dev ? 'development' : 'production' const port = await getPort() const app = next({ dev, port...
} else { res.end() } } catch (err) { res.statusCode = 500 res.end('Internal Server Error') } }) server.once('error', (err) => { console.error(err) process.exit(1) }) server.listen(port, () => { co
{ pathname } = parsedUrl res.setHeader( 'set-cookie', 'custom-server-test-cookie=custom-server-test-cookie-val' ) if (pathname.startsWith('/base')) { await handle(req, res, parsedUrl)
{ "filepath": "test/e2e/app-dir/app-basepath-custom-server/custom-server/server.js", "language": "javascript", "file_size": 1202, "cut_index": 518, "middle_length": 229 }
fetchViaHTTP } from 'next-test-utils' import { NEXT_RSC_UNION_QUERY } from 'next/dist/client/components/app-router-headers' import fs from 'fs' import path from 'path' const configPath = path.join(__dirname, 'next.config.js') describe('rsc-redirect', () => { const { next } = nextTestSetup({ files: __dirname, ...
redirect: 'manual', headers: { rsc: '1', }, } ) expect(response.status).toBe(200) }) }) // TODO: these tests aren't currently run at all during testing if (process.env.NODE_ENV === 'production') { describe.each(
response.status).toBe(307) }) it('should get 200 status code for rsc request', async () => { const response = await fetchViaHTTP( next.url, `/origin?${NEXT_RSC_UNION_QUERY}`, undefined, {
{ "filepath": "test/e2e/app-dir/rsc-redirect/rsc-redirect.test.ts", "language": "typescript", "file_size": 2474, "cut_index": 563, "middle_length": 229 }
port { nextTestSetup } from 'e2e-utils' describe('parallel-routes-catchall-children-slot', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should match the @children slot for a page before attempting to match the catchall', async () => { let browser = await next.browser('/') await ...
wser = await next.browser('/nested') await expect(browser.elementById('children').text()).resolves.toBe( 'Hello from nested @children page' ) await expect(browser.elementById('slot').text()).resolves.toBe( 'Default @slot' ) }
) bro
{ "filepath": "test/e2e/app-dir/parallel-routes-catchall-children-slot/parallel-routes-catchall-children-slot.test.ts", "language": "typescript", "file_size": 789, "cut_index": 514, "middle_length": 14 }
import fs from 'fs' import path from 'path' import { ImageResponse } from 'next/og' export const contentType = 'image/png' export default async function og() { const font = await fs.promises.readFile( path.join(process.cwd(), 'assets/typewr__.ttf') ) return new ImageResponse( ( <div style=...
color: '#000', }} > Typewriter og </div> ), { fonts: [ { name: 'Typewriter', data: font, style: 'normal', }, ], } ) } export const runtime = 'nodejs
d: '#fff',
{ "filepath": "test/e2e/app-dir/metadata-font/app/font/opengraph-image2.tsx", "language": "tsx", "file_size": 784, "cut_index": 512, "middle_length": 14 }
ver response. Skipped in dev because * webpack compiles routes on-demand and only knows about visited routes. * (Turbopack doesn't have this limitation since it builds the full * directory tree from the file system.) * TODO: Replace with end-to-end tests once client behavior is implemented. * * 2. Nav...
e * to a static sibling URL. */ import { nextTestSetup } from 'e2e-utils' // TODO: These imports are only needed for the temporary RSC payload tests. // Remove once client behavior is implemented. import { NEXT_RSC_UNION_QUERY, RSC_HEADER, } from 'n
* * The navigation flow ensures the client has seen the dynamic route before * attempting to navigate to the sibling. This simulates real-world usage * where a user might visit or prefetch a dynamic route, then later navigat
{ "filepath": "test/e2e/app-dir/static-siblings/static-siblings.test.ts", "language": "typescript", "file_size": 9235, "cut_index": 921, "middle_length": 229 }
ult function Page() { return ( <main id="home-page"> <h1>Static Siblings Test</h1> <section> <h2>About</h2> <p> This test verifies that when a dynamic route has static siblings at the same URL level, the client can correctly navigate to the static sibling...
</li> <li>Verify the static sibling page renders, not the dynamic route</li> </ol> <p> The key behavior being tested: when navigating to a URL that matches both a dynamic route (e.g., /products/[id]) and a stat
veal it</li> <li>Click the revealed link to navigate to the dynamic route</li> <li>Use the browser back button to return to this page</li> <li>Click the static sibling link (which has prefetch=false)
{ "filepath": "test/e2e/app-dir/static-siblings/app/page.tsx", "language": "tsx", "file_size": 3586, "cut_index": 614, "middle_length": 229 }
import { join } from 'path' import { FileRef, nextTestSetup } from 'e2e-utils' describe('multiple-lockfiles - has-output-file-tracing-root', () => { const { next, skipped } = nextTestSetup({ files: { app: new FileRef(join(__dirname, 'app')), // This will silence the multiple lockfiles warning. ...
, skipDeployment: true, }) if (skipped) { return } it('should not have multiple lockfiles warnings', async () => { expect(next.cliOutput).not.toMatch( /We detected multiple lockfiles and selected the directory of .+ as the root
ckage-lock.json': JSON.stringify({ name: 'parent-workspace', version: '1.0.0', lockfileVersion: 3, }), }, // So that ../package-lock.json doesn't leave the isolated testDir subDir: 'test'
{ "filepath": "test/e2e/app-dir/multiple-lockfiles/multiple-lockfiles-with-output-file-tracing-root.test.ts", "language": "typescript", "file_size": 1024, "cut_index": 512, "middle_length": 229 }
import { join } from 'path' import { FileRef, nextTestSetup } from 'e2e-utils' describe('multiple-lockfiles - has-turbo-root', () => { const { next, skipped } = nextTestSetup({ files: { app: new FileRef(join(__dirname, 'app')), // This will silence the multiple lockfiles warning. 'next.config.j...
ment: true, }) if (skipped) { return } it('should not have multiple lockfiles warnings', async () => { expect(next.cliOutput).not.toMatch( /We detected multiple lockfiles and selected the directory of .+ as the root directory\./
: JSON.stringify({ name: 'parent-workspace', version: '1.0.0', lockfileVersion: 3, }), }, // So that ../package-lock.json doesn't leave the isolated testDir subDir: 'test', skipDeploy
{ "filepath": "test/e2e/app-dir/multiple-lockfiles/multiple-lockfiles-with-turbo-root.test.ts", "language": "typescript", "file_size": 1008, "cut_index": 512, "middle_length": 229 }
n } from 'path' import { FileRef, nextTestSetup } from 'e2e-utils' import { retry } from 'next-test-utils' describe('multiple-lockfiles', () => { const { next, skipped, isTurbopack } = nextTestSetup({ files: { app: new FileRef(join(__dirname, 'app')), // Write a package-lock.json file to the parent d...
await retry(async () => { expect(next.cliOutput).toMatch( /We detected multiple lockfiles and selected the directory of .+ as the root directory\./ ) if (isTurbopack) { expect(next.cliOutput).toMatch( /To sil
), }, // So that ../package-lock.json doesn't leave the isolated testDir subDir: 'test', skipDeployment: true, }) if (skipped) { return } it('should have multiple lockfiles warnings', async () => {
{ "filepath": "test/e2e/app-dir/multiple-lockfiles/multiple-lockfiles.test.ts", "language": "typescript", "file_size": 1390, "cut_index": 524, "middle_length": 229 }
ely because request-specific arguments such as params, searchParams, cookies() or dynamic data were used inside "use cache".' describe('use-cache-hanging', () => { const { next, isNextDev, skipped, isTurbopack } = nextTestSetup({ files: __dirname, skipDeployment: true, skipStart: process.env.NEXT_TEST_MO...
description": "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".", "environmentLabel": "Server", "label": "Conso
', async () => { const outputIndex = next.cliOutput.length const browser = await next.browser('/static') await expect(browser).toDisplayCollapsedRedbox(` { "code": "E236", "
{ "filepath": "test/e2e/app-dir/use-cache-hanging/use-cache-hanging.test.ts", "language": "typescript", "file_size": 6698, "cut_index": 716, "middle_length": 229 }
a realistic migration hazard. The documented "preload" // pattern (see the "Preloading data" section of the // caching-without-cache-components guide in the Next.js docs) wraps the loader // in `React.cache`, so its store is tied to the ALS snapshot — `'use cache'` // bodies run in a clean snapshot and miss, re-executi...
ed fetch in the outer scope returns a // hanging promise that intentionally never resolves. // - In dev, the outer fetch is parked on the Dynamic stage, which can't // advance until the cache fills. The cache awaits the outer fetch via the //
e map lives above ALS, so a // `'use cache'` body joining it reuses the outer-scope promise (request scope // or prerender scope) — a promise that was never meant to resolve for the // cache: // - During prerendering, an uncach
{ "filepath": "test/e2e/app-dir/use-cache-hanging/app/shared.ts", "language": "typescript", "file_size": 1661, "cut_index": 537, "middle_length": 229 }
ort { cookies } from 'next/headers' import { Suspense } from 'react' import { getData, preload } from '../shared' const sharedUrl = 'https://next-data-api-endpoint.vercel.app/api/random?page=runtime' async function getCachedData(): Promise<string> { 'use cache' // Joins the outer fetch via the module-scoped de...
n Runtime() { await cookies() // Simulate another part of the tree (e.g. a sibling component or a shared // data loader) kicking off the same fetch in outer scope before `Cached` // runs. preload(sharedUrl) return <Cached /> } export default
hen the // invocation is wrapped in a try/catch. try { const data = await getCachedData() return <p id="result">{data}</p> } catch (error) { return <p id="result">Error: {error.message}</p> } } async functio
{ "filepath": "test/e2e/app-dir/use-cache-hanging/app/runtime/page.tsx", "language": "tsx", "file_size": 1107, "cut_index": 515, "middle_length": 229 }
./shared' const sharedUrl = 'https://next-data-api-endpoint.vercel.app/api/random?page=static' async function getCachedData(): Promise<string> { 'use cache' // Joins the outer fetch via the module-scoped dedupe map (see note in // ../shared.ts). return getData(sharedUrl).then((res) => res.text()) } async ...
return <p id="result">Error: {error.message}</p> } } export default function Page() { // Simulate another part of the tree (e.g. a sibling component or a shared // data loader) kicking off the same fetch in outer scope before `Cached` // runs.
turn <p id="result">{data}</p> } catch (error) {
{ "filepath": "test/e2e/app-dir/use-cache-hanging/app/static/page.tsx", "language": "tsx", "file_size": 899, "cut_index": 547, "middle_length": 52 }
for https://github.com/vercel/next.js/issues/93142 // // Any non-ASCII character (Hebrew, Arabic, CJK, emoji, …) in a cache tag — // whether it's a path-derived implicit tag or a user-supplied tag from // `cacheTag()`, `unstable_cache({tags})`, or `fetch({next:{tags}})` — gets // written into the internal `x-next-cache...
SCII path / tag must actually be invalidated by // `revalidatePath`, `revalidateTag`, or `updateTag` against each cache backend. describe('non-ASCII cache tags', () => { const { next, isNextDeploy } = nextTestSetup({ files: __dirname, }) const S
-error masks the 500 from clients, but revalidation // itself keeps failing and the cache stops refreshing for affected routes. The // revalidate / updateTag cases here cover that round-trip: a cached entry keyed // under a non-A
{ "filepath": "test/e2e/app-dir/non-ascii-cache-tags/non-ascii-cache-tags.test.ts", "language": "typescript", "file_size": 4187, "cut_index": 614, "middle_length": 229 }
TADATA_BASE_WARN_STRING = 'metadataBase property in metadata export is not set for resolving social open graph or twitter images,' describe('app dir - metadata missing metadataBase', () => { const { next, isNextDev, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, }) if (skipped) { ...
gStartPosition = next.cliOutput.length await next.fetch('/absolute-url-og') const output = getCliOutput(logStartPosition) expect(output).not.toInclude(METADATA_BASE_WARN_STRING) }) } it('should show warning in vercel deployment o
sition: number) { return isNextDev ? next.cliOutput.slice(logStartPosition) : next.cliOutput } if (isNextDev) { it('should not warn metadataBase is missing if there is only absolute url', async () => { const lo
{ "filepath": "test/e2e/app-dir/metadata-warnings/metadata-warnings-missing-metadatabase.test.ts", "language": "typescript", "file_size": 2659, "cut_index": 563, "middle_length": 229 }
import { Suspense } from 'react' async function SearchAndRouteParams({ searchParams, params, }: { searchParams: Promise<{ id?: string }> params: Promise<{ id: string }> }) { const { id: searchId } = await searchParams const { id: routeId } = await params return ( <div> <h1>Search and Route Par...
ams, params, }: { searchParams: Promise<{ id?: string }> params: Promise<{ id: string }> }) { return ( <Suspense fallback={<div>Loading...</div>}> <SearchAndRouteParams searchParams={searchParams} params={params} /> </Suspense> ) }
({ searchPar
{ "filepath": "test/e2e/app-dir/conflicting-search-and-route-params/app/render/[id]/page.tsx", "language": "tsx", "file_size": 782, "cut_index": 512, "middle_length": 14 }
onst { next, isNextDev } = nextTestSetup({ files: __dirname, }) if (isNextDev) { it('is skipped', () => {}) return } it('navigates to prerendered route without waiting for dynamic render', async () => { const browser = await next.browser('/') // Track elapsed time across the client naviga...
.toBe('Hi alpha') const elapsed = await browser.eval(`performance.now() - window.__navStart`) // The page has an intentional 2s delay in the Server Component. // If this were a dynamic render, navigation would take ~2s+. expect(elapsed).t
ementById('slug') expect(await slug.innerText())
{ "filepath": "test/e2e/app-dir/static-rsc-cache-components/static-rsc-cache-components.test.ts", "language": "typescript", "file_size": 940, "cut_index": 606, "middle_length": 52 }
{ nextTestSetup } from 'e2e-utils' describe('parallel-routes-and-interception', () => { const { next, skipped } = nextTestSetup({ files: __dirname, // TODO: remove after deployment handling is updated skipDeployment: true, }) if (skipped) { return } // TODO: revisit the error for missing p...
sSelector('#children-slot')).toBe(false) const $ = await next.render$('/') expect($('title').length).toBe(1) expect($('title').text()).toBe('layout title') }) it('should render the title once for the non-existed route', async () => { c
through navigating expect(await browser.elementByCss('body').text()).toMatch( /This page could not be found/ ) // we also check that the #children-slot id is not present expect(await browser.hasElementByCs
{ "filepath": "test/e2e/app-dir/parallel-routes-not-found/parallel-routes-not-found.test.ts", "language": "typescript", "file_size": 1248, "cut_index": 518, "middle_length": 229 }
eSelectedLayoutSegment } from 'next/navigation' import Link from 'next/link' export default function RootLayout({ children, auth, nav, }: Readonly<{ children: React.ReactNode auth: React.ReactNode nav: React.ReactNode }>) { const authSegment = useSelectedLayoutSegment('auth') const navSegment = useSele...
/Link> <Link href="/reset/withEmail"> Reset with Email (/app/@auth/reset/withEmail) </Link> <Link href="/reset/withMobile"> Reset with Mobile (/app/@auth/reset/withMobile) </Link>
> <Link href="/foo">Foo (regular page)</Link> <Link href="/login"> Login (/app/@auth/login) and (/app/@nav/login) </Link> <Link href="/reset">Reset (/app/@auth/reset)<
{ "filepath": "test/e2e/app-dir/parallel-routes-use-selected-layout-segment/app/layout.tsx", "language": "tsx", "file_size": 1508, "cut_index": 537, "middle_length": 229 }
t { Suspense, type ReactNode } from 'react' // Validation level is 'manual-warning' (set in next.config.ts). // No implicit validation should fire on bare pages, in dev or build — // only segments that explicitly opt in via `unstable_instant` are validated. // // Children are wrapped in Suspense so that pages with unc...
navigation" // as an instant-specific violation when it runs. export default function RootLayout({ children }: { children: ReactNode }) { return ( <html> <body> <Suspense fallback={<p>loading…</p>}>{children}</Suspense> </body>
gh for instant
{ "filepath": "test/e2e/app-dir/instant-validation-level-manual-warning/app/with-root-suspense/layout.tsx", "language": "tsx", "file_size": 809, "cut_index": 517, "middle_length": 14 }
om 'react' export default function Home() { const [workerDeploymentId, setWorkerDeploymentId] = useState('default') const mainDeploymentId = process.env.NEXT_DEPLOYMENT_ID return ( <div> <button onClick={() => { const worker = new Worker( new URL('../deployment-id-worker'...
ment ID from worker </button> <p> Main deployment ID:{' '} <span id="main-deployment-id">{mainDeploymentId}</span> </p> <p> Worker deployment ID:{' '} <span id="worker-deployment-id">{workerDeployment
) }) }} > Get deploy
{ "filepath": "test/e2e/app-dir/worker/app/deployment-id/page.js", "language": "javascript", "file_size": 894, "cut_index": 547, "middle_length": 52 }
lient' import { useState } from 'react' export default function Home() { const [pngInfo, setPngInfo] = useState(null) return ( <div> <button onClick={() => { const worker = new Worker(new URL('../png-worker', import.meta.url), { type: 'module', }) worker...
default'}</span> </p> <p> Fetched From:{' '} <span id="fetched-from">{pngInfo?.fetchedFrom ?? 'default'}</span> </p> <p> Content-Type:{' '} <span id="content-type">{pngInfo?.contentType ?? 'default'}<
d="png-url">{pngInfo?.url ?? 'default'}</span> </p> <p> PNG Width: <span id="png-width">{pngInfo?.width ?? 'default'}</span> </p> <p> PNG Height: <span id="png-height">{pngInfo?.height ?? '
{ "filepath": "test/e2e/app-dir/worker/app/png/page.js", "language": "javascript", "file_size": 1156, "cut_index": 518, "middle_length": 229 }
', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should prefetch the page without errors', async () => { let hasNetworkError = false const browser = await next.browser('/', { beforePageLoad: (page) => { page.on('response', (response) => { // 304 Not Modifie...
e window to ensure we don't perform an MPA navigation when navigating to the prefetched link await browser.eval('window.beforeNav = 1') await browser.elementById('link-to-random').click() await browser.waitForElementByCss('#random-page')
}) }, }) // set a flag on th
{ "filepath": "test/e2e/app-dir/fallback-prefetch/fallback-prefetch.test.ts", "language": "typescript", "file_size": 993, "cut_index": 582, "middle_length": 52 }
computeCacheBustingSearchParam, computeLegacyCacheBustingSearchParam, } from 'next/dist/shared/lib/router/utils/cache-busting-search-param' describe('app dir - validation', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, }) if (skipped) { return } i...
L('/', 'http://localhost') // Add cache busting search param for both requests const cacheBustingParam1 = await computeCacheBustingSearchParam( undefined, undefined, stateTree1, undefined ) const cacheBustingParam2
rsc: '1', 'next-router-state-tree': stateTree1, } const headers2 = { rsc: '1', 'next-router-state-tree': stateTree2, } const url1 = new URL('/', 'http://localhost') const url2 = new UR
{ "filepath": "test/e2e/app-dir/app-validation/validation.test.ts", "language": "typescript", "file_size": 2736, "cut_index": 563, "middle_length": 229 }
enerate-static-params', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should render the intercepted/non-intercepted modal', async () => { const browser = await next.browser('/en') expect(await browser.elementByCss('h1').text()).toBe('Home Page') await browser.elementByCss("[hr...
terception Page' ) await browser.back() await browser.waitForElementByCss('#home-page') await browser.elementByCss("[href='/en/no-interception/123']").click() await browser.waitForElementByCss('#non-intercepted-page') expect(aw
elementByCss('h2').text()).toBe( 'Modal for In
{ "filepath": "test/e2e/app-dir/parallel-routes-generate-static-params/parallel-routes-generate-static-params.test.ts", "language": "typescript", "file_size": 966, "cut_index": 582, "middle_length": 52 }
} from 'node:timers/promises' async function stable(action: () => Promise<void>, stableForMS: number = 1000) { // Wait for it to reach the initial state. await retry(async () => { await action() }) // Wait for the stableForMS to ensure that it doesn't change. for (let i = 0; i < 10; i++) { await act...
eters on the server', async () => { const $ = await next.render$('/vercel/sub/folder') expect({ client: $( '[data-client-file="/[teamID]/@slot/[...catchAll]/page.tsx"][data-client-params]' ).data('client-params'), server:
this in development because there's no prefetching // during development. if (isNextDev) { it.skip('skipping in dev', async () => { await Promise.resolve() }) return } it('should render the right param
{ "filepath": "test/e2e/app-dir/parallel-route-navigations/parallel-route-navigations.test.ts", "language": "typescript", "file_size": 3757, "cut_index": 614, "middle_length": 229 }
xt, isNextDev, isTurbopack, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, skipStart: true, }) if (skipped) return if (!isNextDev) { it('should skip in non-dev mode', () => {}) return } beforeAll(async () => { await next.start() }) describe('CLI output', () ...
toContain('string-error.data') expect(output).toContain( 'A string error thrown by string-error-loader' ) expect(output).toMatch(/\(from .+loaders\/string-error-loader/) }, // webpack compilation ou
h and error message when a loader throws a plain string', async () => { await next.fetch('/string-error') await retry( async () => { const output = stripAnsi(next.cliOutput) expect(output).
{ "filepath": "test/e2e/app-dir/webpack-loader-errors/webpack-loader-errors.test.ts", "language": "typescript", "file_size": 6526, "cut_index": 716, "middle_length": 229 }