prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
t').NextConfig}
*/
const nextConfig = {
turbopack: {
rules: {
'error.data': {
loaders: [require.resolve('./loaders/error-loader.js')],
as: '*.js',
},
'string-error.data': {
loaders: [require.resolve('./loaders/string-error-loader.js')],
as: '*.js',
},
... | loaders: [require.resolve('./loaders/fs-error-loader.js')],
as: '*.js',
},
'crash.data': {
loaders: [require.resolve('./loaders/crash-loader.js')],
as: '*.js',
},
},
},
webpack(config) {
config.mod | ./loaders/timeout-error-loader.js')],
as: '*.js',
},
'no-stack-error.data': {
loaders: [require.resolve('./loaders/no-stack-error-loader.js')],
as: '*.js',
},
'fs-error.data': {
| {
"filepath": "test/e2e/app-dir/webpack-loader-errors/next.config.js",
"language": "javascript",
"file_size": 1928,
"cut_index": 537,
"middle_length": 229
} |
is a rather contrived test. The trick is to construct a scenario where
* Math.random is called during the create-component-tree phase but not during the render.
* To do this we patch Symbol.for. When the `react.client.reference` symbol is checked
* we know that this is happening in the create-component-tree function... | will not express the regression for other reasons.
*/
function patchSymbolFor() {
const isPatched = globalThis[Symbol.for('__SYMBOL_FOR_PATCHED__')]
if (!isPatched) {
console.log('patching')
globalThis[Symbol.for('__SYMBOL_FOR_PATCHED__')] = | hat uses
* our OTel implementation to ensure that the built-in trace in create-component-tree does not
* early abort the prerender. The problem is that we are about to make these functions avoid the
* workUnitStore scope so it | {
"filepath": "test/e2e/app-dir/cache-components-create-component-tree/app/layout.tsx",
"language": "tsx",
"file_size": 1397,
"cut_index": 524,
"middle_length": 229
} |
ce,
retry,
} from 'next-test-utils'
describe('app-dir - error-on-next-codemod-comment', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) return
if (isNextDev) {
beforeAll(async () => {
await next.start... |
After review, either remove the comment if you made the necessary changes or replace "@next-codemod-error" with "@next-codemod-ignore" to bypass the build error if no action at this line can be taken.
1 | export default functio | env.IS_TURBOPACK_TEST) {
expect(await getRedboxSource(browser)).toMatchInlineSnapshot(`
"./app/page.tsx (2:2)
You have an unresolved @next/codemod comment "remove jsx of next line" that needs review. | {
"filepath": "test/e2e/app-dir/error-on-next-codemod-comment/error-on-next-codemod-comment.test.ts",
"language": "typescript",
"file_size": 5031,
"cut_index": 614,
"middle_length": 229
} |
=> {
const { next } = nextTestSetup({
files: __dirname,
})
it('should handle conflicting search and route params on page', async () => {
const browser = await next.browser('/render/123?id=456')
const routeParamText = await browser.elementByCss('#route-param').text()
expect(routeParamText).toCont... | , async () => {
// Test with route param "789" and search param "abc"
const response = await next.fetch('/api/789?id=abc')
const data = await response.json()
expect(data).toEqual({
routeParam: '789',
searchParam: 'abc',
})
| le conflicting search and route params on API route' | {
"filepath": "test/e2e/app-dir/conflicting-search-and-route-params/conflicting-search-and-route-params.test.ts",
"language": "typescript",
"file_size": 922,
"cut_index": 606,
"middle_length": 52
} |
-build-mode', 'compile'] })
})
afterEach(async () => {
await next.stop()
})
} else {
beforeAll(async () => {
await next.start()
})
}
const prerender = async (pathname: string) => {
return await next.build({
args: [
'--experimental-build-mode',
'generate',... | ant`, so
// violating bare pages produce no errors at all.
//
// - `without-root-suspense/`: layout renders {children} directly. A
// bare violating page has no Suspense between the layout and the
// runtime data, so static-shell validation | } in Suspense, so
// static-shell validation is satisfied for pages that access runtime
// data at the top. Under 'manual-warning', instant validation only
// runs on segments that explicitly opt in via `unstable_inst | {
"filepath": "test/e2e/app-dir/instant-validation-level-manual-warning/instant-validation-level-manual-warning.test.ts",
"language": "typescript",
"file_size": 21715,
"cut_index": 1331,
"middle_length": 229
} |
up({
files: __dirname,
// The latest changes to support this behavior on deployed infra are available in the adapter,
// and are not being backported to the CLI
skipDeployment: !isAdapterTest,
})
if (isNextDev) {
it.skip('skipping dev test', () => {})
return
}
if (process.env.__NEXT_CA... | /second/third')
// Get the sentinel value that was generated at build time or runtime.
expect($('[data-layout="/"]').data('sentinel')).toBe('buildtime')
expect($('[data-layout="/[first]"]').data('sentinel')).toBe('buildtime')
expec | First try to load a page that'll use the base fallback route with the
// `/[first]/[second]/[third]` fallback.
let $ = await next.render$('/first/second/third')
expect($('[data-slug]').data('slug')).toBe('first | {
"filepath": "test/e2e/app-dir/sub-shell-generation-middleware/sub-shell-generation-middleware.test.ts",
"language": "typescript",
"file_size": 9536,
"cut_index": 921,
"middle_length": 229
} |
retry } from 'next-test-utils'
describe('parallel-routes-and-interception-from-root', () => {
const { next, isNextDeploy } = nextTestSetup({
files: __dirname,
})
it('should interpolate [locale] in "/[locale]/example/(...)[locale]/intercepted"', async () => {
const browser = await next.browser('/en/examp... | xt.cliOutput.length
await browser.elementByCss('a').click()
await retry(async () => {
expect(await browser.elementByCss('h2').text()).toBe(
'Page intercepted from root'
)
})
// Ensure that the locale is still correctl | .cliOutput).toInclude('RootLayout rendered, locale: en')
}
// Referenced by commented out assertion below, see TODO message
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const cliOutputLength = ne | {
"filepath": "test/e2e/app-dir/parallel-routes-and-interception-from-root/parallel-routes-and-interception-from-root.test.ts",
"language": "typescript",
"file_size": 2228,
"cut_index": 563,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
const isoDateRegExp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
const randomRegExp = /^\d+\.\d+$/
describe('use-cache-with-server-function-props', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should be able to ... | xt()).toMatch('Hello, World!')
})
})
it('should be able to use nested cache functions as props', async () => {
const browser = await next.browser('/nested-cache')
await browser.elementById('submit-button-date').click()
await retry(asy | => {
expect(await browser.elementById('hi').text()).toMatch('Hi, World!')
})
await browser.elementById('submit-button-hello').click()
await retry(async () => {
expect(await browser.elementById('hello').te | {
"filepath": "test/e2e/app-dir/use-cache-with-server-function-props/use-cache-with-server-function-props.test.ts",
"language": "typescript",
"file_size": 1292,
"cut_index": 524,
"middle_length": 229
} |
ort { isNextDev, nextTestSetup } from 'e2e-utils'
import { waitForNoRedbox } from 'next-test-utils'
describe('hello-world', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: !isNextDev,
skipDeployment: true,
})
if (isNextDev) {
it('should not indicate there is an error when i... | se {
it('should not indicate there is an error when incidental math.random calls occur during component tree generation during build', async () => {
try {
await next.build()
} catch (e) {
console.error('Expected build to Suc | edbox assertion is currently unreliable in this test and so this is an additional check to ensure the CLI didn't print anything with `Math.random()` in it.
expect(next.cliOutput).not.toContain('Math.random()')
})
} el | {
"filepath": "test/e2e/app-dir/cache-components-create-component-tree/cache-components-create-component-tree.test.ts",
"language": "typescript",
"file_size": 1122,
"cut_index": 515,
"middle_length": 229
} |
})
it('hard nav to router page and soft nav around other router pages', async () => {
const browser = await next.browser('/')
await check(
() => browser.elementById('navSegment').text(),
'navSegment (parallel route):'
)
await check(
() => browser.elementById('authSegment').text(),... | parallel route):'
)
await check(
() => browser.elementById('routeSegment').text(),
'routeSegment (app route): foo'
)
})
it('hard nav to router page and soft nav to parallel routes', async () => {
const browser = await next. | href="/foo"]').click()
await check(
() => browser.elementById('navSegment').text(),
'navSegment (parallel route):'
)
await check(
() => browser.elementById('authSegment').text(),
'authSegment ( | {
"filepath": "test/e2e/app-dir/parallel-routes-use-selected-layout-segment/parallel-routes-use-selected-layout-segment.test.ts",
"language": "typescript",
"file_size": 5620,
"cut_index": 716,
"middle_length": 229
} |
opack } = nextTestSetup({
files: __dirname,
env: {
NEXT_DEPLOYMENT_ID: isNextStart ? 'test-deployment-id' : undefined,
},
disableAutoSkewProtection: true,
})
function beforePageLoad(page: Page) {
// TODO fix deployment id for webpack
if (isTurbopack && (isNextDeploy || isNextStart)) {... | ct(await browser.elementByCss('#worker-state').text()).toBe('default')
await browser.elementByCss('button').click()
await retry(async () =>
expect(await browser.elementByCss('#worker-state').text()).toBe(
'worker.ts:worker-dep'
| rams.get('dpl')).toBe(next.assetToken)
}
})
}
}
it('should support web workers with dynamic imports', async () => {
const browser = await next.browser('/classic', {
beforePageLoad,
})
expe | {
"filepath": "test/e2e/app-dir/worker/worker.test.ts",
"language": "typescript",
"file_size": 5707,
"cut_index": 716,
"middle_length": 229
} |
ed'
// TODO(NAR-423): Migrate to Cache Components.
describe.skip('ppr-middleware-rewrite-force-dynamic-generate-static-params', () => {
const { next } = nextTestSetup({
files: __dirname,
})
const expectedParams = JSON.stringify(expected)
it('should have correct dynamic params', async () => {
// shoul... | 1/2 with correct params
expect(await browser.elementByCss('p').text()).toBe(expectedParams)
// reloading the page should have the same params
await browser.refresh()
expect(await browser.elementByCss('p').text()).toBe(expectedParams)
})
| s('a').click()
// should be rewritten with /en/ | {
"filepath": "test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params.test.ts",
"language": "typescript",
"file_size": 917,
"cut_index": 606,
"middle_length": 52
} |
nction Page() {
return (
<>
<p>
This test does some hacky stuff to cause a `Math.random()` call to
happen during the component tree creation which happens before the RSC
render. Before the fix that this test accompanied landed this kind of
sync IO was reported as a problem in... | o the final prerender.
</p>
<p>
In the long run we ought to move create-component-tree into the render
itself and ensure the tree structure comports with CacheComponent rules.
This test can be deleted at that time.
| function will not leak any sync IO results int | {
"filepath": "test/e2e/app-dir/cache-components-create-component-tree/app/page.tsx",
"language": "tsx",
"file_size": 857,
"cut_index": 529,
"middle_length": 52
} |
use client'
import { useState } from 'react'
export default function Home() {
const [state, setState] = useState('default')
return (
<div>
<button
onClick={() => {
const worker = new SharedWorker(
new URL('../shared-worker', import.meta.url),
{
type... | r('message', (event) => {
setState(event.data)
})
worker.port.start()
})
worker.port.start()
}}
>
Get web worker data
</button>
<p>Worker state: </p>
<p id="w | worker
const worker = new SharedWorker(
new URL('../shared-worker', import.meta.url),
{
type: 'module',
}
)
worker.port.addEventListene | {
"filepath": "test/e2e/app-dir/worker/app/shared/page.js",
"language": "javascript",
"file_size": 1040,
"cut_index": 513,
"middle_length": 229
} |
port { Suspense } from 'react'
import ComponentClient from './component.client'
type Props = {
file: string
params: Promise<Record<string, string | string[]>>
}
async function ComponentServer(props: Props) {
const params = await props.params
return (
<code
data-server-file={props.file}
data-se... | back={<div data-loading>Loading Server...</div>}>
<ComponentServer {...props} />
</Suspense>
<Suspense fallback={<div data-loading>Loading Client...</div>}>
<ComponentClient file={props.file} />
</Suspense>
</div>
)
| <div>File: {props.file}</div>
<Suspense fall | {
"filepath": "test/e2e/app-dir/parallel-route-navigations/app/component.tsx",
"language": "tsx",
"file_size": 824,
"cut_index": 514,
"middle_length": 52
} |
tTestSetup } from 'e2e-utils'
describe('parallel-routes-and-interception-catchall', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should render intercepted route and preserve other slots', async () => {
const browser = await next.browser('/')
const homeContent = 'Home Page\n\nOp... | ntById('cart-modal-intercept').text()).toBe(
'Cart Modal'
)
// Children slot should still be the same
expect(await browser.elementById('children-slot').text()).toBe(homeContent)
expect(await browser.elementById('slot-slot').text()).t | text()).toBe(slotContent)
// Check if navigation to modal route works
await browser
.elementByCss('[href="/cart"]')
.click()
.waitForElementByCss('#cart-modal-intercept')
expect(await browser.eleme | {
"filepath": "test/e2e/app-dir/parallel-routes-and-interception-catchall/parallel-routes-and-interception-catchall.test.ts",
"language": "typescript",
"file_size": 1467,
"cut_index": 524,
"middle_length": 229
} |
<ul>
<li>
<Link href={'/first'} id="first" prefetch={false}>
First
</Link>
</li>
<li>
<Link href={'/first-client'} id="first-client" prefetch={false}>
First client
</Link>
</li>
<li>
<Link href={'/second... | ved-a" prefetch={false}>
Interleaved A
</Link>
</li>
<li>
<Link href={'/interleaved/b'} id="interleaved-b" prefetch={false}>
Interleaved B
</Link>
</li>
<li>
<L | client
</Link>
</li>
<li>
<Link href={'/third'} id="third" prefetch={false}>
Third
</Link>
</li>
<li>
<Link href={'/interleaved/a'} id="interlea | {
"filepath": "test/e2e/app-dir/css-order/app/nav.tsx",
"language": "tsx",
"file_size": 4624,
"cut_index": 614,
"middle_length": 229
} |
from 'e2e-utils'
describe('mdx-font-preload', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
'@next/mdx': 'canary',
'@mdx-js/loader': '^2.2.1',
'@mdx-js/react': '^2.2.1',
},
})
it('should render MDX page', async () => {
const browser = await next.bro... | ).toMatch(/myFont/)
})
it('should preload font from layout on MDX page', async () => {
const browser = await next.browser('/')
// Check for font preload link in DOM
const fontPreloadLinks = await browser.elementsByCss('link[as="font"]')
| })
it('should apply font class from layout', async () => {
const browser = await next.browser('/')
const fontFamily = await browser.eval(
'getComputedStyle(document.body).fontFamily'
)
expect(fontFamily | {
"filepath": "test/e2e/app-dir/mdx-font-preload/mdx-font-preload.test.ts",
"language": "typescript",
"file_size": 1521,
"cut_index": 537,
"middle_length": 229
} |
('missing-suspense-with-csr-bailout', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
// This test is skipped when deployed because it's not possible to rename files after deployment.
skipDeployment: true,
})
if (skipped) {
return
}
if (isN... | nse boundary at page "/".`
it('should fail build if useSearchParams is not wrapped in a suspense boundary', async () => {
const { exitCode } = await next.build()
expect(exitCode).toBe(1)
expect(next.cliOutput).toContain(message)
| EXT_CACHE_COMPONENTS === 'true'
describe('useSearchParams', () => {
const message = isCacheComponentsEnabled
? 'https://nextjs.org/docs/messages/blocking-route'
: `useSearchParams() should be wrapped in a suspe | {
"filepath": "test/e2e/app-dir/missing-suspense-with-csr-bailout/missing-suspense-with-csr-bailout.test.ts",
"language": "typescript",
"file_size": 2600,
"cut_index": 563,
"middle_length": 229
} |
pped } = nextTestSetup({
files: __dirname,
// This test is skipped because it sends requests with manipulated host headers
// which doesn't work in a deployed environment
skipDeployment: true,
})
if (skipped) return
it('should include x-forwarded-* headers', async () => {
const res = await n... | ers['middleware-x-forwarded-proto']).toBe(
url.protocol.replace(':', '')
)
})
describe('host header exists', () => {
it('should include x-forwarded-* headers relative to host', async () => {
const url = new URL(next.url)
cons | ort)
expect(headers['x-forwarded-proto']).toBe(url.protocol.replace(':', ''))
expect(headers['middleware-x-forwarded-host']).toBe(url.host)
expect(headers['middleware-x-forwarded-port']).toBe(url.port)
expect(head | {
"filepath": "test/e2e/app-dir/x-forwarded-headers/x-forwarded-headers.test.ts",
"language": "typescript",
"file_size": 3102,
"cut_index": 614,
"middle_length": 229
} |
ental: {
staleTimes: {
static: 30, // Minimum enforced by clientSegmentCache is 30 seconds
dynamic: 5,
},
},
},
})
if (isNextDev) {
it('should skip next dev for now', () => {})
return
}
it('should not fetch again when a static page was prefetched when navi... | t reveal.click()
return browser.elementByCss('#to-static-page')
},
{ includes: 'Static Page [prefetch-sentinel]' }
)
// Navigate to static page - should use prefetched data with no additional requests
await act(async () => | )
},
})
// Reveal the link to trigger prefetch and wait for it to complete
const link = await act(
async () => {
const reveal = await browser.elementByCss('#accordion-to-static-page')
awai | {
"filepath": "test/e2e/app-dir/app-prefetch/prefetching.stale-times.test.ts",
"language": "typescript",
"file_size": 12274,
"cut_index": 921,
"middle_length": 229
} |
ext dev for now', () => {})
return
}
it('NEXT_RSC_UNION_QUERY query name is _rsc', async () => {
expect(NEXT_RSC_UNION_QUERY).toBe('_rsc')
})
it('should show layout eagerly when prefetched with loading one level down', async () => {
let act: ReturnType<typeof createRouterAct>
const timeControl... | eveal.click()
await browser.waitForElementByCss('#to-dashboard')
return await browser.elementByCss('#to-dashboard')
},
{ includes: '[dashboard-prefetch-sentinel]' }
)
const before = Date.now()
await dashboardLink.cl | owser)
// Reveal the dashboard accordion and wait for prefetch to complete
const dashboardLink = await act(
async () => {
const reveal = await browser.elementByCss('#accordion-to-dashboard')
await r | {
"filepath": "test/e2e/app-dir/app-prefetch/prefetching.test.ts",
"language": "typescript",
"file_size": 19788,
"cut_index": 1331,
"middle_length": 229
} |
r) => {
return browser.eval(`
(() => {
const OriginalDate = Date;
const originalSetTimeout = globalThis.setTimeout;
const originalSetInterval = globalThis.setInterval;
const originalClearTimeout = globalThis.clearTimeout;
const originalClearInterval = glob... | }
static now() {
return fixedTime;
}
};
// Preserve static methods
Object.setPrototypeOf(globalThis.Date, OriginalDate);
// Override setTimeout
globalThis.setTim | lThis.Date = class extends OriginalDate {
constructor(...args) {
if (args.length === 0) {
super(fixedTime);
} else {
super(...args);
}
| {
"filepath": "test/e2e/app-dir/app-prefetch/test-utils.ts",
"language": "typescript",
"file_size": 3097,
"cut_index": 614,
"middle_length": 229
} |
mponents/link-accordion'
export default function HomePage() {
return (
<>
<p id="home-page">Home Page [prefetch-sentinel]</p>
<LinkAccordion href="/dashboard" id="to-dashboard">
To Dashboard
</LinkAccordion>
<LinkAccordion href="/static-page" id="to-static-page">
To Static... | -dynamic-page-no-params">
To Dynamic Page
</LinkAccordion>
<LinkAccordion href="/prefetch-auto/foobar" id="to-dynamic-page">
To Dynamic Slug Page
</LinkAccordion>
<a href="/static-page" id="to-static-page-hard">
| on>
<LinkAccordion href="/dynamic-page" id="to | {
"filepath": "test/e2e/app-dir/app-prefetch/app/page.js",
"language": "javascript",
"file_size": 908,
"cut_index": 547,
"middle_length": 52
} |
('app-dir - bun externals', () => {
const { next, isNextDev, isTurbopack, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should handle bun builtins as external modules', async () => {
const $ = await next.render$('/')
// When not runni... | found)')
})
it('should handle bun builtins in server actions', async () => {
const browser = await next.browser('/server-action')
await browser.elementByCss('#test-action').click()
await browser.waitForElementByCss('#action-result')
| ($('#bun-sqlite').text()).toBe('external (not found)')
expect($('#bun-test').text()).toBe('external (not found)')
expect($('#bun-wrap').text()).toBe('external (not found)')
expect($('#bun').text()).toBe('external (not | {
"filepath": "test/e2e/app-dir/bun-externals/bun-externals.test.ts",
"language": "typescript",
"file_size": 2801,
"cut_index": 563,
"middle_length": 229
} |
be handled as external modules
// When not running in Bun, require() will throw "Cannot find module"
let bunFfiStatus = 'not loaded'
let bunJscStatus = 'not loaded'
let bunSqliteStatus = 'not loaded'
let bunTestStatus = 'not loaded'
let bunWrapStatus = 'not loaded'
let bunStatus = 'not loaded'
try {
... | rnal (not found)'
: 'error: ' + e.message
}
try {
require('bun:sqlite')
bunSqliteStatus = 'loaded successfully'
} catch (e: any) {
bunSqliteStatus = e.message.includes('Cannot find module')
? 'external (not found)'
: 'e | ? 'external (not found)'
: 'error: ' + e.message
}
try {
require('bun:jsc')
bunJscStatus = 'loaded successfully'
} catch (e: any) {
bunJscStatus = e.message.includes('Cannot find module')
? 'exte | {
"filepath": "test/e2e/app-dir/bun-externals/app/page.tsx",
"language": "tsx",
"file_size": 2071,
"cut_index": 563,
"middle_length": 229
} |
import { NextResponse } from 'next/server'
export async function GET() {
const results: Record<string, string> = {}
const modules = [
{ name: 'bunFfi', module: 'bun:ffi' },
{ name: 'bunJsc', module: 'bun:jsc' },
{ name: 'bunSqlite', module: 'bun:sqlite' },
{ name: 'bunTest', module: 'bun:test' },
... | nd module error when not in Bun runtime
// This confirms the module was externalized (not bundled)
results[name] = e.message.includes('Cannot find module')
? 'external'
: 'error'
}
}
return NextResponse.json(results)
}
|
} catch (e: any) {
// Expected: Cannot fi | {
"filepath": "test/e2e/app-dir/bun-externals/app/api/bun-externals/route.ts",
"language": "typescript",
"file_size": 820,
"cut_index": 512,
"middle_length": 52
} |
r'
export async function testBunExternals() {
const modules = [
'bun:ffi',
'bun:jsc',
'bun:sqlite',
'bun:test',
'bun:wrap',
'bun',
]
const results: Record<string, string> = {}
for (const mod of modules) {
try {
require(mod)
results[mod] = 'loaded'
} catch (e: any) {... | les should be external (not found when not in Bun)
const allExternal = Object.values(results).every(
(r) => r === 'external (not found)' || r === 'loaded'
)
return allExternal
? 'All Bun modules are external'
: 'Some modules were not prop |
// All modu | {
"filepath": "test/e2e/app-dir/bun-externals/app/server-action/actions.ts",
"language": "typescript",
"file_size": 813,
"cut_index": 522,
"middle_length": 14
} |
('pnpm-workspace-root', () => {
const { next, skipped } = nextTestSetup({
files: {
'app/layout.tsx': `
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
... | ngify({
name: 'parent-workspace',
version: '1.0.0',
lockfileVersion: 3,
}),
// Write pnpm-workspace.yaml in the same parent directory.
// This file should be prioritized over lockfiles when determining root.
| >
}
`,
// Write a package-lock.json (npm lockfile, ignored by pnpm) to the application directory
// directory to create the scenario where multiple "lockfiles" exist.
'package-lock.json': JSON.stri | {
"filepath": "test/e2e/app-dir/pnpm-workspace-root/pnpm-workspace-root.test.ts",
"language": "typescript",
"file_size": 2682,
"cut_index": 563,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
describe('app-dir - esm js extension', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should be able to render nextjs api in app router', async () => {
const $ = await next.render$('/app')
async function validateDomNodes(selector: string) {
exp... | st.js"]').length).toBe(1)
})
it('should be able to use nextjs api in pages router', async () => {
const $ = await next.render$('/pages')
expect(await $('meta[name="head-value-1"]').attr('content')).toBe(
'with-ext'
)
expect(awai | ()).toContain(
'function'
)
}
await validateDomNodes('#with-ext')
await validateDomNodes('#without-ext')
expect($('head link[href="/test-ext.js"]').length).toBe(1)
expect($('head link[href="/te | {
"filepath": "test/e2e/app-dir/app-esm-js/index.test.ts",
"language": "typescript",
"file_size": 1359,
"cut_index": 524,
"middle_length": 229
} |
import fs 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 ESM app dir', () =... |
return
}
beforeAll(async () => {
await next.start()
})
it('should work correctly with output standalone', async () => {
const tmpFolder = path.join(os.tmpdir(), 'next-standalone-' + Date.now())
await fs.mkdirp(tmp | c: new FileRef(path.join(__dirname, 'public')),
'next.config.js': 'export default {"output": "standalone"}',
},
packageJson: {
type: 'module',
},
skipStart: true,
})
if (skipped) { | {
"filepath": "test/e2e/app-dir/app-esm-js/standalone.test.ts",
"language": "typescript",
"file_size": 2021,
"cut_index": 563,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
function countSubstring(str: string, substr: string): number {
return str.split(substr).length - 1
}
// TODO(NAR-423): Migrate to Cache Components.
describe.skip('ppr-metadata-blocking-ppr-fallback', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
// Need ... | itle>')).toBe(0)
})
it('should include viewport metadata in partial shell when metadata is dynamic under suspense', async () => {
const $ = await next.render$(
'/dynamic-metadata/partial?__nextppronly=fallback'
)
expect(countSubstrin | if (skipped) return
it('should not include metadata in partial shell when page is fully dynamic', async () => {
const $ = await next.render$('/fully-dynamic?__nextppronly=fallback')
expect(countSubstring($.html(), '<t | {
"filepath": "test/e2e/app-dir/ppr-metadata-blocking/ppr-metadata-blocking-ppr-fallback.test.ts",
"language": "typescript",
"file_size": 1501,
"cut_index": 524,
"middle_length": 229
} |
ge 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) => setTimeout(resolve, 500))
return (
... | spended component</div>
}
export async function generateMetadata() {
await connection()
await new Promise((resolve) => setTimeout(resolve, 3 * 1000))
return {
title: 'dynamic-metadata - partial',
description: `dynamic metadata - ${Math.rando | => setTimeout(resolve, 500))
return <div>nested su | {
"filepath": "test/e2e/app-dir/ppr-metadata-blocking/app/dynamic-metadata/partial/page.tsx",
"language": "tsx",
"file_size": 880,
"cut_index": 559,
"middle_length": 52
} |
rt { 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)... | meout(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',
| connection()
await new Promise((resolve) => setTi | {
"filepath": "test/e2e/app-dir/ppr-metadata-blocking/app/dynamic-page/partial/page.tsx",
"language": "tsx",
"file_size": 830,
"cut_index": 516,
"middle_length": 52
} |
stripAnsi from 'strip-ansi'
const nextConfigWithUseCache: NextConfig = {
experimental: { useCache: true },
}
describe('use-cache-without-experimental-flag', () => {
const { next, isNextStart, isTurbopack, skipped, isRspack } = nextTestSetup({
files: __dirname,
skipStart: process.env.NEXT_TEST_MODE !== 'd... | )
expect(buildOutput).toContain(
'Read more: https://nextjs.org/docs/app/api-reference/directives/use-cache#usage'
)
expect(buildOutput).toContain('Ecmascript file had an error')
expect(buildOutput).toContai | ild()
const buildOutput = getBuildOutput(cliOutput)
if (isTurbopack) {
expect(buildOutput).toContain(
'To use "use cache", please enable the feature flag `cacheComponents` in your Next.js config.'
| {
"filepath": "test/e2e/app-dir/use-cache-without-experimental-flag/use-cache-without-experimental-flag.test.ts",
"language": "typescript",
"file_size": 6514,
"cut_index": 716,
"middle_length": 229
} |
port { nextTestSetup } from 'e2e-utils'
describe('app dir - metadata dynamic routes with async deps', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
'@vercel/og': 'latest',
},
})
it('should render page with og:image meta tag when opengraph-image has async dependenci... | mage')
})
it('should serve the opengraph-image route as a valid image', async () => {
const res = await next.fetch('/blog/hello-world/opengraph-image')
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('image/png')
| ld/opengraph-i | {
"filepath": "test/e2e/app-dir/metadata-dynamic-routes-async-deps/index.test.ts",
"language": "typescript",
"file_size": 792,
"cut_index": 514,
"middle_length": 14
} |
sNextDeploy, skipped } = nextTestSetup({
files: __dirname,
// `patchFile` and reading runtime logs are not supported in a deployed environment
skipDeployment: true,
})
if (skipped) return
const pathPrefix = '/' + runtimeValue
let currentCliOutputIndex = 0
const ignorePreviousLogs = () => {
... | beforeEach(() => {
ignorePreviousLogs()
})
it('runs in dynamic pages', async () => {
const response = await next.fetch(pathPrefix + '/123/dynamic')
expect(response.status).toBe(200)
await retry(() => {
expect(getLogs()).toContain | putIndex) {
// cliOutput shrank since we started the test, so something (like a `sandbox`) reset the logs
currentCliOutputIndex = 0
}
return Log.readCliLogs(next.cliOutput.slice(currentCliOutputIndex))
}
| {
"filepath": "test/e2e/app-dir/next-after-app/index.test.ts",
"language": "typescript",
"file_size": 13327,
"cut_index": 921,
"middle_length": 229
} |
kies } from 'next/headers'
import { NextResponse, after } from 'next/server'
import { cliLog } from './utils/log'
export async function middleware(
/** @type {import ('next/server').NextRequest} */ request
) {
const url = new URL(request.url)
{
const match = url.pathname.match(
/^(?<prefix>\/[^/]+?)\/... | urn NextResponse.redirect(
new URL(prefix + '/middleware/redirect', request.url)
)
}
}
{
const match = url.pathname.match(
/^(?<prefix>\/[^/]+?)\/provided-request-context\/middleware/
)
if (match) {
const pref |
after(async () => {
cliLog({
source: '[middleware] /middleware/redirect-source',
requestId,
cookies: { testCookie: cookieStore.get('testCookie')?.value },
})
})
ret | {
"filepath": "test/e2e/app-dir/next-after-app/middleware.js",
"language": "javascript",
"file_size": 1411,
"cut_index": 524,
"middle_length": 229
} |
t { after } from 'next/server'
import { cookies } from 'next/headers'
export default async function Index() {
const cookieStore = await cookies()
after(async () => {
cookieStore.set('testCookie', 'after-render', { path: '/' })
})
const action = async () => {
'use server'
const cookieStore = await ... | ge with after() that tries to set cookies</h1>
<div id="cookie">
Cookie: {JSON.stringify(cookieStore.get('testCookie')?.value ?? null)}
</div>
<form action={action}>
<button type="submit">Submit</button>
</form>
| >
<h1>Pa | {
"filepath": "test/e2e/app-dir/next-after-app/app/nodejs/[id]/setting-cookies/page.js",
"language": "javascript",
"file_size": 800,
"cut_index": 517,
"middle_length": 14
} |
ort { after, connection } from 'next/server'
import { cache } from 'react'
import { cliLog } from '../../../utils/log'
const thing = cache(() => Symbol('cache me please'))
export default async function Index(props) {
await connection()
const valueFromRender = thing()
after(async () => {
const valueFromAfte... |
})
await new Promise((resolve) => setTimeout(resolve, 500))
after(() => {
const valueFromAfter = thing()
cliLog({
source: '[page] /nested-after (after #3)',
assertions: {
'cache() works in after()': val | r(() => {
const valueFromAfter = thing()
cliLog({
source: '[page] /nested-after (after #2)',
assertions: {
'cache() works in after()': valueFromRender === valueFromAfter,
},
}) | {
"filepath": "test/e2e/app-dir/next-after-app/app/nodejs/nested-after/page.js",
"language": "javascript",
"file_size": 1113,
"cut_index": 515,
"middle_length": 229
} |
ter } from 'next/server'
import { Suspense } from 'react'
import { cliLog } from '../../../../../utils/log'
export default async function Page() {
await connection()
after(() => {
cliLog({
source: '[page] /interrupted/incomplete-stream/hang',
})
})
return (
<main>
<h1>Hanging forever</h... | else
'Loading' + (Math.random() > 1 ? 'impossible' : '') + '...'
}
</div>
}
>
<HangForever />
</Suspense>
</main>
)
}
async function HangForever() {
await new Promise((_resolve) => { | ure it doesn't show up in the literal form someplace | {
"filepath": "test/e2e/app-dir/next-after-app/app/nodejs/interrupted/incomplete-stream/hang/page.js",
"language": "javascript",
"file_size": 848,
"cut_index": 535,
"middle_length": 52
} |
('Script component with beforeInteractive strategy CSS class rendering', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should render script tag with correct class attribute instead of classname', async () => {
const browser = await next.browser('/')
// Wait for the page to fully ... | he script element directly
const scriptElement = await browser.elementByCss('script#example-script')
const className = await scriptElement.getAttribute('class')
expect(className).toBe('example-class')
})
it('should execute beforeInteracti | mentElement.innerHTML)
// Check that the script tag has 'class' attribute, not 'classname'
expect(html).toContain('class="example-class"')
expect(html).not.toContain('classname="example-class"')
// Also verify t | {
"filepath": "test/e2e/app-dir/script-before-interactive/script-before-interactive.test.ts",
"language": "typescript",
"file_size": 2247,
"cut_index": 563,
"middle_length": 229
} |
xport default function MultiplePage() {
return (
<div>
<h1>Multiple beforeInteractive Scripts Test</h1>
<Script
id="first-script"
strategy="beforeInteractive"
className="first-script"
dangerouslySetInnerHTML={{
__html: `
console.log('First beforeIn... | nnerHTML={{
__html: `
console.log('Second beforeInteractive script executed');
window.secondScriptExecuted = true;
`,
}}
/>
<p>
This page tests multiple beforeInteractive scripts with | className="second-script"
dangerouslySetI | {
"filepath": "test/e2e/app-dir/script-before-interactive/app/multiple/page.tsx",
"language": "tsx",
"file_size": 896,
"cut_index": 547,
"middle_length": 52
} |
'
const isAdapterTest = Boolean(process.env.NEXT_ENABLE_ADAPTER)
type NextInstance = ReturnType<typeof nextTestSetup>['next']
function createSplitHTMLFetcher(next: NextInstance) {
return async function fetchSplitHTML(pathname: string) {
let response: Awaited<ReturnType<typeof next.fetch>> | undefined
const... | oad(staticPart),
}
}
}
describe('partial-fallback-shell-upgrade', () => {
const { next, isNextDev } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'default'),
// The latest changes to support this behavior on deployed infra are | nse.body) {
throw new Error(`Expected a streamed response body for ${pathname}`)
}
return response.body
}
)
return {
response: response!,
dynamicPart,
static$: cheerio.l | {
"filepath": "test/e2e/app-dir/partial-fallback-shell-upgrade/partial-fallback-shell-upgrade.test.ts",
"language": "typescript",
"file_size": 5990,
"cut_index": 716,
"middle_length": 229
} |
await browser.loadPage(new URL(`/?n=1&unrelated`, next.url).toString())
expect(await browser.waitForElementByCss('#x').text()).toBe('1')
const random1b = await browser.waitForElementByCss('#y').text()
// The two navigations to n=1 should use a cached value.
expect(random1a).toBe(random1b)
// The ... | ync () => {
const browser = await next.browser(`/custom-handler?n=1`)
expect(await browser.waitForElementByCss('#x').text()).toBe('1')
const random1a = await browser.waitForElementByCss('#y').text()
await browser.loadPage(new URL(`/custom- | xt()).toBe('foo')
// Client component child should have rendered but not invalidated the cache.
expect(await browser.waitForElementByCss('#r').text()).toContain('rnd')
})
it('should cache results custom handler', as | {
"filepath": "test/e2e/app-dir/use-cache/use-cache.test.ts",
"language": "typescript",
"file_size": 63241,
"cut_index": 2151,
"middle_length": 229
} |
t { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
describe('RSC binary serialization', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
dependencies: {
'server-only': 'latest',
},
})
if (skipped) return
afterEach(async (... | nt = await browser.elementByCss('body').text()
return content.includes('utf8 binary: hello') &&
content.includes('arbitrary binary: 255,0,1,2,3') &&
content.includes('hydrated: true')
? 'success'
: 'fail'
}, 'succ | const conte | {
"filepath": "test/e2e/app-dir/binary/rsc-binary.test.ts",
"language": "typescript",
"file_size": 801,
"cut_index": 517,
"middle_length": 14
} |
e client'
import { useActionState } from 'react'
export function Form({
revalidateAction,
initialValues,
}: {
revalidateAction: (type: 'tag' | 'path') => Promise<[number, number, string]>
initialValues: [number, number, string]
}) {
const [
[useCacheValue1, useCacheValue2, fetchedValue],
revalidate,... | alue}</p>
<button
id="revalidate-tag"
formAction={() => revalidate('tag')}
disabled={isPending}
>
Revalidate Tag
</button>
<button
id="revalidate-path"
formAction={() => revalidate('pa |
before revalidate: <span id="use-cache-value-1">{useCacheValue1}</span>
</p>
<p>
after revalidate: <span id="use-cache-value-2">{useCacheValue2}</span>
</p>
<p id="fetched-value">{fetchedV | {
"filepath": "test/e2e/app-dir/use-cache/app/(dynamic)/revalidate-and-use/form.tsx",
"language": "tsx",
"file_size": 1101,
"cut_index": 515,
"middle_length": 229
} |
{ revalidatePath, cacheTag, updateTag } from 'next/cache'
import { Form } from './form'
import { connection } from 'next/server'
async function fetchCachedValue() {
return fetch('https://next-data-api-endpoint.vercel.app/api/random', {
next: { tags: ['revalidate-and-use'], revalidate: false },
}).then((res) =... | ()
if (type === 'tag') {
updateTag('revalidate-and-use')
} else {
revalidatePath('/revalidate-and-use')
}
return Promise.all([
initialCachedValue,
getCachedValue(),
fetchCa | s we don't want to deal with ISR in this scenario.
await connection()
return (
<Form
revalidateAction={async (type: 'tag' | 'path') => {
'use server'
const initialCachedValue = await getCachedValue | {
"filepath": "test/e2e/app-dir/use-cache/app/(dynamic)/revalidate-and-use/page.tsx",
"language": "tsx",
"file_size": 1180,
"cut_index": 518,
"middle_length": 229
} |
ort { connection } from 'next/server'
import { Suspense } from 'react'
import { setTimeout } from 'timers/promises'
async function Inner() {
await setTimeout(1000)
return <p className="inner">{Math.random()}</p>
}
// We're only using the id to force using a different cache key for different
// test scenarios.
as... | e: remote'
return <InnerCached id={id} name="inner" />
}
export default async function Page({
params,
}: {
params: Promise<{ id: string }>
}) {
await connection()
const { id } = await params
return (
<>
<OuterCached1 id={id} name=" | e>
)
}
async function OuterCached1({ id }: { id: string; name: string }) {
'use cache: remote'
return <InnerCached id={id} name="inner" />
}
async function OuterCached2({ id }: { id: string; name: string }) {
'use cach | {
"filepath": "test/e2e/app-dir/use-cache/app/(dynamic)/nested/[id]/page.tsx",
"language": "tsx",
"file_size": 1070,
"cut_index": 515,
"middle_length": 229
} |
'next/navigation'
export default function Page() {
//
return (
<>
<p>
This tests a regression case where an action called outside of a React
transition scope (onClick, in this case) results in a server-side
redirect. Before the fix, the external redirect would get swallowed by
... | uest.)
</p>
<button
id="external-redirect-from-action-on-click"
onClick={async () => {
'use server'
redirect('http://localhost:9292')
}}
>
External Redirect
</button>
</>
)
} | the req | {
"filepath": "test/e2e/app-dir/external-redirect/app/page.tsx",
"language": "tsx",
"file_size": 807,
"cut_index": 536,
"middle_length": 14
} |
t { createSandbox } from 'development-sandbox'
describe('use-cache-unknown-cache-kind', () => {
const { next, isNextStart, isTurbopack, isRspack, skipped } = nextTestSetup({
files: __dirname,
skipStart: process.env.NEXT_TEST_MODE !== 'dev',
skipDeployment: true,
})
if (skipped) {
return
}
i... | andler for this kind in the \`cacheHandlers\` object in your Next.js config.
> 1 | 'use cache: custom'
| ^^^^^^^^^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</ | ut)
if (isTurbopack) {
expect(buildOutput).toMatchInlineSnapshot(`
"Error: Turbopack build failed with 1 errors:
./app/page.tsx:1:1
Unknown cache kind "custom". Please configure a cache h | {
"filepath": "test/e2e/app-dir/use-cache-unknown-cache-kind/use-cache-unknown-cache-kind.test.ts",
"language": "typescript",
"file_size": 6947,
"cut_index": 716,
"middle_length": 229
} |
import { nextTestSetup } from 'e2e-utils'
describe('{{name}}', () => {
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 cheerio', async () => {
const $ = await next.render$('/')
... | r('/')
expect(html).toContain('hello world')
})
// In case you need to test the response object
it('should work with fetch', async () => {
const res = await next.fetch('/')
const html = await res.text()
expect(html).toContain('hello | )
expect(await browser.elementByCss('p').text()).toBe('hello world')
})
// In case you need the full HTML. Can also use $.html() with cheerio.
it('should work with html', async () => {
const html = await next.rende | {
"filepath": "test/e2e/app-dir/test-template/{{ toFileName name }}/{{ toFileName name }}.test.ts",
"language": "typescript",
"file_size": 1013,
"cut_index": 512,
"middle_length": 229
} |
: string
status: '200' | '404'
}
type RouteSection = {
title: string
columns: string[]
routes: RouteInfo[]
}
const ROUTE_SECTIONS: RouteSection[] = [
{
title: 'Base Routes',
columns: ['Route', 'Expected Status'],
routes: [
{ href: '/en', status: '200' },
{ href: '/fr', status: '200' ... | ['Route', 'Expected Status'],
routes: [
{
href: '/en/gsp/stories/static-123',
status: '200',
},
{
href: '/fr/gsp/stories/static-123',
status: '200',
},
{
href: '/es/gsp/stories/stati | ynamic-123', status: '200' },
{ href: '/fr/no-gsp/stories/dynamic-123', status: '200' },
{ href: '/es/no-gsp/stories/dynamic-123', status: '200' },
],
},
{
title: 'With generateStaticParams',
columns: | {
"filepath": "test/e2e/app-dir/parallel-routes-root-param-dynamic-child/app/[locale]/layout.client.tsx",
"language": "tsx",
"file_size": 3449,
"cut_index": 614,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
import type { Response } from 'node-fetch'
import cookies, { nextConfigHeaders } from './cookies.mjs'
function getSetCookieHeaders(res: Response): ReadonlyArray<string> {
return (
(res.headers as any).getSetCookie?.() ??
(res.headers as any).raw()['set-cookie']
)
}
describe(... | imes)('for %s runtime', (runtime) => {
it('should set two set-cookie headers', async () => {
let res = await next.fetch(`/api/${dir}/${runtime}`)
let headers = getSetCookieHeaders(res)
expect(headers).toHaveLength(2)
| skipped) {
return
}
describe.each([
{ dir: 'pages', runtimes: ['edge', 'experimental-edge', 'node'] },
{ dir: 'app', runtimes: ['edge', 'node'] },
])('for /$dir', ({ dir, runtimes }) => {
describe.each(runt | {
"filepath": "test/e2e/app-dir/set-cookies/set-cookies.test.ts",
"language": "typescript",
"file_size": 1323,
"cut_index": 524,
"middle_length": 229
} |
uteRedirect,
multiRelativeRedirect,
relativeRedirect,
} from '../actions'
export default function Page() {
return (
<>
<p>hello subdir page</p>
<button
onClick={async () => {
startTransition(async () => {
await relativeRedirect()
})
}}
id="r... | relative-subdir-redirect"
>
multi-level relative redirect
</button>
<button
onClick={async () => {
startTransition(async () => {
await absoluteRedirect()
})
}}
id="absolute-s | edirect()
})
}}
id="multi- | {
"filepath": "test/e2e/app-dir/server-actions-relative-redirect/app/subdir/page.tsx",
"language": "tsx",
"file_size": 970,
"cut_index": 582,
"middle_length": 52
} |
dge SSR', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should handle edge only routes', async () => {
const appHtml = await next.render('/edge/basic')
expect(appHtml).toContain('<p>Edge!</p>')
const pageHtml... | apis/process')
expect(await $('#process').text()).toContain('object')
})
it('should handle /index routes correctly', async () => {
const appHtml = await next.render('/index')
expect(appHtml).toContain('the /index route')
})
if ((globa | nst res = await next.fetch('/edge-apis/cookies')
expect(await res.text()).toInclude('Hello')
})
it('should treat process as object without polyfill in edge runtime', async () => {
const $ = await next.render$('/edge- | {
"filepath": "test/e2e/app-dir/app-edge/app-edge.test.ts",
"language": "typescript",
"file_size": 3108,
"cut_index": 614,
"middle_length": 229
} |
waitForRedbox,
waitForNoRedbox,
getRedboxDescription,
} from 'next-test-utils'
describe('app dir - unauthorized with default unauthorized boundary', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
// TODO: err... | )
}
})
// TODO: error unauthorized usage in root layout
it.skip('should error on server unauthorized from root layout on server-side', async () => {
const browser = await next.browser('/?root-unauthorized=1')
if (isNextDev) {
aw | lementByCss('#trigger-unauthorized').click()
if (isNextDev) {
await waitForRedbox(browser)
expect(await getRedboxDescription(browser)).toMatch(
/unauthorized\(\) is not allowed to use in root layout/
| {
"filepath": "test/e2e/app-dir/unauthorized/default/unauthorized-default.test.ts",
"language": "typescript",
"file_size": 2604,
"cut_index": 563,
"middle_length": 229
} |
nextTestSetup({
files: __dirname,
dependencies: {
sass: 'latest',
},
})
it('should successfully hard navigate from pages -> app', async () => {
const browser = await next.browser('/base/pages-path')
await browser.elementByCss('#to-another').click()
// Hard nav from pages -> app trigge... | yCss('a[href="/base/another"]')
.click()
.waitForElementByCss('#page-2')
.text()
).toBe(`Page 2`)
})
it('should prefix segment metadata og image with basePath and pathname', async () => {
const $ = await next.render$('/ | er('/base')
expect(html).toContain('<h1>Test Page</h1>')
})
it('should support Link with basePath prefixed', async () => {
const browser = await next.browser('/base')
expect(
await browser
.elementB | {
"filepath": "test/e2e/app-dir/app-basepath/index.test.ts",
"language": "typescript",
"file_size": 7042,
"cut_index": 716,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('dynamic-interception-route-revalidate', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should refresh the dynamic intercepted route when the interception route is revalidated', async () => {
const browser ... | e fired
await browser.waitForElementByCss('#loading')
// verify that we get a result from the server action
await retry(async () => {
const result = await browser.elementByCss('#result').text()
expect(result).toMatch(/^Result: 0(\. | .waitForElementByCss('#intercepted-page')
expect(await browser.elementByCss('h2').text()).toBe('Photo Id: 1')
// trigger the revalidate
await browser.elementByCss('button').click()
// make sure the loading stat | {
"filepath": "test/e2e/app-dir/dynamic-interception-route-revalidate/dynamic-interception-route-revalidate.test.ts",
"language": "typescript",
"file_size": 1444,
"cut_index": 524,
"middle_length": 229
} |
utils'
import { retry } from 'next-test-utils'
describe('actions-revalidate-remount', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should not remount the page + loading component when revalidating', async () => {
const browser = await next.browser('/test')
const initialTime = aw... | .toMatch(/Time: \d+/)
// The time should be updated
expect(initialTime).not.toBe(time)
const logs = (await browser.log()).filter(
(log) => log.message === 'Loading Mounted'
)
// There should not be any loading logs
| rowser.elementById('time').text()
expect(time) | {
"filepath": "test/e2e/app-dir/actions-revalidate-remount/actions-revalidate-remount.test.ts",
"language": "typescript",
"file_size": 904,
"cut_index": 547,
"middle_length": 52
} |
from 'e2e-utils'
// TODO(NAR-423): Migrate to Cache Components.
describe.skip('static-shell-debugging', () => {
const ppr = Boolean(process.env.__NEXT_CACHE_COMPONENTS)
const context = {
ppr,
debugging: ppr,
}
const { next, skipped, isNextDev } = nextTestSetup({
files: __dirname,
// This test ... | xt.ppr) {
it('should only render the static shell', async () => {
const res = await next.fetch('/?__nextppronly=1')
expect(res.status).toBe(200)
const html = await res.text()
expect(html).toContain('Fallback')
expect(html | EXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING: context.debugging
? '1'
: undefined,
},
nextConfig: {
experimental: { ppr: context.ppr },
},
})
if (skipped) return
if (context.debugging && conte | {
"filepath": "test/e2e/app-dir/static-shell-debugging/static-shell-debugging.test.ts",
"language": "typescript",
"file_size": 1836,
"cut_index": 537,
"middle_length": 229
} |
-test-utils'
const runtimes = ['nodejs', 'edge']
const WAIT_BEFORE_REVALIDATING = 1000
// If we want to verify that `after()` ran its callback,
// we need it to perform some kind of side effect (because it can't affect the response).
// In other tests, we often use logs for this, but we don't have access to those in... | ntimes)('after() in %s runtime', (runtimeValue) => {
const { next, skipped } = nextTestSetup({
files: __dirname,
env: { WAIT_BEFORE_REVALIDATING: WAIT_BEFORE_REVALIDATING + '' },
})
const retryDuration = WAIT_BEFORE_REVALIDATING * 2
if (sk | f it did, we successfully ran the callback (and performed a side effect).
// This test relies on revalidating a static page, so it can't work in dev mode.
const _describe = isNextDev ? describe.skip : describe
_describe.each(ru | {
"filepath": "test/e2e/app-dir/next-after-app-deploy/index.test.ts",
"language": "typescript",
"file_size": 4230,
"cut_index": 614,
"middle_length": 229
} |
nst revalidate = 3600 // arbitrarily long, just so that it doesn't happen during a test run
export const dynamicParams = true
export async function generateStaticParams() {
return ['nodejs', 'edge'].flatMap((runtime) =>
['dynamic-page', 'middleware', 'route', 'server-action'].map((page) => ({
key: `/${runt... | {
const decoded = decodeURIComponent(key)
new URL(decoded, 'http://__n')
path = decoded
} catch (err) {}
return (
<>
{path !== null && (
<Link prefetch={false} href={path}>
Go to {path}
</Link>
)} | /key/[key] rendered', data)
let path = null
try | {
"filepath": "test/e2e/app-dir/next-after-app-deploy/app/timestamp/key/[key]/page.js",
"language": "javascript",
"file_size": 960,
"cut_index": 582,
"middle_length": 52
} |
tion Home() {
return (
<div className="flex min-h-screen items-center justify-center bg-zinc-50 font-sans dark:bg-black font-[family-name:var(--font-geist-sans)]">
<main className="flex min-h-screen w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
... | the page.tsx file.
</h1>
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{' '}
<a
href="https://vercel.com | ssName="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit | {
"filepath": "test/e2e/app-dir/middleware-rewrite-dynamic/app/page.tsx",
"language": "tsx",
"file_size": 2925,
"cut_index": 563,
"middle_length": 229
} |
mport { nextTestSetup } from 'e2e-utils'
describe('external-redirect', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('regression: Server Action triggered from onClick redirects to external URL', async () => {
let page
const browser = await next.browser('/', {
async beforePag... | return route.continue()
})
},
})
const button = await browser.elementById(
'external-redirect-from-action-on-click'
)
await button.click()
await page.waitForNavigation('http://localhost:9292')
expect(await page. | if (req.url().includes('localhost:9292')) {
return route.fulfill({
status: 200,
body: '<!DOCTYPE html><html><body>External page</body></html>',
})
}
| {
"filepath": "test/e2e/app-dir/external-redirect/external-redirect.test.ts",
"language": "typescript",
"file_size": 1047,
"cut_index": 513,
"middle_length": 229
} |
on } from 'next/server'
import { ReactNode, Suspense } from 'react'
// A cache fill in the Dynamic stage (after `connection()`) should not be
// subject to the dev fill timeout. This mirrors prerender, where caches
// past `connection()` aren't executed at all and therefore not subject to
// the timeout handling eithe... | imeout(resolve, 12_000))
return <p id="cached">cached</p>
}
async function Dynamic(): Promise<ReactNode> {
await connection()
return <Cached />
}
export default function Page() {
return (
<Suspense fallback="Loading...">
<Dynamic />
| 'use cache'
await new Promise((resolve) => setT | {
"filepath": "test/e2e/app-dir/use-cache-hanging/app/dynamic/page.tsx",
"language": "tsx",
"file_size": 858,
"cut_index": 529,
"middle_length": 52
} |
return result
}
const PAGES: Record<
string,
{
group: string
url: string
selector: string
color: string
background?: string
conflict?: boolean
conflictTurbo?: boolean
brokenLoading?: boolean
brokenLoadingDev?: boolean
requests?: number
requestsLoose?: number
requ... | lient': {
group: 'basic',
url: '/first-client',
selector: '#hello1c',
color: 'rgb(255, 0, 255)',
requests: 1,
},
'second-client': {
group: 'basic',
url: '/second-client',
selector: '#hello2c',
color: 'rgb(255, 128, 0 | rl: '/second',
selector: '#hello2',
color: 'rgb(0, 128, 0)',
requests: 1,
},
third: {
group: 'basic',
url: '/third',
selector: '#hello3',
color: 'rgb(0, 128, 128)',
requests: 1,
},
'first-c | {
"filepath": "test/e2e/app-dir/css-order/css-order.test.ts",
"language": "typescript",
"file_size": 14626,
"cut_index": 921,
"middle_length": 229
} |
{ nextTestSetup } from 'e2e-utils'
describe('app-dir - params hooks compat', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should only access search params with useSearchParams', async () => {
const browserApp = await next.browser('/app/foobar?q=app')
const appSearchparamsJSON =... | params with useParams', async () => {
const browserApp = await next.browser('/app/foobar?a=app')
const appParamsJSON = JSON.parse(
await browserApp.elementByCss('#use-params').text()
)
const browserPages = await next.browser('/pages/f | parse(
await browserPages.elementByCss('#use-search-params').text()
)
expect(appSearchparamsJSON).toEqual({ q: 'app' })
expect(pagesSearchparamsJSON).toEqual({ q: 'pages' })
})
it('should only access path | {
"filepath": "test/e2e/app-dir/params-hooks-compat/index.test.ts",
"language": "typescript",
"file_size": 1244,
"cut_index": 518,
"middle_length": 229
} |
test-utils'
describe('parallel-routes-catchall-groups', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should work without throwing any errors about conflicting paths', async () => {
const browser = await next.browser('/')
await check(() => browser.elementByCss('body').text(), /H... | ar doesn't have an explicit page path. (group-a) defines a catch-all slot with a separate root layout
// that only renders a slot (ie no children). So we'd expect to see the fallback slot content
await browser.elementByCss('[href="/bar"]').click()
| t(), /Foo Page/)
await browser.back()
// /b | {
"filepath": "test/e2e/app-dir/parallel-routes-catchall-groups/parallel-routes-catchall-groups.test.ts",
"language": "typescript",
"file_size": 968,
"cut_index": 582,
"middle_length": 52
} |
tSetup } from 'e2e-utils'
import path from 'path'
describe('app-dir edge SSR invalid reexport', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: {
'app/export': new FileRef(path.join(__dirname, 'app', 'export')),
'app/export/inherit/page.tsx':
"export { default, runtime, pr... | // Turbopack is stricter and disallows reexports completely
// webpack merely warns in the CLI and still serves the page wuthout a redbox
if (process.env.IS_TURBOPACK_TEST) {
await expect(browser).toDisplayRedbox(`
{
| ntime/preferredRegion config', async () => {
try {
await next.start()
} catch (_) {
// We expect the build to fail
}
if (isNextDev) {
const browser = await next.browser('/export/inherit')
| {
"filepath": "test/e2e/app-dir/app-edge/app-edge-invalid-reexport.test.ts",
"language": "typescript",
"file_size": 1817,
"cut_index": 537,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
describe('app dir - unauthorized - basic', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should match dynamic route unauthorized boundary correctly', async () => {
// `/dynamic` display works
const browserDynamic = await next.browser('/dynamic')
... | t browserDynamicId.elementByCss('#page').text()).toBe(
'dynamic [id]'
)
})
it('should escalate unauthorized to parent layout if no unauthorized boundary present in current layer', async () => {
const browserDynamic = await next.browser(
| await next.browser('/dynamic/401')
expect(await browserError.elementByCss('#unauthorized').text()).toBe(
'dynamic/[id] unauthorized'
)
const browserDynamicId = await next.browser('/dynamic/123')
expect(awai | {
"filepath": "test/e2e/app-dir/unauthorized/basic/unauthorized-basic.test.ts",
"language": "typescript",
"file_size": 1498,
"cut_index": 524,
"middle_length": 229
} |
/action'
export default function Page() {
return (
<div>
<form>
<button
id="redirect-relative"
formAction={() => redirectAction('/another')}
>
redirect internal with relative path
</button>
</form>
<form>
<button
id="redire... | d="redirect-absolute-external"
formAction={() =>
redirectAction(location.origin + '/outsideBasePath')
}
>
redirect external with domain (excluding basePath)
</button>
</form>
</div>
)
}
| </form>
<form>
<button
i | {
"filepath": "test/e2e/app-dir/app-basepath/app/client/page.js",
"language": "javascript",
"file_size": 867,
"cut_index": 559,
"middle_length": 52
} |
export function middleware(
/** @type {import ('next/server').NextRequest} */ request
) {
const url = new URL(request.url)
const match = url.pathname.match(/^(?<prefix>\/[^/]+?)\/middleware/)
if (match) {
const pathPrefix = match.groups.prefix
after(async () => {
// we can't call revalidatePath... | validate)
const response = await fetch(postUrl, { method: 'POST' })
if (!response.ok) {
throw new Error(
`Failed to revalidate path '${pathToRevalidate}' (status: ${response.status})`
)
}
})
}
}
export co | )
postUrl.searchParams.append('path', pathToRe | {
"filepath": "test/e2e/app-dir/next-after-app-deploy/middleware.js",
"language": "javascript",
"file_size": 908,
"cut_index": 547,
"middle_length": 52
} |
retry } from 'next-test-utils'
describe('server-actions-relative-redirect', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should work with relative redirect', async () => {
const browser = await next.browser('/')
await browser.waitForElementByCss('#relative-redirect').click()
... | ()).toBe(
'hello nested page'
)
})
})
it('should work with relative redirect from subdir', async () => {
const browser = await next.browser('/subdir')
await browser.waitForElementByCss('#relative-subdir-redirect').click()
| ct', async () => {
const browser = await next.browser('/')
await browser.waitForElementByCss('#absolute-redirect').click()
await retry(async () => {
expect(await browser.waitForElementByCss('#page-loaded').text | {
"filepath": "test/e2e/app-dir/server-actions-relative-redirect/server-actions-relative-redirect.test.ts",
"language": "typescript",
"file_size": 2048,
"cut_index": 563,
"middle_length": 229
} |
tTestSetup({
skipDeployment: true,
files: __dirname,
})
if (skipped) return
if (isNextStart) {
it('should not log server actions in production mode', async () => {
const browser = await next.browser('/')
const outputIndex = next.cliOutput.length
await browser.elementByCss('#succes... |
const browser = await next.browser('/')
const outputIndex = next.cliOutput.length
await browser.elementByCss('#success-action').click()
await browser.waitForElementByCss('#result')
await retry(() => {
const logs = stripAnsi(nex | put.slice(outputIndex))
// Should not contain the server action log format
expect(logs).not.toContain('└─ ƒ successAction')
})
})
return
}
it('should log successful server action', async () => { | {
"filepath": "test/e2e/app-dir/server-action-logging/server-action-logging.test.ts",
"language": "typescript",
"file_size": 7347,
"cut_index": 716,
"middle_length": 229
} |
ort default function ActionButtons({
successAction,
multiArgAction,
redirectAction,
notFoundAction,
errorAction,
objectArgAction,
arrayArgAction,
inlineAction,
promiseArgAction,
}) {
const [result, setResult] = useState(null)
const [error, setError] = useState(null)
const handleSuccess = async ... | )
} catch (e) {
setError('notFound triggered')
}
}
const handleError = async () => {
setError(null)
try {
await errorAction()
} catch (e) {
setError(e.message)
}
}
const handleObjectArg = async () => {
| )
setResult(res)
}
const handleRedirect = async () => {
setError(null)
await redirectAction('/redirect-target')
}
const handleNotFound = async () => {
setError(null)
try {
await notFoundAction( | {
"filepath": "test/e2e/app-dir/server-action-logging/app/action-buttons.js",
"language": "javascript",
"file_size": 2761,
"cut_index": 563,
"middle_length": 229
} |
erver'
import { redirect } from 'next/navigation'
import { notFound } from 'next/navigation'
// Simple successful action
export async function successAction(value) {
return { result: value + 1 }
}
// Action with multiple arguments
export async function multiArgAction(a, b, c) {
return { sum: a + b + c }
}
// Ac... | on objectArgAction(data) {
return { received: data }
}
// Action with array argument
export async function arrayArgAction(items) {
return { count: items.length }
}
// Inline action export for testing inline action display
export const inlineAction = | oundAction() {
notFound()
}
// Action that throws an error (should show 500 status)
export async function errorAction() {
throw new Error('Intentional error for testing')
}
// Action with object argument
export async functi | {
"filepath": "test/e2e/app-dir/server-action-logging/app/actions.js",
"language": "javascript",
"file_size": 1193,
"cut_index": 518,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
describe('metadata-invalid-image-file', () => {
const { next, isTurbopack, isNextDev, skipped, isRspack } = nextTestSetup({
files: __dirname,
skipDeployment: true,
skipStart: true,
})
if (skipped) return
it('should error on invalid metadata image file', async () => {... | ).toContain('unable to decode image data')
} else {
expect(next.cliOutput).toContain(
'Error: Process image "/favicon.ico" failed:'
)
}
if (!isNextDev) {
// `next build` should fail
if (isTurbopack) {
ex | // In turbopack the image decoding error is displayed in multiple lines
expect(next.cliOutput).toContain('app/favicon.ico')
expect(next.cliOutput).toContain('Processing image failed')
expect(next.cliOutput | {
"filepath": "test/e2e/app-dir/metadata-invalid-image-file/metadata-invalid-image-file.test.ts",
"language": "typescript",
"file_size": 1335,
"cut_index": 524,
"middle_length": 229
} |
from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('rsc-query-routing', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should contain rsc query in rsc request when redirect the page', async () => {
const browser = await next.browser('/redirect')
const rscRequestUrl... | redirect source and dest urls should both contain the rsc query
expect(rscRequestUrls[0]).toContain('/redirect/source')
expect(rscRequestUrls[1]).toContain('/redirect/dest')
})
it('should contain rsc query in rsc request when rewrite the page | = await browser.elementByCss('a')
await link.click()
// Wait for the page load to be completed
await retry(async () => {
expect(await browser.elementByCss('h1').text()).toBe('Redirect Dest')
})
// The | {
"filepath": "test/e2e/app-dir/rsc-query-routing/rsc-query-routing.test.ts",
"language": "typescript",
"file_size": 1650,
"cut_index": 537,
"middle_length": 229
} |
Output: string) {
let cliIndex = 0
return function expectError(
containing: string,
withStackContaining?: string
) {
const initialCliIndex = cliIndex
let lines = cliOutput.slice(cliIndex).split('\n')
let i = 0
while (i < lines.length) {
let line = lines[i++] + '\n'
cliIndex +=... | return
}
}
}
}
}
expect(cliOutput.slice(initialCliIndex)).toContain(containing)
}
}
describe(`Request Promises`, () => {
describe('On Prerender Completion', () => {
const { next, isNextDev, skipped } = | t stackLine = lines[i++] + '\n'
if (!stackStart.test(stackLine)) {
expect(stackLine).toContain(withStackContaining)
}
if (stackLine.includes(withStackContaining)) {
| {
"filepath": "test/e2e/app-dir/cache-components-request-apis/cache-components-request-apis.test.ts",
"language": "typescript",
"file_size": 3434,
"cut_index": 614,
"middle_length": 229
} |
nnection } from 'next/server'
export default async function Page(props: {
params: Promise<{}>
searchParams: Promise<{}>
}) {
props.params.catch(logReason)
props.searchParams.catch(logReason)
cookies().catch(logReason)
headers().catch(logReason)
draftMode().catch(logReason)
connection().catch(logReason)... | ute is
synchronously dynamic (which this one is by rendering a Math.random()
value)
</p>
<p>
<TriggerSyncDynamic />
</p>
</>
)
}
function logReason(reason: any) {
console.log('Reason:', reason)
}
async fu | at these promises eventually reject even when the ro | {
"filepath": "test/e2e/app-dir/cache-components-request-apis/fixtures/reject-hanging-promises-dynamic/app/[slug]/page.tsx",
"language": "tsx",
"file_size": 993,
"cut_index": 582,
"middle_length": 52
} |
ployment: true,
})
if (skipped) {
return
}
it('should generate types for next/link', async () => {
await retry(async () => {
const dts = await next.readFile(`${next.distDir}/types/link.d.ts`)
expect(dts).toContain(`declare module 'next/link'`)
})
})
it('should include handler rout... | await next.stop()
await next.patchFile(
'app/valid-links.tsx',
`
import Link from 'next/link'
export default function ValidLinks() {
return (
<div>
<Link href="/">Simple Route</Link>
<Link href="/dashboard">Simple | Ensure the app route handler at app/api-test/route.ts ("/api-test") is present
expect(dts).toContain('`/api-test`')
})
})
if (isNextStart) {
it('should pass type checking with valid routes', async () => {
| {
"filepath": "test/e2e/app-dir/typed-routes/typed-links.test.ts",
"language": "typescript",
"file_size": 5128,
"cut_index": 716,
"middle_length": 229
} |
tils'
const expectedDts = `
type AppRoutes = "/" | "/_shop/[[...category]]" | "/dashboard" | "/dashboard/settings" | "/docs/[...slug]" | "/gallery/photo/[id]" | "/project/[slug]"
type AppRouteHandlerRoutes = "/api-test" | "/api/docs/[...slug]" | "/api/shop/[[...category]]" | "/api/users/[id]"
type PageRoutes = "/about... | dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should generate route types correctly', async () => {
// Route type generation happens after the "Ready" log fires; give it time.
await retry(async () => {
const | ]"
type Routes = AppRoutes | PageRoutes | LayoutRoutes | RedirectRoutes | RewriteRoutes | AppRouteHandlerRoutes
`
describe('typed-routes', () => {
const { next, isNextDev, isNextStart, skipped } = nextTestSetup({
files: __ | {
"filepath": "test/e2e/app-dir/typed-routes/typed-routes.test.ts",
"language": "typescript",
"file_size": 4545,
"cut_index": 614,
"middle_length": 229
} |
ect all CSS reachable from a page (inline <style> + linked .css). */
async function collectPageCss(
next: ReturnType<typeof nextTestSetup>['next'],
path: string
): Promise<string> {
const html = await (await next.fetch(path)).text()
let css = ''
// Inline <style> blocks
for (const m of html.matchAll(/<style... | tTestSetup({
files: __dirname,
dependencies: { lightningcss: '^1.23.0' },
// Chrome 123 supports light-dark() natively — using it here proves that
// the `include` flag forces transpilation regardless of browser support.
packa | [^"]*?)"[^>]*>/g)) {
const res = await next.fetch(m[1])
if (res.ok) css += await res.text()
}
return css
}
describe('experimental-lightningcss-features', () => {
describe('include', () => {
const { next } = nex | {
"filepath": "test/e2e/app-dir/experimental-lightningcss-features/experimental-lightningcss-features.test.ts",
"language": "typescript",
"file_size": 2936,
"cut_index": 563,
"middle_length": 229
} |
mport { nextTestSetup } from 'e2e-utils'
describe('unstable-rethrow', () => {
const { next, isNextStart } = nextTestSetup({
files: __dirname,
})
it('should correctly trigger the not found page as not found', async () => {
const browser = await next.browser('/not-found-page')
expect(await browser.ele... | liOutput).toContain('[test assertion]: checking error')
expect(next.cliOutput).not.toContain('[test assertion]: error leaked')
})
it('should correctly mark the dynamic page as dynamic', async () => {
expect(next.cliOutput).toContain('ƒ | browser = await next.browser('/cause')
expect(await browser.elementByCss('body').text()).toContain('hello world')
})
if (isNextStart) {
it('should not log any errors at build time', async () => {
expect(next.c | {
"filepath": "test/e2e/app-dir/unstable-rethrow/unstable-rethrow.test.ts",
"language": "typescript",
"file_size": 1031,
"cut_index": 513,
"middle_length": 229
} |
from 'e2e-utils'
describe('use-params', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should work for single dynamic param', async () => {
const $ = await next.render$('/a/b')
expect($('#param-id').text()).toBe('a')
})
it('should work for nested dynamic params', async () => {... | next.browser('/')
expect(
await browser
.elementByCss('#to-a')
.click()
.waitForElementByCss('#param-id')
.text()
).toBe('a')
})
it('should work for nested dynamic params client navigating', async () => { | const $ = await next.render$('/a/b/c/d/e/f/g')
expect($('#params').text()).toBe('["a","b","c","d","e","f","g"]')
})
it('should work for single dynamic param client navigating', async () => {
const browser = await | {
"filepath": "test/e2e/app-dir/use-params/use-params.test.ts",
"language": "typescript",
"file_size": 1893,
"cut_index": 537,
"middle_length": 229
} |
eRouterAct } from 'router-act'
describe('prefetch={true} with instant route', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
it('is skipped', () => {})
return
}
it('does not include dynamic content in the prefetch when the target route has instant', asy... | / but NOT dynamic content.
await act(async () => {
const linkToggle = await browser.elementByCss(
'input[data-link-accordion="/target-page"]'
)
await linkToggle.click()
}, [
{
includes: 'Cached content',
| ct(page)
// Reveal the link to trigger a prefetch. Even though the Link has
// prefetch={true}, the route has unstable_instant defined, so the
// prefetch should be downgraded — it should include cached content
/ | {
"filepath": "test/e2e/app-dir/prefetch-true-instant/prefetch-true-instant.test.ts",
"language": "typescript",
"file_size": 4046,
"cut_index": 614,
"middle_length": 229
} |
Suspense } from 'react'
import { cookies } from 'next/headers'
import { connection } from 'next/server'
export const unstable_instant = {
unstable_samples: [{ cookies: [{ name: 'test', value: null }] }],
}
export const unstable_prefetch = 'force-runtime'
export default async function Page() {
return (
<main>... | cookieStore = await cookies()
const value = cookieStore.get('test')?.value ?? 'default'
return <div id="cached-content">Cached content: {value}</div>
}
async function Dynamic() {
await connection()
return <div id="dynamic-content">Dynamic content< | </main>
)
}
async function Cached() {
const | {
"filepath": "test/e2e/app-dir/prefetch-true-instant/app/target-page/page.tsx",
"language": "tsx",
"file_size": 836,
"cut_index": 520,
"middle_length": 52
} |
} from 'react'
import { cookies } from 'next/headers'
import { connection } from 'next/server'
// No instant config on the page — only the layout has it.
export default async function Page() {
return (
<main>
<Suspense fallback={<div>Loading cached...</div>}>
<CachedWrapper />
</Suspense>
... |
return <Cached value={value} />
}
async function Cached({ value }: { value: string }) {
'use cache'
return <div id="cached-content">Cached content: {value}</div>
}
async function Dynamic() {
await connection()
return <div id="dynamic-content"> | value = cookieStore.get('test')?.value ?? 'default' | {
"filepath": "test/e2e/app-dir/prefetch-true-instant/app/layout-instant/page.tsx",
"language": "tsx",
"file_size": 863,
"cut_index": 529,
"middle_length": 52
} |
getTitle,
retry,
} from 'next-test-utils'
describe('app dir - metadata navigation', () => {
const { next } = nextTestSetup({
files: __dirname,
})
describe('navigation', () => {
it('should render root not-found with default metadata', async () => {
const $ = await next.render$('/does-not-exist'... | ).toBe('Root not found')
})
it('should support notFound in generateMetadata', async () => {
const res = await next.fetch('/async/not-found')
// metadata is suspended in SSR, it won't affect the response status
expect(res.status). | ame', 'content', {
viewport: 'width=device-width, initial-scale=1',
robots: 'noindex',
// not found metadata
description: 'Root not found description',
})
expect(await $('title').text() | {
"filepath": "test/e2e/app-dir/metadata-navigation/metadata-navigation.test.ts",
"language": "typescript",
"file_size": 5009,
"cut_index": 614,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('prefetching-not-found', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should correctly navigate to/from a global 404 page when following links with prefetch=auto', async () => {
let browser = await next.b... | s('h1').text()).toBe('Home Page')
})
// Assert the same behavior, but starting at the not found page. This is to
// ensure that when we seed the prefetch cache, we don't have any cache
// collisions that would cause the not-found page to r | it browser.elementByCss('body').text()).toContain(
'This page could not be found.'
)
})
await browser.elementByCss("[href='/']").click()
await retry(async () => {
expect(await browser.elementByCs | {
"filepath": "test/e2e/app-dir/prefetching-not-found/prefetching-not-found.test.ts",
"language": "typescript",
"file_size": 1399,
"cut_index": 524,
"middle_length": 229
} |
'app dir - not found with default 404 page', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should error on client notFound from root layout in browser', async () => {
const browser = await next.browser('/')... | `)
}
})
it('should render default 404 with root layout for non-existent page', async () => {
const browser = await next.browser('/non-existent')
await browser.waitForElementByCss('.next-error-h1')
expect(await browser.elementByCss | {
"code": "E192",
"description": "notFound() is not allowed to use in root layout",
"environmentLabel": null,
"label": "Runtime Error",
"source": null,
"stack": [],
}
| {
"filepath": "test/e2e/app-dir/not-found-default/index.test.ts",
"language": "typescript",
"file_size": 3281,
"cut_index": 614,
"middle_length": 229
} |
import { nextTestSetup } from 'e2e-utils'
// Skip as Turbopack doesn't support the `!=!` Webpack syntax
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'app dir - rsc webpack loader',
() => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
// TODO: Temporaril... | loader rules', async () => {
const browser = await next.browser('/loader-rule')
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('#red')).color`
)
).toBe('rgb(255, 0, 0)')
})
}
) | atest',
},
resolutions: {
'@babel/core': '7.22.18',
'@babel/parser': '7.22.16',
'@babel/types': '7.22.17',
'@babel/traverse': '7.22.18',
},
})
it('should support webpack | {
"filepath": "test/e2e/app-dir/rsc-webpack-loader/rsc-webpack-loader.test.ts",
"language": "typescript",
"file_size": 998,
"cut_index": 512,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
describe('interception-routes-root-catchall', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should support having a root catch-all and a catch-all in a parallel route group', async () => {
const browser = await nex... | => browser.elementById('children').text(),
/Regular Item Page. Id: 1/
)
})
it('should handle non-intercepted catch-all pages', async () => {
const browser = await next.browser('/')
// there's no explicit page for /foobar. This will | .text(),
/Intercepted Modal Page. Id: 1/
)
await browser.refresh()
// no longer intercepted, using the page
await check(() => browser.elementById('slot').text(), /default @modal/)
await check(
() | {
"filepath": "test/e2e/app-dir/interception-routes-root-catchall/interception-routes-root-catchall.test.ts",
"language": "typescript",
"file_size": 1291,
"cut_index": 524,
"middle_length": 229
} |
{ nextTestSetup } from 'e2e-utils'
describe('transition-indicator', () => {
const { next } = nextTestSetup({
files: __dirname,
})
// TODO: Find testing pattern to assert that the browser's pending indicator is shown
// These tests are just instructions for manual testing
it('displays while loading con... | tByCss('a[href="/slow-with-fallback"]').click()
// fallback is shown, no pending indicator in browser tab
})
it('displays during any Transition that does not commit a pending state', async () => {
const browser = await next.browser('/')
| browser tab while loading
// Gets stuck due to usage of history.pushState
})
it('does not display while loading content with fallback', async () => {
const browser = await next.browser('/')
await browser.elemen | {
"filepath": "test/e2e/app-dir/transition-indicator/transition-indicator.test.ts",
"language": "typescript",
"file_size": 1164,
"cut_index": 518,
"middle_length": 229
} |
{ next, skipped, isTurbopack } = nextTestSetup({
files: __dirname,
skipDeployment: true,
dependencies: {
pino: '9.6.0',
jspdf: '4.2.1',
},
})
if (skipped) {
return
}
// These tests are Turbopack-specific since they rely on Turbopack's worker bundling
if (!isTurbopack) {
i... | , import.meta.url)', async () => {
const res = await next.fetch('/api/url-worker-test')
const data = await res.json()
expect(res.status).toBe(200)
expect(data.success).toBe(true)
expect(data.message).toBe('pong from url worker')
})
| imple-worker-test')
const data = await res.json()
expect(res.status).toBe(200)
expect(data.success).toBe(true)
expect(data.message).toBe('pong from simple worker')
})
it('should handle worker with new URL(... | {
"filepath": "test/e2e/app-dir/node-worker-threads/node-worker-threads.test.ts",
"language": "typescript",
"file_size": 4214,
"cut_index": 614,
"middle_length": 229
} |
read, parentPort } from 'node:worker_threads'
import { NextResponse } from 'next/server'
// This file tests self-referencing worker threads using __filename
// This pattern is used by libraries like @duckdb/duckdb-wasm
if (!isMainThread && parentPort) {
// Worker thread - handle messages
parentPort.on('message', ... | try {
// Create a worker using __filename - this is the pattern that triggers the cycle bug
const worker = new Worker(__filename)
const message = await new Promise<string>((resolve, reject) => {
const timeout = setTimeout(() => {
| nother worker
return NextResponse.json({ error: 'Already in worker' }, { status: 500 })
}
// Log __filename for debugging
console.log('__filename:', __filename)
console.log('typeof __filename:', typeof __filename)
| {
"filepath": "test/e2e/app-dir/node-worker-threads/app/api/worker-test/route.ts",
"language": "typescript",
"file_size": 1712,
"cut_index": 537,
"middle_length": 229
} |
mport { Worker } from 'node:worker_threads'
import { NextResponse } from 'next/server'
export async function GET() {
try {
const worker = new Worker(
new URL('../../worker-dir/url-worker.ts', import.meta.url)
)
const message = await new Promise<string>((resolve, reject) => {
const timeout = ... | de ${code}`))
}
})
worker.postMessage('ping')
})
await worker.terminate()
return NextResponse.json({ success: true, message })
} catch (error) {
return NextResponse.json(
{ success: false, error: String(error) | ('error', (err) => {
clearTimeout(timeout)
reject(err)
})
worker.on('exit', (code) => {
if (code !== 0) {
clearTimeout(timeout)
reject(new Error(`Worker stopped with exit co | {
"filepath": "test/e2e/app-dir/node-worker-threads/app/api/url-worker-test/route.ts",
"language": "typescript",
"file_size": 1036,
"cut_index": 513,
"middle_length": 229
} |
ditional network requests.
*/
async function isAccordionClosed(
browser: Playwright,
href: string
): Promise<boolean> {
const selector = `[data-testid="link-accordion"][data-href="${href}"]`
// Check if the button is already open
return await browser.hasElementByCss(`${selector} button`)
}... | lick the "Open" button, it may already be open, so we don't need to
// click it again.
if (await isAccordionClosed(browser, href)) {
const button = await browser.elementByCss(`${selector} button`)
await button.click()
}
// Clic | ) {
const selector = `[data-testid="link-accordion"][data-href="${href}"]`
// Find and scroll to accordion
const accordion = await browser.elementByCss(selector)
await accordion.scrollIntoViewIfNeeded()
// C | {
"filepath": "test/e2e/app-dir/interception-dynamic-segment/interception-dynamic-segment.test.ts",
"language": "typescript",
"file_size": 14664,
"cut_index": 921,
"middle_length": 229
} |
rt default function Page() {
return (
<div id="children">
<section>
<h2>✅ Should Work WITHOUT default.tsx</h2>
<div>
<h3>Test Case 1a: Simple page (no parallel routes)</h3>
<LinkAccordion href="/simple-page" />
<p>
Interception route with just a pag... | outes/deeper" />
<p>No @parallel routes exist, so no implicit layout created.</p>
</div>
<div>
<h3>Test Case 3: Has both @sidebar AND page.tsx</h3>
<LinkAccordion href="/has-both" />
<p>
| Interception route has page.tsx at root level. No children slot
exists.
</p>
</div>
<div>
<h3>Test Case 2: No parallel routes</h3>
<LinkAccordion href="/no-parallel-r | {
"filepath": "test/e2e/app-dir/interception-dynamic-segment/app/page.tsx",
"language": "tsx",
"file_size": 2443,
"cut_index": 563,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.