prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
extTestSetupActionTreeShaking, getActionsRoutesStateByRuntime, } from '../_testing/utils' // TODO: revisit when we have a better side-effect free transform approach for server action ;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)( 'actions-tree-shaking - shared-module-actions', () => { const { n...
age": [ "app/client/actions.js#sharedClientLayerAction", ], "app/server/one/page": [ "app/server/actions.js#sharedServerLayerAction", "app/server/actions.js#unusedServerLayerAction1", "app/serve
ionsRoutesStateByRuntime(next) expect(actionsRoutesState).toMatchInlineSnapshot(` { "app/client/one/page": [ "app/client/actions.js#sharedClientLayerAction", ], "app/client/two/p
{ "filepath": "test/production/app-dir/actions-tree-shaking/shared-module-actions/shared-module-actions.test.ts", "language": "typescript", "file_size": 1320, "cut_index": 524, "middle_length": 229 }
ionsRoutesStateByRuntime, } from '../_testing/utils' import { retry } from 'next-test-utils' // TODO: revisit when we have a better side-effect free transform approach for server action ;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)( 'actions-tree-shaking - reexport', () => { const { next } = next...
"app/named-reexport/server/page": [ "app/named-reexport/server/actions.js#sharedServerLayerAction", "app/named-reexport/server/actions.js#unusedServerLayerAction1", "app/named-reexport/server/actions.js#unusedServerLayerAc
sStateByRuntime(next) expect(actionsRoutesState).toMatchInlineSnapshot(` { "app/named-reexport/client/page": [ "app/named-reexport/client/actions.js#sharedClientLayerAction", ],
{ "filepath": "test/production/app-dir/actions-tree-shaking/reexport/reexport.test.ts", "language": "typescript", "file_size": 3018, "cut_index": 563, "middle_length": 229 }
2e-utils' // This is from 'next/dist/build/webpack/plugins/flight-client-entry-plugin', but unfortunately // Typescript breaks when importing it directly. type Actions = { [actionId: string]: { exportedName?: string filename?: string workers: { [name: string]: { moduleId: string | number ...
TEST_EDGE, }) if (process.env.TEST_EDGE) { beforeAll(async () => { const layoutContent = await result.next.readFile('app/layout.js') await result.next.patchFile( 'app/layout.js', layoutContent + `\nexport const runtime
wait next.readFile('.next/server/server-reference-manifest.json') ) return manifest[runtime] } export function nextTestSetupActionTreeShaking(opts) { let result = nextTestSetup({ ...opts, skipStart: !!process.env.
{ "filepath": "test/production/app-dir/actions-tree-shaking/_testing/utils.ts", "language": "typescript", "file_size": 2197, "cut_index": 563, "middle_length": 229 }
t { nextTestSetup } from 'e2e-utils' describe('app-dir - metadata-revalidate', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should contain the routes in prerender manifest', async () => { const manifestContent = await next.readFile('.next/prerender-manifest.json') const prerende...
es['/manifest.webmanifest'].initialRevalidateSeconds ).toBe(5) expect( prerenderManifest.routes['/robots.txt'].initialRevalidateSeconds ).toBe(5) expect( prerenderManifest.routes['/sitemap.xml'].initialRevalidateSeconds ).to
rManifest.rout
{ "filepath": "test/production/app-dir/metadata-revalidate/metadata-revalidate.test.ts", "language": "typescript", "file_size": 801, "cut_index": 517, "middle_length": 14 }
from 'e2e-utils' import { createMultiDomMatcher } from 'next-test-utils' describe('metadata spread types', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should allow spreading resolved parent metadata into child metadata', async () => { const browser = await next.browser('/') con...
name': 'Example Site', }) // Verify twitter metadata is correctly merged await matchMultiDom('meta', 'name', 'content', { 'twitter:title': 'Page Twitter title', 'twitter:description': 'Page Twitter description', 'twitter:site
nGraph metadata is correctly merged await matchMultiDom('meta', 'property', 'content', { 'og:title': 'Page OG title', 'og:description': 'Page OG description', 'og:url': 'https://example.com', 'og:site_
{ "filepath": "test/production/app-dir/metadata-spread-types/metadata-spread-types.test.ts", "language": "typescript", "file_size": 1532, "cut_index": 537, "middle_length": 229 }
('generate-static-params-errors', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true, }) let cliOutputLength: number afterEach(async () => { await next.stop() }) const buildRoute = async (routePath: string) => { cliOutputLength = next.cliOutput.length await nex...
ted because `generateStaticParams` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context' ) }) it('should error when headers() is called inside generateStaticParams', async () => {
Params', async () => { await buildRoute('app/[lang]/cookies/[slug]/page.tsx') expect(getCliOutput()).toContain( 'Error: Route /[lang]/cookies/[slug] used `cookies()` inside `generateStaticParams`. This is not suppor
{ "filepath": "test/production/app-dir/generate-static-params-errors/generate-static-params-errors.test.ts", "language": "typescript", "file_size": 2567, "cut_index": 563, "middle_length": 229 }
ls' import { existsSync } from 'fs' import path from 'path' describe('post-build', () => { if (!isNextStart) { it('skipped for non-start mode', () => {}) return } const { next, isTurbopack, skipped } = nextTestSetup({ files: __dirname, skipStart: true, env: { NEXT_USE_POST_BUILD: '1', ...
t', 'cache', 'turbopack') expect(existsSync(cachePath)).toBe(true) // Run `next internal post-build` to compact the database const result = await next.runCommand(['internal', 'post-build']) if (result.exitCode !== 0) { console.log('
return } // Build with NEXT_USE_POST_BUILD=1 which skips compaction during build const buildResult = await next.build() expect(buildResult.exitCode).toBe(0) const cachePath = path.join(next.testDir, '.nex
{ "filepath": "test/production/app-dir/post-build/post-build.test.ts", "language": "typescript", "file_size": 2075, "cut_index": 563, "middle_length": 229 }
t { ImageResponse } from 'next/og' // Image metadata export const alt = 'About Acme' export const size = { width: 1200, height: 630, } export const contentType = 'image/png' // Image generation export default async function Image() { return new ImageResponse( ( // ImageResponse JSX element <div...
nt: 'center', }} > About Acme </div> ), // ImageResponse options { // For convenience, we can re-use the exported opengraph-image // size config to also set the ImageResponse's width and height. ...
justifyConte
{ "filepath": "test/production/app-dir/metadata-static/app/opengraph-image.tsx", "language": "tsx", "file_size": 805, "cut_index": 517, "middle_length": 14 }
import fs from 'fs' describe('upload-trace', () => { if (!isNextStart) { it('skipped for non-start mode', () => {}) return } const { next, isTurbopack, skipped } = nextTestSetup({ files: __dirname, skipStart: true, skipDeployment: true, buildCommand: 'pnpm next build --experimental-cpu-...
les.filter((f: string) => f.endsWith('.cpuprofile') ) expect(cpuProfiles.length).toBeGreaterThan(0) if (isTurbopack) { expect(allFiles).toContain('trace-turbopack') } const uploadableFiles = allFiles.filter( (f: stri
ct(buildResult.exitCode).toBe(0) const profilesDir = path.join(next.testDir, '.next-profiles') expect(fs.existsSync(profilesDir)).toBe(true) const allFiles = fs.readdirSync(profilesDir) const cpuProfiles = allFi
{ "filepath": "test/production/app-dir/upload-trace/upload-trace.test.ts", "language": "typescript", "file_size": 4112, "cut_index": 614, "middle_length": 229 }
ort { nextTestSetup } from 'e2e-utils' import path from 'path' ;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)( 'app dir - typed-routes-with-webpack-worker', () => { describe('good-routes', () => { const { next } = nextTestSetup({ files: path.join(__dirname, 'good-routes'), ski...
oin(__dirname, 'bad-routes'), skipStart: true, }) it('builds with valid errors', async () => { const { exitCode, cliOutput } = await next.build() expect(cliOutput).toContain('webpackBuildWorker') expect(exitCod
ldWorker') expect(exitCode).toBe(0) expect(cliOutput).not.toContain(`"/" is not an existing route.`) }) }) describe('bad-routes', () => { const { next } = nextTestSetup({ files: path.j
{ "filepath": "test/production/app-dir/typed-routes-with-webpack-worker/typed-routes-with-webpack-worker.test.ts", "language": "typescript", "file_size": 1114, "cut_index": 515, "middle_length": 229 }
from 'e2e-utils' describe('use-cache-non-deterministic-args', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should warn about non-deterministic cache args during on-demand prerender', async () => { const outputIndex = next.cliOutput.length await next.browser('/unknown') cons...
tchDone = new Promise<void>((resolve) => { onRuntimePrefetchDone = resolve }) // Visit /with-runtime-prefetch to render the Link. The link being visible // in the viewport triggers a runtime prefetch for the /known route. await next.
rerendering' ) }) it('should warn about non-deterministic cache args during runtime prefetch', async () => { const outputIndex = next.cliOutput.length let onRuntimePrefetchDone: () => void const runtimePrefe
{ "filepath": "test/production/app-dir/use-cache-non-deterministic-args/use-cache-non-deterministic-args.test.ts", "language": "typescript", "file_size": 1673, "cut_index": 537, "middle_length": 229 }
heSignal } from 'react' import { setTimeout } from 'timers/promises' import { cookies } from 'next/headers' export const unstable_prefetch = 'force-runtime' const callCounts = new Map<string, number>() function getNonDeterministicItems(slug: string) { // For testing purposes, this creates an artificial determinist...
ces a different cache // key that misses the RDC. const count = (callCounts.get(slug) ?? 0) + 1 callCounts.set(slug, count) return count === 1 ? ['b', 'a'] : ['a', 'b'] } async function getCachedValue(items: string[]) { 'use cache' await setTi
terministic order, and that array then being passed // as an argument to a cached function). // // Call 1 (prospective prerender) warms the RDC entry for ['b','a']. // Call 2+ (final prerender) uses ['a','b'], which produ
{ "filepath": "test/production/app-dir/use-cache-non-deterministic-args/app/[slug]/page.tsx", "language": "tsx", "file_size": 2619, "cut_index": 563, "middle_length": 229 }
artial-fallback', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should emit partial fallback metadata when infra can upgrade the shell', async () => { const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] = await next.readJSON('build-complete.json') const withGsp...
output.pathname !== '/with-gsp/[slug].segments/_tree.segment.rsc' ) const withoutGspPrerender = outputs.prerenders.find( (output) => output.pathname === '/without-gsp/[slug]' ) const withoutGspRouteTreePrerender = outputs.prerender
put.pathname === '/with-gsp/[slug].segments/_tree.segment.rsc' ) const withGspOtherSegmentPrerenders = outputs.prerenders.filter( (output) => output.pathname.startsWith('/with-gsp/[slug].segments/') &&
{ "filepath": "test/production/app-dir/adapter-partial-fallback/adapter-partial-fallback.test.ts", "language": "typescript", "file_size": 4914, "cut_index": 614, "middle_length": 229 }
serted-html', () => { const { next, isNextStart } = nextTestSetup({ files: __dirname, }) if (isNextStart) { it('should mark the route as ppr rendered', async () => { const prerenderManifest = JSON.parse( await next.readFile('.next/prerender-manifest.json') ) expect(prerenderMani...
:') }) it('should insert the html insertion into html body', async () => { const $ = await next.render$('/partial-resume') const output = next.cliOutput expect(output).toContain('testing-log-insertion:dynamic-data') expect($('head [da
expect(output).not.toContain('testing-log-insertion
{ "filepath": "test/production/app-dir/ppr-use-server-inserted-html/ppr-use-server-inserted-html.test.ts", "language": "typescript", "file_size": 980, "cut_index": 582, "middle_length": 52 }
('build-output-ssg-bailout', () => { if (process.env.__NEXT_CACHE_COMPONENTS === 'true') { it.skip('PPR is enabled, will throw instead of bailing out', () => {}) return } const { next } = nextTestSetup({ files: __dirname, skipStart: true, env: { __NEXT_PRIVATE_DETERMINISTIC_BUILD_OUTPUT...
t(next.cliOutput).toContain( 'Error: Static generation failed due to dynamic usage on /ssg-bailout/2, reason: `await searchParams`, `searchParams.then`, or similar' ) expect(next.cliOutput).toContain( 'Error: Static generation failed du
s for SSG bailout', async () => { expect(next.cliOutput).toContain( 'Error: Static generation failed due to dynamic usage on /ssg-bailout/1, reason: `await searchParams`, `searchParams.then`, or similar' ) expec
{ "filepath": "test/production/app-dir/build-output-ssg-bailout/build-output-ssg-bailout.test.ts", "language": "typescript", "file_size": 2541, "cut_index": 563, "middle_length": 229 }
from 'e2e-utils' import { retry } from 'next-test-utils' describe('empty-generate-static-params', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipStart: true, }) if (skipped) return // If we're not using cache components, there shouldn't be any build errors! if (process.env....
by a HIT after being generated', async () => { const firstResponse = await next.fetch('/foo') expect(firstResponse.status).toBe(200) // With PPR enabled, the initial request doesn't send back a cache header const isPPREnabled = pro
) => { const isPPREnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true' expect(next.cliOutput).toContain(`${isPPREnabled ? '◐' : '●'} /[slug]`) }) it('should be a cache miss on the initial render followed
{ "filepath": "test/production/app-dir/empty-generate-static-params/empty-generate-static-params.test.ts", "language": "typescript", "file_size": 1698, "cut_index": 537, "middle_length": 229 }
from 'e2e-utils' describe('app edge middleware', () => { describe('without node.js modules', () => { const { next } = nextTestSetup({ files: { 'app/page.js': ` export default function Page() { return <p>hello world</p> } `, 'app/layout.js': ` ...
, }) it('should not have any errors about using Node.js modules if not present in middleware', async () => { expect(next.cliOutput).not.toContain('node-module-in-edge-runtime') }) }) describe('with node.js modules', () => { const
) } `, 'middleware.js': ` import { NextResponse } from 'next/server'; export async function middleware() { return NextResponse.next() } `, }
{ "filepath": "test/production/app-dir/app-edge-middleware/app-edge-middleware.test.ts", "language": "typescript", "file_size": 1879, "cut_index": 537, "middle_length": 229 }
import type { ClientReferenceManifest } from 'next/dist/build/webpack/plugins/flight-manifest-plugin' describe('route-handler-manifest-size', () => { const { next, isNextStart, skipped } = nextTestSetup({ files: __dirname, }) if (skipped) return /** * Gets the module paths from clientModules */ ...
tain client components from the page const hasButton = modulePaths.some((p) => p.includes('Button')) const hasModal = modulePaths.some((p) => p.includes('Modal')) const hasDropdown = modulePaths.some((p) => p.includes('Dropdown'))
ponents in pure route handler manifest', () => { const manifest = getClientReferenceManifest(next, '/api/hello/route') const modulePaths = getClientModulePaths(manifest) // The pure route handler should NOT con
{ "filepath": "test/production/app-dir/route-handler-manifest-size/route-handler-manifest-size.test.ts", "language": "typescript", "file_size": 3695, "cut_index": 614, "middle_length": 229 }
export function Dropdown({ items, }: { items: { label: string; value: string }[] }) { const [isOpen, setIsOpen] = useState(false) const [selected, setSelected] = useState<string | null>(null) return ( <div className="relative"> <button onClick={() => setIsOpen(!isOpen)}> {selected || 'Sele...
setSelected(item.label) setIsOpen(false) }} className="px-4 py-2 hover:bg-gray-100 cursor-pointer" > {item.label} </li> ))} </ul> )} </div> )
.value} onClick={() => {
{ "filepath": "test/production/app-dir/route-handler-manifest-size/app/components/Dropdown.tsx", "language": "tsx", "file_size": 870, "cut_index": 559, "middle_length": 52 }
{ waitFor, retry } from 'next-test-utils' import { nextTestSetup } from 'e2e-utils' describe('app-fetch-deduping', () => { const { next, isTurbopack } = nextTestSetup({ files: __dirname }) const itSkipTurbopack = isTurbopack ? it.skip : it // This solution consistently works in Webpack but is flaky in Turbopa...
await browser.refresh() currentValue = await browser.elementById('random').text() expect(currentValue).toBe(initialRandom) }) // wait for the revalidation period await waitFor(3000) await retry(async () => {
it next.browser('/') let currentValue: string | undefined await retry(async () => { const initialRandom = await browser.elementById('random').text() expect(initialRandom).toMatch(/^0\.\d+$/)
{ "filepath": "test/production/app-dir/app-fetch-patching/app-fetch-patching.test.ts", "language": "typescript", "file_size": 1171, "cut_index": 518, "middle_length": 229 }
tTestSetup } from 'e2e-utils' describe('Re-export all exports from page is disallowed', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true, dependencies: { 'find-up': '4.1.0', }, }) it('shows error when a page re-export all exports', async () => { const { cliOut...
}) it('builds without error when no `export * from "..."` is used in pages', async () => { const origContent = await next.readFile('pages/contact.js') const newContent = origContent.replace(/^export \*/gm, '// export *') await next.patchFile
"Using `export * from '...'` in a page is disallowed. Please use `export { default } from '...'` instead." ) expect(cliOutput).toContain( 'Read more: https://nextjs.org/docs/messages/export-all-in-page' )
{ "filepath": "test/production/re-export-all-exports-from-page-disallowed/re-export-all-exports-from-page-disallowed.test.ts", "language": "typescript", "file_size": 1291, "cut_index": 524, "middle_length": 229 }
path from 'path' import { FileRef, nextTestSetup } from 'e2e-utils' import { renderViaHTTP } from 'next-test-utils' describe('TypeScript basic', () => { const { next } = nextTestSetup({ files: new FileRef(path.join(__dirname, 'app')), dependencies: { '@next/bundle-analyzer': 'canary', typescript...
llo world') }) // Turbopack doesn't support Babel built-in. ;(process.env.IS_TURBOPACK_TEST ? it.skip : it)( 'should work with babel', async () => { await next.stop() await next.patchFile( '.babelrc', JSON.stringi
t(next.cliOutput).not.toContain( 'How would you like to configure ESLint' ) }) it('have built and started correctly', async () => { const html = await renderViaHTTP(next.url, '/') expect(html).toContain('he
{ "filepath": "test/production/typescript-basic/index.test.ts", "language": "typescript", "file_size": 1240, "cut_index": 518, "middle_length": 229 }
as childProcess from 'child_process' import path from 'path' import { FileRef, nextTestSetup } from 'e2e-utils' describe('typechecking', () => { const { next } = nextTestSetup({ files: new FileRef(path.join(__dirname, 'typechecking')), skipStart: true, }) it('should typecheck', async () => { const ...
the format barely useable. // Printing it as a last resort in case it's not reproducible locally. // Best to NEXT_TEST_SKIP_CLEANUP=1 this test and run the command in the app localy. throw new Error('Typecheck failed: \n' + stdout) }
tus !== 0) { // Piped output is incomplete and
{ "filepath": "test/production/typescript-basic/typechecking.test.ts", "language": "typescript", "file_size": 837, "cut_index": 520, "middle_length": 52 }
rt { useRouter } from 'next/router' import Link from 'next/link' import { type PageConfig } from 'next' // eslint-disable-next-line @typescript-eslint/no-unused-vars import { StyleRegistry, createStyleRegistry } from 'styled-jsx' export const config: PageConfig = {} export default function Page() { // eslint-disabl...
to /another </Link> <Link href="/another" onClick={(e) => { /** @ts-expect-error - foo does not exist on React.MouseEvent */ console.log(e.foo) }} > to /another </Link> </>
onsole.log(e.currentTarget) }} >
{ "filepath": "test/production/typescript-basic/app/pages/index.tsx", "language": "tsx", "file_size": 830, "cut_index": 516, "middle_length": 52 }
te } from 'next' // eslint-disable-next-line @typescript-eslint/no-unused-expressions ;() => { ;({ background_color: undefined, categories: undefined, description: undefined, dir: undefined, display: undefined, display_override: undefined, file_handlers: undefined, icons: undefined, ...
}) satisfies MetadataRoute.Manifest ;({ icons: [ { src: '', type: undefined, sizes: undefined, purpose: undefined, }, ], related_applications: [ { platform: '', url: '',
ed, related_applications: undefined, scope: undefined, screenshots: undefined, share_target: undefined, short_name: undefined, shortcuts: undefined, start_url: undefined, theme_color: undefined,
{ "filepath": "test/production/typescript-basic/typechecking/metadata/manifest.ts", "language": "typescript", "file_size": 1680, "cut_index": 537, "middle_length": 229 }
incremental-cache/file-system-cache') /** * A FileSystemCache variant that lets a test simulate the passage of time by * shifting the `lastModified` timestamp of a cached entry into the past. The * offset is controlled per-request via the `x-test-cache-age-offset-ms` header * so tests can skip over `expire` window...
t result = await super.get(key, ctx) const offsetHeader = this.requestHeaders?.['x-test-cache-age-offset-ms'] const offsetMs = typeof offsetHeader === 'string' ? Number(offsetHeader) : 0 if (result && offsetMs > 0 && !ctx.fetchCache) {
requestHeaders } async get(key, ctx) { cons
{ "filepath": "test/production/app-dir/use-cache-expire/incremental-cache-handler.js", "language": "javascript", "file_size": 988, "cut_index": 582, "middle_length": 52 }
m 'next/cache' import { connection } from 'next/server' import { Suspense } from 'react' async function getValue() { 'use cache' cacheLife({ revalidate: 60, expire: 300 }) return new Date().toISOString() } export function generateStaticParams() { return [{ id: 'known' }] } export default async function Page(...
ms} /> </Suspense> </> ) } async function DynamicPart({ params }: { params: Promise<{ id: string }> }) { const { id } = await params await connection() return ( <p id="dynamic"> {id} - {new Date().toISOString()} </p> ) }
t params={para
{ "filepath": "test/production/app-dir/use-cache-expire/app/partially-static/[id]/page.tsx", "language": "tsx", "file_size": 806, "cut_index": 536, "middle_length": 14 }
{ nextTestSetup, type NextInstance } from 'e2e-utils' async function getServerActionManifestNodeKeys(next: NextInstance) { const manifest = await next.readJSON( '.next/server/server-reference-manifest.json' ) return Object.keys(manifest.node) } describe('app-dir - server-action-period-hash', () => { cons...
e different manifest between two builds with period hash', async () => { await next.build() const firstActionIds = await getServerActionManifestNodeKeys(next) await next.remove('.next') // dismiss cache await next.build() const second
stActionIds = await getServerActionManifestNodeKeys(next) await next.build() const secondActionIds = await getServerActionManifestNodeKeys(next) expect(firstActionIds).toEqual(secondActionIds) }) it('should hav
{ "filepath": "test/production/app-dir/server-action-period-hash/server-action-period-hash.test.ts", "language": "typescript", "file_size": 1124, "cut_index": 518, "middle_length": 229 }
nextTestSetup } from 'e2e-utils' import { generatePNG } from '../generate-image' describe('app-dir - metadata-img-too-large twitter-image', () => { const { next, isTurbopack } = nextTestSetup({ files: __dirname, skipStart: true, }) const pngFile = generatePNG(5) it('should throw when twitter-image f...
ier, so the prefix is slightly different. /File size for Twitter image "\[project\]\/app\/twitter-image\.png" exceeds 5MB/ : /Error: File size for Twitter image ".*\/app\/twitter-image\.png" exceeds 5MB/ expect(next.cliOutput).toMatch(re
s simplified as [project]/.... It's also thrown earl
{ "filepath": "test/production/app-dir/metadata-img-too-large/twitter-image/index.test.ts", "language": "typescript", "file_size": 841, "cut_index": 520, "middle_length": 52 }
t path from 'path' import { nextTestSetup } from 'e2e-utils' function collectJsFiles(dir: string): string[] { if (!fs.existsSync(dir)) return [] return fs .readdirSync(dir, { recursive: true, encoding: 'utf8' }) .flatMap((entry) => { const full = path.join(dir, entry) return entry.endsWith('.js...
next.testDir, '.next/static') const jsFiles = collectJsFiles(staticDir) expect(jsFiles.length).toBeGreaterThan(0) const allContent = jsFiles .map((f) => fs.readFileSync(f, 'utf8')) .join('\n') // Custom
}) ;(isNextDeploy || !isTurbopack ? describe.skip : describe)( 'chunk output', () => { it('uses the custom global name and drops the default TURBOPACK global', async () => { const staticDir = path.join(
{ "filepath": "test/production/app-dir/turbopack-chunk-loading-global/turbopack-chunk-loading-global.test.ts", "language": "typescript", "file_size": 1974, "cut_index": 537, "middle_length": 229 }
join } from 'path' describe('NEXT_HASH_SALT', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true, }) /** Build with the given salt and return { chunks, images, css } filename lists. */ async function buildWithSalt(salt: string) { await next.clean() await next.build({ en...
salt-b. let saltAFirst: Awaited<ReturnType<typeof buildWithSalt>> let saltASecond: Awaited<ReturnType<typeof buildWithSalt>> let saltB: Awaited<ReturnType<typeof buildWithSalt>> beforeAll( async () => { saltAFirst = await buildWithSalt('
s') ) const images = files.filter((f) => f.endsWith('.png')) const css = files.filter((f) => f.endsWith('.css')) return { chunks, images, css } } // Three builds: salt-a (twice for reproducibility check) and
{ "filepath": "test/production/app-dir/hash-salt/hash-salt.test.ts", "language": "typescript", "file_size": 4930, "cut_index": 614, "middle_length": 229 }
ypto from 'crypto' function generateMD5(text: string) { const hash = crypto.createHash('md5') hash.update(text) return hash.digest('hex') } describe('app dir - metadata static routes cache', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true, }) it('should generate differe...
await next.fetch(opengraphImageUrl) ).text() const opengraphImageMd5 = generateMD5(opengraphImageBody) await next.stop() // Update favicon and opengraph image const newFaviconContent = await next.readFileBuffer('app/favicon.new.ico')
nst faviconBody = await (await next.fetch(faviconUrl)).text() const faviconMd5 = generateMD5(faviconBody) const opengraphImageUrl = $('meta[property="og:image"]').attr('href') const opengraphImageBody = await (
{ "filepath": "test/production/app-dir/metadata-static-route-cache/metadata-static-route-cache.test.ts", "language": "typescript", "file_size": 2064, "cut_index": 563, "middle_length": 229 }
oDateRegExp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/ describe.each(['NEXT_DEPLOYMENT_ID', 'BUILD_ID', 'default'])( 'use-cache-cross-deployment with %s', (envKey) => { const { next, skipped } = nextTestSetup({ files: __dirname, disableAutoSkewProtection: true, skipStart: true, }) ...
keyRoot: string, keyPrerender: string { let match = next.cliOutput.match( /CustomCacheHandler::get \["([A-Za-z0-9_-]+)","([0-9a-f]{2})+",\[\{"id":"dynamic-cache"\}\]\] \[\["_N_T_\/layout","_N_T_\/prerender\/layout","_N
ployments', async () => { async function execute(id: string) { await next.stop() if (envKey !== 'default') { next.env[envKey] = id } try { await next.start() let
{ "filepath": "test/production/app-dir/use-cache-cross-deployment/use-cache-cross-deployment.test.ts", "language": "typescript", "file_size": 2146, "cut_index": 563, "middle_length": 229 }
"▲ Next.js x.y.z (Turbopack) - Cache Components enabled - Experiments (use with caution): ✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`) ✓ cachedNavigations (enabled by \`__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS\`)" `)...
S\`)" `) } else { expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(` "▲ Next.js x.y.z (webpack) - Cache Components enabled - Experiments (use with caution):
- Experiments (use with caution): ✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`) ✓ cachedNavigations (enabled by \`__NEXT_EXPERIMENTAL_CACHED_NAVIGATION
{ "filepath": "test/production/app-dir/build-output-prerender/build-output-prerender.test.ts", "language": "typescript", "file_size": 25849, "cut_index": 1331, "middle_length": 229 }
e of graceful-degrade-error-bot.test.ts since we need to // restart with a new browser context for UA setting. Otherwise the browser context // will not be closed and reset properly. TODO: investigate why browser.close didn't help. import { nextTestSetup } from 'e2e-utils' import { deleteBrowserDynamicChunks } from '....
r('/chunk-loading-failed') const logs = await browser.log() const errors = logs .filter((x) => x.source === 'error') .map((x) => x.message) .join('\n') expect(errors).toMatch(/Failed to load resource./) // Should not sho
e beforeAll(async () => { await deleteBrowserDynamicChunks(next) }) it('should not degrade to graceful error when chunk loading fails in ssr for non-bot user agents', async () => { const browser = await next.browse
{ "filepath": "test/production/app-dir/graceful-degrade/graceful-degrade-non-bot.test.ts", "language": "typescript", "file_size": 1981, "cut_index": 537, "middle_length": 229 }
from 'e2e-utils' import { deleteBrowserDynamicChunks } from './delete-dynamic-chunk' describe('graceful-degrade', () => { const { next } = nextTestSetup({ files: __dirname, }) // Delete client chunks to simulate chunk loading failure beforeAll(async () => { await deleteBrowserDynamicChunks(next) }) ...
show the original content const originHtml = await browser.elementByCss('html') const originBody = await browser.elementByCss('body') expect(await originHtml.getAttribute('class')).toBe('layout-cls') expect(await originBody.getAttribute('cl
}) const logs = await browser.log() const errors = logs .filter((x) => x.source === 'error') .map((x) => x.message) .join('\n') expect(errors).toMatch(/Failed to load resource./) // Should
{ "filepath": "test/production/app-dir/graceful-degrade/graceful-degrade.test.ts", "language": "typescript", "file_size": 1760, "cut_index": 537, "middle_length": 229 }
}) function fetchWithPolicy(policy: string | null, reportOnly?: boolean) { const cspKey = reportOnly ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy' return next.fetch(`/${runtime}`, { headers: policy ? { [cspKey]...
const policies = [ `script-src 'nonce-'`, // invalid nonce 'style-src "nonce-cmFuZG9tCg=="', // no script or default src `script-src 'nonce-" onerror="alert(1)'`, // malformed nonce '', // empty string
await fetchWithPolicy(policy, reportOnly) expect(res.ok).toBe(true) const html = await res.text() return cheerio.load(html) } it('does not include nonce when not enabled', async () => {
{ "filepath": "test/production/app-dir/subresource-integrity/subresource-integrity.test.ts", "language": "typescript", "file_size": 9489, "cut_index": 921, "middle_length": 229 }
from 'e2e-utils' // TODO: the incremental option has been removed, update to use cacheComponents describe.skip('app-dir - metadata-streaming-config', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should have the default streaming metadata config output in routes-manifest.json', async () ...
log|Twitterbot|LinkedInBot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|Yeti|googleweblight"` ) const prerenderManifest = JSON.parse( await next.readFile('.next/prerender-manifest.json') ) const { routes } = prerenderManifest co
ot( `"[\\w-]+-Google|Google-[\\w-]+|Chrome-Lighthouse|Slurp|DuckDuckBot|baiduspider|yandex|sogou|bitlybot|tumblr|vkShare|quora link preview|redditbot|ia_archiver|Bingbot|BingPreview|applebot|facebookexternalhit|facebookcata
{ "filepath": "test/production/app-dir/metadata-streaming-config/metadata-streaming-config.test.ts", "language": "typescript", "file_size": 1958, "cut_index": 537, "middle_length": 229 }
from 'e2e-utils' describe('worker-restart', () => { describe('timeout', () => { const { next } = nextTestSetup({ files: __dirname + '/fixtures/timeout', skipStart: true, }) it('should properly exhaust all restart attempts and not fail with any worker errors', async () => { const { cliO...
Failed to build /bad-page/page: /bad-page after 3 attempts' ) expect(cliOutput).not.toContain( 'Error: Farm is ended, no more calls can be done to it' ) }) }) describe('retries', () => { const { next } = nextTestSetup
.' ) expect(cliOutput).toContain( 'Failed to build /bad-page/page: /bad-page (attempt 2 of 3) because it took more than 10 seconds. Retrying again shortly.' ) expect(cliOutput).toContain( '
{ "filepath": "test/production/app-dir/worker-restart/worker-restart.test.ts", "language": "typescript", "file_size": 1902, "cut_index": 537, "middle_length": 229 }
etup } from 'e2e-utils' import { fetchViaHTTP, findPort, initNextServerScript, killApp, retry, } from 'next-test-utils' describe('global-default-cache-handler', () => { let appPort: number let server: any let output = '' const { next } = nextTestSetup({ files: new FileRef(__dirname), skipSta...
console.log('symbol set', cacheKey) }, refreshTags() { console.log('symbol refreshTags') }, getExpiration(...tags) { console.log('symbol getExpiration', tags) },
alThis[Symbol.for('@next/cache-handlers')] = { DefaultCache: { get(cacheKey, softTags) { console.log('symbol get', cacheKey, softTags) }, set(cacheKey, entry) {
{ "filepath": "test/production/app-dir/global-default-cache-handler/global-default-cache-handler.test.ts", "language": "typescript", "file_size": 2698, "cut_index": 563, "middle_length": 229 }
} from 'e2e-utils' import path from 'path' describe('empty-shell-route-cache', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true, }) beforeAll(async () => { await next.build() }) async function getRouteArtifactMtimes(route: string) { const routeMeta = JSON.parse( ...
estDir, '.next/server/app', file) ) return [file, stat.mtimeMs] }) ) ) } it('should emit both routes as partially static build artifacts', async () => { const prerenderManifest = JSON.parse( await next.
ring) => `${route}.segments${segmentPath}.segment.rsc` ), ] return Object.fromEntries( await Promise.all( files.map(async (file) => { const stat = await fs.stat( path.join(next.t
{ "filepath": "test/production/app-dir/empty-shell-route-cache/empty-shell-route-cache.test.ts", "language": "typescript", "file_size": 2351, "cut_index": 563, "middle_length": 229 }
ype NextInstance } from 'e2e-utils' async function getServerActionManifestNodeKeys(next: NextInstance) { const manifest = await next.readJSON( '.next/server/server-reference-manifest.json' ) return Object.keys(manifest.node) } describe('app-dir - server-action-period-hash-custom-key', () => { const { next...
RVER_ACTIONS_ENCRYPTION_KEY = 'my-secret-key2' await next.build() delete process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY const secondActionIds = await getServerActionManifestNodeKeys(next) expect(firstActionIds).not.toEqual(secondActionIds)
EXT_SERVER_ACTIONS_ENCRYPTION_KEY = 'my-secret-key1' await next.build() delete process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY const firstActionIds = await getServerActionManifestNodeKeys(next) process.env.NEXT_SE
{ "filepath": "test/production/app-dir/server-action-period-hash/server-action-period-hash-custom-key.test.ts", "language": "typescript", "file_size": 1588, "cut_index": 537, "middle_length": 229 }
er.from([137, 80, 78, 71, 13, 10, 26, 10]) function createChunk(type, data) { const length = Buffer.alloc(4) length.writeUInt32BE(data.length, 0) const crc = Buffer.alloc(4) const crcValue = calculateCRC(Buffer.concat([Buffer.from(type), data])) >>> 0 // Ensure unsigned 32-bit integer crc.writeUInt32BE(crcVa...
= 1024 let pngFile: Buffer do { const ihdrData = Buffer.alloc(13) ihdrData.writeUInt32BE(width, 0) ihdrData.writeUInt32BE(height, 4) ihdrData.writeUInt8(8, 8) // bitDepth ihdrData.writeUInt8(6, 9) // colorType ihdrData.writeUIn
i++) { crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0) } } return crc ^ 0xffffffff } export function generatePNG(targetSizeMB) { const targetSizeBytes = targetSizeMB * 1024 * 1024 let width = 2048, height
{ "filepath": "test/production/app-dir/metadata-img-too-large/generate-image.ts", "language": "typescript", "file_size": 2095, "cut_index": 563, "middle_length": 229 }
rt { nextTestSetup } from 'e2e-utils' describe('reference-tree-shaking', () => { const { next } = nextTestSetup({ files: __dirname, }) it('Should apply removeUnusedImports tree shaking to client and server references', async () => { const res = await next.fetch('/') expect(await res.text()).toContai...
pect(serverReferences).not.toContain('library/action.js') const clientReferences = await next.readFile( '.next/server/app/page_client-reference-manifest.js' ) expect(clientReferences).not.toContain('library/client.js') } })
ver/server-reference-manifest.json' ) ex
{ "filepath": "test/production/app-dir/reference-tree-shaking/reference-tree-shaking.test.ts", "language": "typescript", "file_size": 828, "cut_index": 516, "middle_length": 52 }
strictRouteTypes = process.env.__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES === 'true' describe('types-gen-nounuselocal', () => { const { next, skipped } = nextTestSetup({ files: __dirname, }) if (skipped) { return } it('should build successfully', async () => { const $ = await next.render$('/') ...
f (strictRouteTypes) { const cacheLifeTypes = await fsp.readFile( path.join(next.testDir, '.next', 'types', 'cache-life.d.ts'), 'utf-8' ) expect(cacheLifeTypes).toContain("declare module 'next/cache'") expect(routeT
t', 'types', 'routes.d.ts'), 'utf-8' ) expect(routeTypes).not.toContain('AppRouteHandlerRoutes') expect(routeTypes).not.toContain('PagesPageConfig') expect(routeTypes).not.toContain('ApiRouteConfig') i
{ "filepath": "test/production/app-dir/types-gen-nounuselocal/types-gen-nounuselocal.test.ts", "language": "typescript", "file_size": 4765, "cut_index": 614, "middle_length": 229 }
import path from 'path' import execa from 'execa' const appDir = path.join(__dirname, 'app') describe('next/jest image qualities config', () => { const { next } = nextTestSetup({ skipStart: true, files: { 'next.config.js': ` module.exports = { images: { qualities: [90, 100], }, } `, ...
age quality config', () => { it('respects custom qualities from next.config.js', () => { render( <Image src="/test.jpg" alt="test" width={500} height={500} quality={100} /> ) const img = sc
testEnvironment: 'jsdom', } module.exports = createJestConfig(customJestConfig) `, [`tests/image.test.tsx`]: ` import Image from 'next/image' import { render, screen } from '@testing-library/react' describe('Im
{ "filepath": "test/production/app-dir/image-jest-qualities/image-jest-qualities.test.ts", "language": "typescript", "file_size": 2664, "cut_index": 563, "middle_length": 229 }
import { nextTestSetup } from 'e2e-utils' describe('app-dir parallel-routes-static', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should static generate parallel routes', async () => { const rscExtension = '.rsc' expect(await next.hasFile('.next/server/app/nested/foo.html')).toB...
.next/server/app/nested/bar.meta')).toBe(true) // we do not output '.rsc' statically with cache components if (!process.env.__NEXT_CACHE_COMPONENTS) { expect( await next.hasFile(`.next/server/app/nested/bar${rscExtension}`) ).t
NTS) { expect( await next.hasFile(`.next/server/app/nested/foo${rscExtension}`) ).toBe(true) } expect(await next.hasFile('.next/server/app/nested/bar.html')).toBe(true) expect(await next.hasFile('
{ "filepath": "test/production/app-dir/parallel-routes-static/index.test.ts", "language": "typescript", "file_size": 1021, "cut_index": 512, "middle_length": 229 }
outdent' describe('production - app dir - build output', () => { const { next } = nextTestSetup({ files: __dirname, }) let output = '' beforeAll(() => { output = stripAnsi(next.cliOutput) }) it('should only log app routes', async () => { expect(output).toContain('Route (app)') expect(outp...
han(indexOfLinting) expect(indexOfStartCompiling).toBeLessThan(indexOfLinting) }) it('should match the expected output format', async () => { // output type expect(output).toContain('○ (Static) prerendered as static content') }) it(
tput.indexOf('▲ Next.js') const indexOfStartCompiling = output.indexOf( 'Creating an optimized production build' ) const indexOfLinting = output.indexOf('Running TypeScript') expect(indexOfVersion).toBeLessT
{ "filepath": "test/production/app-dir/build-output/index.test.ts", "language": "typescript", "file_size": 4136, "cut_index": 614, "middle_length": 229 }
under `test/production` so it only runs in `next start` mode. In dev // mode the default in-memory `'use cache'` handler would return the cached // function value on re-render (we don't fake time for the function-level // cache), so the observable wouldn't change even when the ISR layer does a // blocking revalidation...
pire', () => { const { next } = nextTestSetup({ files: __dirname, }) async function expectBlockingRevalidation(path: string) { const $first = await next.render$(path) const v0 = $first('#value').text() expect(v0).toBeTruthy() co
nion suite // `test/e2e/app-dir/expire-time` covers the same `IncrementalCache` / // response-cache change via classic ISR (no `use cache`, no custom handler, // short `expireTime`) and runs in deploy mode. describe('use-cache-ex
{ "filepath": "test/production/app-dir/use-cache-expire/use-cache-expire.test.ts", "language": "typescript", "file_size": 2409, "cut_index": 563, "middle_length": 229 }
{ nextTestSetup } from 'e2e-utils' // TODO: the incremental option has been removed, update to use cacheComponents describe.skip('app-dir - metadata-streaming-config-customized', () => { const { next } = nextTestSetup({ files: __dirname, overrideFiles: { 'next.config.js': ` module.exports = { ...
Object.keys(routes) .map((route) => [route, routes[route].experimentalBypassFor?.[2]]) .filter(([, bypassConfig]) => Boolean(bypassConfig)) .reduce((acc, [route, bypassConfig]) => { acc[route] = bypassConfig return acc
config output in routes-manifest.json', async () => { const prerenderManifest = JSON.parse( await next.readFile('.next/prerender-manifest.json') ) const { routes } = prerenderManifest const bypassConfigs =
{ "filepath": "test/production/app-dir/metadata-streaming-config/metadata-streaming-config-customized.test.ts", "language": "typescript", "file_size": 1205, "cut_index": 518, "middle_length": 229 }
s' import { listClientChunks } from 'next-test-utils' import path from 'path' export async function deleteBrowserDynamicChunks(next) { const distDir = path.join(next.testDir, '.next') const clientChunkFiles = (await listClientChunks(distDir)) .map((file) => path.join(distDir, file)) // filter out the js fi...
isJsFile && fileContent && fileContent.includes('large test content') ) }) // Intended to log to help debugging tests console.log('Deleting client chunk files:', clientChunkFiles) // delete all chunk files clientChunkFiles.map((
, { encoding: 'utf8' }) : '' return (
{ "filepath": "test/production/app-dir/graceful-degrade/delete-dynamic-chunk.js", "language": "javascript", "file_size": 865, "cut_index": 529, "middle_length": 52 }
from 'e2e-utils' describe('no-mangling', () => { describe('with the default `next build`', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true, }) it('should show mangled function names in stack traces', async () => { try { await next.build() } catc...
build --no-mangling`', () => { const { next } = nextTestSetup({ files: __dirname, buildArgs: ['--no-mangling'], skipStart: true, }) it('should show original function names in stack traces', async () => { try { a
`Page` is the original function name that is mangled because `next // build` was called without `--no-mangling`. expect(next.cliOutput).not.toInclude(` Error: Kaputt! at Page`) }) }) describe('with `next
{ "filepath": "test/production/app-dir/no-mangling/no-mangling.test.ts", "language": "typescript", "file_size": 1794, "cut_index": 537, "middle_length": 229 }
Setup } from 'e2e-utils' import { generatePNG } from '../generate-image' describe('app-dir - metadata-img-too-large opengraph-image', () => { const { next, isTurbopack } = nextTestSetup({ files: __dirname, skipStart: true, }) const pngFile = generatePNG(8) it('should throw when opengraph-image file s...
, so the prefix is slightly different. /File size for Open Graph image "\[project\]\/app\/opengraph-image\.png" exceeds 8MB/ : /Error: File size for Open Graph image ".*\/app\/opengraph-image\.png" exceeds 8MB/ expect(next.cliOutput).toM
implified as [project]/.... It's also thrown earlier
{ "filepath": "test/production/app-dir/metadata-img-too-large/opengraph-image/index.test.ts", "language": "typescript", "file_size": 857, "cut_index": 529, "middle_length": 52 }
lib/cache-handlers/default.external').default /** * @type {import('next/dist/server/lib/cache-handlers/types').CacheHandler} */ const cacheHandler = { async get(cacheKey, softTags) { console.log('CustomCacheHandler::get', cacheKey, JSON.stringify([softTags])) return defaultCacheHandler.get(cacheKey, softTa...
sync getExpiration(tags) { // Expecting soft tags in `get` to be used by the cache handler for checking // the expiration of a cache entry, instead of letting Next.js handle it. return Infinity }, async updateTags(tags) { return defaul
return defaultCacheHandler.refreshTags() }, a
{ "filepath": "test/production/app-dir/use-cache-cross-deployment/handler.js", "language": "javascript", "file_size": 959, "cut_index": 582, "middle_length": 52 }
mises' import { listClientChunks } from 'next-test-utils' describe('browser-chunks', () => { const { next } = nextTestSetup({ files: __dirname, }) let sources: string[] = [] let jsContents: string[] = [] beforeAll(async () => { const chunksDir = join(next.testDir, '.next') const chunks = await ...
(join(chunksDir, f), 'utf8')) ) }) it('must not bundle any server modules into browser chunks', () => { const serverSources = sources.filter( (source) => /webpack:\/\/_N_E\/(\.\.\/)*src\/server\//.test(source) || source.i
'utf8')) ) sources = sourcemaps.flatMap((sourcemap) => JSON.parse(sourcemap).sources) jsContents = await Promise.all( chunks .filter((filename) => filename.endsWith('.js')) .map((f) => readFile
{ "filepath": "test/production/app-dir/browser-chunks/browser-chunks.test.ts", "language": "typescript", "file_size": 3754, "cut_index": 614, "middle_length": 229 }
onfiguration', () => { let nextTgzFilename: string beforeAll(() => { nextTgzFilename = resolveNextTgzFilename() }) it('should match biome.json snapshot', async () => { await useTempDir(async (cwd) => { const projectName = 'test-biome-snapshot' const { exitCode } = await run( [ ...
t readFile(join(projectDir, 'biome.json'), 'utf8') expect(biomeConfig).toMatchSnapshot() }) }) it('should run biome check successfully on generated TypeScript project', async () => { await useTempDir(async (cwd) => { const project
, '--no-agents-md', '--skip-install', ], nextTgzFilename, { cwd } ) expect(exitCode).toBe(0) const projectDir = join(cwd, projectName) const biomeConfig = awai
{ "filepath": "test/production/create-next-app/biome-config.test.ts", "language": "typescript", "file_size": 5350, "cut_index": 716, "middle_length": 229 }
=> { let nextTgzFilename: string beforeAll(() => { nextTgzFilename = resolveNextTgzFilename() }) it('should create JavaScript project with --js flag', async () => { await useTempDir(async (cwd) => { const projectName = 'pages-js' const { exitCode } = await run( [ projectN...
cwd, projectName, template: 'default', mode: 'js', }) await tryNextDev({ cwd, projectName, isApp: false, }) }) }) it('should create TypeScript project with --ts flag', async () =>
'--no-agents-md', ...(process.env.NEXT_RSPACK ? ['--rspack'] : []), ], nextTgzFilename, { cwd, } ) expect(exitCode).toBe(0) shouldBeTemplateProject({
{ "filepath": "test/production/create-next-app/templates/pages.test.ts", "language": "typescript", "file_size": 5541, "cut_index": 716, "middle_length": 229 }
ort path from 'path' import { FileRef, nextTestSetup } from 'e2e-utils' import { renderViaHTTP } from 'next-test-utils' const files = { 'app/layout.jsx': ` export default function AppLayout({ children }) { return ( <html> <head> <title>WASM Import</title> </head> ...
1 is: $\{two}\` } export const runtime = "edge" `, 'wasm/add.wasm': new FileRef(path.join(__dirname, 'add.wasm')), } describe('app-dir edge runtime with wasm', () => { const { next } = nextTestSetup({ files, }) it('should have buil
nstantiate(wasm); async function addOne(a) { const { exports } = await instance$; return exports.add_one(a); } export default async function Page() { const two = await addOne(1) return \`1 +
{ "filepath": "test/production/app-dir-edge-runtime-with-wasm/index.test.ts", "language": "typescript", "file_size": 1120, "cut_index": 515, "middle_length": 229 }
from 'e2e-utils' import { retry } from 'next-test-utils' describe('Image Component No IntersectionObserver test', () => { const { next } = nextTestSetup({ files: __dirname, }) describe('SSR Lazy Loading Tests', () => { it('should automatically load images if observer does not exist', async () => { ...
entById('lazy-no-observer').getAttribute('srcset') ).toBe( 'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=1024 1x, https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000 2x' ) }) }) describe('Client-si
) expect( await browser.elementById('lazy-no-observer').getAttribute('src') ).toBe( 'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000' ) expect( await browser.elem
{ "filepath": "test/production/next-image-legacy/no-intersection-observer-fallback/no-intersection-observer-fallback.test.ts", "language": "typescript", "file_size": 1921, "cut_index": 537, "middle_length": 229 }
s = await browser.elementsByCss('link[rel=preload][as=image]') for (const link of links) { const imagesrcset = await link.getAttribute('imagesrcset') const href = await link.getAttribute('href') if (imagesrcset?.includes(url) || (!imagesrcset && href === url)) { return true } } ...
tyle' && foundImage) { return true } } } return false } function runTests(browser: () => Browser) { it('should render an image tag', async () => { expect(await browser().hasElementByCssSelector('img')).toBeTru
{ const rel = await link.getAttribute('rel') if (rel === 'preload') { const linkAs = await link.getAttribute('as') if (linkAs === 'image') { foundImage = true } else if (linkAs === 's
{ "filepath": "test/production/next-image-legacy/basic/basic.test.ts", "language": "typescript", "file_size": 15535, "cut_index": 921, "middle_length": 229 }
egacy/image' import Link from 'next/link' const ClientSide = () => { return ( <div> <p id="stubtext">This is a client side page</p> <Image id="basic-image" src="foo.jpg" loading="eager" width={300} height={400} quality={60} ></Image> <Image ...
src="https://arbitraryurl.com/foo.jpg" loading="eager" width={300} height={400} /> <Image id="priority-image-client" priority src="withpriorityclient.png" width={300} height={400}
age" data-demo="demo-value" host="secondary" src="foo2.jpg" loading="eager" width={300} height={400} /> <Image id="unoptimized-image" unoptimized
{ "filepath": "test/production/next-image-legacy/basic/pages/client-side.js", "language": "javascript", "file_size": 2087, "cut_index": 563, "middle_length": 229 }
egacy/image' import Link from 'next/link' import Head from 'next/head' const Page = () => { return ( <div> <p>Hello World</p> <Image id="image-with-sizes" src="/test-sizes.jpg" width={2000} height={100} sizes="100vw" /> <Image id="basic-imag...
loading="eager" width={300} height={400} /> <Image id="unoptimized-image" unoptimized src="https://arbitraryurl.com/foo.jpg" loading="eager" width={300} height={400} />
value" src="bar.jpg" loading="eager" width={1024} height={400} /> <Image id="secondary-image" data-demo="demo-value" host="secondary" src="foo2.jpg"
{ "filepath": "test/production/next-image-legacy/basic/pages/index.js", "language": "javascript", "file_size": 2846, "cut_index": 563, "middle_length": 229 }
from 'react' import Image from 'next/legacy/image' const Lazy = () => { return ( <div> <p id="stubtext">This is a page with lazy-loaded images</p> <Image id="lazy-top" src="lazy1.jpg" height={400} width={1024} loading="lazy" ></Image> <div style={{...
></Image> <div style={{ height: '2000px' }}></div> <Image id="lazy-without-attribute" src="lazy4.jpg" height={400} width={800} ></Image> <div style={{ height: '2000px' }}></div> <Image
/Image> <div style={{ height: '2000px' }}></div> <Image id="lazy-bottom" src="https://www.otherhost.com/lazy3.jpg" height={400} width={300} unoptimized loading="lazy"
{ "filepath": "test/production/next-image-legacy/basic/pages/lazy.js", "language": "javascript", "file_size": 1384, "cut_index": 524, "middle_length": 229 }
import { join } from 'path' import { nextTestSetup } from 'e2e-utils' import { waitFor } from 'next-test-utils' describe('react-virtualized wrapping next/legacy/image', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipStart: true, skipDeployment: true, dependencies: { 'r...
next.start() proxyChild = spawn( process.execPath, [join(next.testDir, 'server.js'), next.url, '0', '3000'], { stdio: ['ignore', 'pipe', 'inherit'] } ) proxyPort = await new Promise<number>((resolve, reject) => { let b
nst res = await fetch(`http://localhost:${proxyPort}/_test/cancel-count`) const data = (await res.json()) as { cancelCount: number } return data.cancelCount } beforeAll(async () => { await next.build() await
{ "filepath": "test/production/next-image-legacy/react-virtualized/react-virtualized.test.ts", "language": "typescript", "file_size": 2241, "cut_index": 563, "middle_length": 229 }
xy server used by react-virtualized.test.ts to introduce // per-request stalls and count cancelled image requests. The script is run // inside the isolated test directory so `http-proxy` can be installed via the // `dependencies` option of `nextTestSetup`. The test process communicates // with this server via the `_tes...
eServer(async (req, res) => { if (req.url === '/_test/cancel-count') { res.setHeader('content-type', 'application/json') res.end(JSON.stringify({ cancelCount })) return } if (req.url.startsWith('/_next/image')) { let isComplete = fal
process.argv[4] || 3000) if (!target) { console.error('usage: node server.js <target> [port] [stallMs]') process.exit(1) } let cancelCount = 0 const proxy = httpProxy.createProxyServer({ target }) const server = http.creat
{ "filepath": "test/production/next-image-legacy/react-virtualized/server.js", "language": "javascript", "file_size": 1393, "cut_index": 524, "middle_length": 229 }
jpg' import { WindowScroller, List as VirtualizedList } from 'react-virtualized' export default function Home() { return ( <div> <WindowScroller serverHeight={800}> {({ height, isScrolling, onChildScroll, scrollTop }) => ( <VirtualizedList autoHeight height={height...
r={() => { return ( <div> <Image src={img} placeholder="blur" className="thumbnail" /> <Image src={img} className="large" /> </div> ) }}
} rowHeight={400} rowRendere
{ "filepath": "test/production/next-image-legacy/react-virtualized/pages/index.js", "language": "javascript", "file_size": 977, "cut_index": 582, "middle_length": 52 }
t { nextTestSetup } from 'e2e-utils' import cheerio from 'cheerio' describe('Noscript Tests', () => { const { next } = nextTestSetup({ files: __dirname, }) describe('Noscript page source tests', () => { it('should use local API for noscript img#basic-image src attribute', async () => { const html ...
script img#image-with-loader src attribute', async () => { const html = await next.render('/') const $ = cheerio.load(html) expect($('noscript > img#image-with-loader').attr('src')).toMatch( /^https:\/\/customresolver.com/
der url for no
{ "filepath": "test/production/next-image-legacy/noscript/noscript.test.ts", "language": "typescript", "file_size": 804, "cut_index": 517, "middle_length": 14 }
tTestSetup, type Playwright } from 'e2e-utils' describe('Custom Resolver Tests', () => { const { next } = nextTestSetup({ files: __dirname, }) type Browser = Playwright function runTests(browser: () => Browser) { it('Should use a custom resolver for image URL', async () => { expect( awai...
) }) it('should support the unoptimized attribute', async () => { expect( await browser().elementById('unoptimized-image').getAttribute('src') ).toBe('https://arbitraryurl.com/foo.jpg') }) } describe('SSR Custom Lo
ync () => { expect( await browser().elementById('basic-image').getAttribute('srcset') ).toBe( 'https://customresolver.com/foo.jpg?w~~480,q~~60 1x, https://customresolver.com/foo.jpg?w~~1024,q~~60 2x'
{ "filepath": "test/production/next-image-legacy/custom-resolver/custom-resolver.test.ts", "language": "typescript", "file_size": 1371, "cut_index": 524, "middle_length": 229 }
t' import Image from 'next/legacy/image' import Link from 'next/link' const myLoader = ({ src, width, quality }) => { return `https://customresolver.com/${src}?w~~${width},q~~${quality}` } const MyImage = (props) => { return <Image loader={myLoader} {...props}></Image> } const Page = () => { return ( <div>...
unoptimized src="https://arbitraryurl.com/foo.jpg" loading="eager" width={300} height={400} /> <Link href="/client-side" id="clientlink"> Client Side </Link> </div> ) } export default Page
/> <Image id="unoptimized-image"
{ "filepath": "test/production/next-image-legacy/custom-resolver/pages/index.js", "language": "javascript", "file_size": 844, "cut_index": 535, "middle_length": 52 }
p } from 'e2e-utils' import { findPort, initNextServerScript, killApp, renderViaHTTP, } from 'next-test-utils' describe('pnpm support', () => { describe('build with dependencies installed via pnpm', () => { const { next } = nextTestSetup({ files: { pages: new FileRef(path.join(__dirname, 'a...
BeTruthy() expect(next.cliOutput).toMatch(/Compiled successfully/) const html = await renderViaHTTP(next.url, '/') expect(html).toContain('Hello World') const manifest = JSON.parse( await next.readFile('.next/next-server.
d', start: 'next start', }, }, buildCommand: 'pnpm run build', }) it('should build with dependencies installed via pnpm', async () => { expect(await next.readFile('pnpm-lock.yaml')).to
{ "filepath": "test/production/pnpm-support/index.test.ts", "language": "typescript", "file_size": 3781, "cut_index": 614, "middle_length": 229 }
('next.config.js validation', () => { describe('production mode', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipStart: true, skipDeployment: true, }) if (skipped) return it.each([ { name: 'invalid config types', configContent: ` ...
experimental: { anotherNonExistent: true } } `, outputs: [ `Unrecognized key(s) in object: 'nonExistent'`, `Unrecognized key(s) in object: 'anotherNonExistent' at "experimental"`,
loader"`, 'Expected function, received boolean at "rewrites"', ], }, { name: 'unexpected config fields', configContent: ` module.exports = { nonExistent: true,
{ "filepath": "test/production/config-validation/config-validation.test.ts", "language": "typescript", "file_size": 2029, "cut_index": 563, "middle_length": 229 }
hing code, // so we only enable it in production describe('Link with legacyBehavior - handles buggy userspace ref merging', () => { const { next } = nextTestSetup({ files: __dirname, }) it('does not crash when Link unmounts', async () => { const browser = await next.browser('/') expect(await browser...
sSelector('#test-link')).toBe(false) // shouldn't cause a crash expect(await browser.elementByCss('h1').text()).toEqual('Home') expect(await browser.elementByCss('body').text()).not.toContain( 'Application error: a client-side exception
on').click() expect(await browser.hasElementByCs
{ "filepath": "test/production/next-link-legacybehavior-ref-merging/index.test.ts", "language": "typescript", "file_size": 942, "cut_index": 606, "middle_length": 52 }
from 'next/link' import { useCallback, useState, type ComponentPropsWithRef, type ReactNode, type Ref, type RefCallback, } from 'react' export default function Page() { return ( <> <h1>Home</h1> <ToggleVisibility> <Link href="/link-target" legacyBehavior> <AnchorThatDoes...
ow content'} </button> </div> {isVisible ? children : null} </> ) } function AnchorThatDoesRefMerging({ ref, children, ...anchorProps }: ComponentPropsWithRef<'a'>) { const customRef: RefCallback<HTMLAnchorElement> = useC
{ children: ReactNode }) { const [isVisible, setIsVisible] = useState(true) return ( <> <div> <button type="button" onClick={() => setIsVisible((prev) => !prev)}> {isVisible ? 'Hide content' : 'Sh
{ "filepath": "test/production/next-link-legacybehavior-ref-merging/app/page.tsx", "language": "tsx", "file_size": 2016, "cut_index": 537, "middle_length": 229 }
mport { recursiveReadDir } from 'next/dist/lib/recursive-readdir' import { nextTestSetup } from 'e2e-utils' function extractSourceMappingURL(jsContent: string): string | null { // Matches both //# and //@ sourceMappingURL=... const match = jsContent.match(/\/\/[#@] sourceMappingURL=([^\s]+)/) return match ? matc...
/^__turbopack_load_page_chunks__\(["']/.test(jsContent) || (!process.env.IS_TURBOPACK_TEST && jsContent.length < 300) ) { // There is no sourcemap in these loader chunks, ignore return } if (await fs.pathExists(jsFilePath +
rSourceMaps: boolean } ) { const jsFilePath = path.join(dir, file) const jsContent = await fs.readFile(jsFilePath, 'utf8') const sourceMappingURL = extractSourceMappingURL(jsContent) if (!sourceMappingURL) { if (
{ "filepath": "test/production/production-browser-sourcemaps/index.test.ts", "language": "typescript", "file_size": 3409, "cut_index": 614, "middle_length": 229 }
> { it('should not revalidate during prefetching', async () => { const cliOutputStart = next.cliOutput.length for (let i = 0; i < 3; i++) { for (const path of ['/blog/first', '/blog/second']) { const res = await fetchViaHTTP( next.url, `/_next/data/${next.build...
revalidating /blog' ) }) it('should trigger revalidation after navigation', async () => { const getData = () => fetchViaHTTP( next.url, `/_next/data/${next.buildId}/blog/first.json`, undefined,
e(200) } // do requests three times with 1 second between // to go over revalidate period await waitFor(1000) } expect(next.cliOutput.substring(cliOutputStart)).not.toContain( '
{ "filepath": "test/production/prerender-prefetch/index.test.ts", "language": "typescript", "file_size": 10945, "cut_index": 921, "middle_length": 229 }
from 'e2e-utils' import { retry } from 'next-test-utils' import { NextInstanceOpts } from '../../lib/next-modes/base' describe('React Profiling Mode', () => { describe('default is disabled', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should not have used the react-dom profil...
'--profile'] } satisfies Partial<NextInstanceOpts>, }, ])('enabled with $name', ({ opts }) => { const { next } = nextTestSetup({ files: __dirname, ...opts, }) it('should have used the react-dom profiling bundle for pages', as
cribe.each([ { name: 'config setting', opts: { env: { TEST_REACT_PRODUCTION_PROFILING: 'true' }, } satisfies Partial<NextInstanceOpts>, }, { name: 'CLI flag', opts: { buildArgs: [
{ "filepath": "test/production/react-profiling-mode/react-profiling-mode.test.ts", "language": "typescript", "file_size": 2018, "cut_index": 537, "middle_length": 229 }
oryStatsWithFiles serverUnbundled: CategoryStatsWithFiles clientJs: CategoryStatsWithFiles clientMaps: CategoryStatsWithFiles clientCss: CategoryStatsWithFiles } interface ToolOutput { routes: RouteInfo[] totals: Totals } const ALL_CATEGORIES = [ 'serverBundled', 'serverMaps', 'serverUnbundled', '...
= 0) { throw new Error( `next build failed with exit code ${buildResult.exitCode}` ) } }) async function runTool( args: string[] ): Promise<{ stdout: string; stderr: string; code: number | null }> { const result = awa
const { next, isTurbopack, skipped } = nextTestSetup({ files: __dirname, skipStart: true, }) if (skipped) return beforeAll(async () => { const buildResult = await next.build() if (buildResult.exitCode !=
{ "filepath": "test/production/static-routes-info/static-routes-info.test.ts", "language": "typescript", "file_size": 31199, "cut_index": 1331, "middle_length": 229 }
{ readFileSync, statSync } from 'fs' import { join } from 'path' import { nextTestSetup } from 'e2e-utils' describe('Fallback Modules', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true, dependencies: { seedrandom: 'latest', }, }) it('should not include crypto', a...
th = join(next.testDir, '.next', chunkPath) try { const stats = statSync(fullChunkPath) totalSize += stats.size } catch { // chunk may not exist } } const totalSizeKB = totalSize / 1024 expect(totalSi
const buildManifest = JSON.parse(readFileSync(buildManifestPath, 'utf8')) const indexPageChunks = buildManifest.pages['/'] || [] let totalSize = 0 for (const chunkPath of indexPageChunks) { const fullChunkPa
{ "filepath": "test/production/fallback-modules/fallback-modules.test.ts", "language": "typescript", "file_size": 1133, "cut_index": 518, "middle_length": 229 }
nextConfigPath = 'next.config.js' const outdir = 'out' const outNoTrailSlash = 'outNoTrailSlash' let server: Server let port: number let serverNoTrailSlash: Server let portNoTrailSlash: number beforeAll(async () => { const nextConfig = await next.readFile(nextConfigPath) await next.build() ...
Dir, outNoTrailSlash) ) port = (server.address() as AddressInfo).port portNoTrailSlash = (serverNoTrailSlash.address() as AddressInfo).port }) afterAll(async () => { await Promise.all([ new Promise((resolve) => server.close(resol
) await next.build() await next.patchFile(nextConfigPath, nextConfig) server = await startStaticServer(path.join(next.testDir, outdir)) serverNoTrailSlash = await startStaticServer( path.join(next.test
{ "filepath": "test/production/export/index.test.ts", "language": "typescript", "file_size": 15638, "cut_index": 921, "middle_length": 229 }
ts = (phase) => { return { output: 'export', distDir: 'out', trailingSlash: true, exportPathMap: function () { return { '/': { page: '/' }, '/index': { page: '/' }, '/about': { page: '/about' }, '/button-link': { page: '/button-link' }, '/hash-link': { pag...
} }, '/dynamic/one': { page: '/dynamic', query: { text: 'next export is nice' }, }, '/dynamic/two': { page: '/dynamic', query: { text: 'Vercel is awesome' }, }, '/file-name.md'
page: '/get-initial-props-with-no-query', }, '/counter': { page: '/counter' }, '/dynamic-imports': { page: '/dynamic-imports' }, '/dynamic': { page: '/dynamic', query: { text: 'cool dynamic text'
{ "filepath": "test/production/export/next.config.js", "language": "javascript", "file_size": 1382, "cut_index": 524, "middle_length": 229 }
nk' import Router from 'next/router' function routeToAbout(e) { e.preventDefault() Router.push('/about') } export default () => ( <div id="home-page"> <div> <Link href="/about" id="about-via-link"> About via Link </Link> <a href="#" onClick={routeToAbout} id="about-via-router"> ...
some" as="/dynamic/two" id="dynamic-2" > Dynamic 2 </Link> <Link href="/dynamic?text=Vercel+is+awesome#cool" id="with-hash"> With Hash </Link> <Link href="/dynamic?text=this+file+has+an+
nitialProps </Link> <Link href="/dynamic?text=next+export+is+nice" as="/dynamic/one" id="dynamic-1" > Dynamic 1 </Link> <Link href="/dynamic?text=Vercel+is+awe
{ "filepath": "test/production/export/pages/index.js", "language": "javascript", "file_size": 1666, "cut_index": 537, "middle_length": 229 }
eRef, nextTestSetup } from 'e2e-utils' import { join } from 'path' import { fetchViaHTTP, waitFor } from 'next-test-utils' describe('app-dir-prevent-304-caching', () => { const { next } = nextTestSetup({ files: { 'next.config.js': new FileRef(join(__dirname, 'next.config.js')), app: new FileRef(join(...
nst rHit = await fetchViaHTTP( next.url, '/', {}, { headers: { 'If-None-Match': rStale.headers.get('etag'), }, } ) expect(rHit.status).toBe(200) await waitFor(500) // Here happens the
ing background revalidation. await next.waitForMinPrerenderAge(1000 + 50) const rStale = await fetchViaHTTP(next.url, '/') expect(rStale.status).toBe(200) await waitFor(500) // Cache HIT but still 200 co
{ "filepath": "test/production/app-dir-prevent-304-caching/index.test.ts", "language": "typescript", "file_size": 1463, "cut_index": 524, "middle_length": 229 }
('TypeScript with error handling options', () => { describe('production mode', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipStart: true, skipDeployment: true, }) if (skipped) return for (const incremental of [false, true]) { for (const ignoreBuildErr...
= { typescript: { ignoreBuildErrors }, } await next.patchFile( 'next.config.js', 'module.exports = ' + JSON.stringify(nextConfig) ) const tsconfig = JSON.parse(origin
(async () => { originalNextConfig = await next .readFile('next.config.js') .catch(() => '') originalTsConfig = await next.readFile('tsconfig.json') const nextConfig
{ "filepath": "test/production/typescript-ignore-errors/typescript-ignore-errors.test.ts", "language": "typescript", "file_size": 2987, "cut_index": 563, "middle_length": 229 }
{ nextTestSetup } from 'e2e-utils' describe('ipc-forbidden-headers', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should not error if expect header is included', async () => { let res = await next.fetch('/api/pages-api', { method: 'POST', headers: { expect: '100-continu...
t shouldn't contain a payload", async () => { let res = await next.fetch('/api/pages-api', { method: 'DELETE', headers: { 'content-length': '0' }, }) expect(res.status).toBe(200) res = await next.fetch('/api/app-api', {
100-continue', }, }) text = await res.text() expect(text).toEqual('Hello, Next.js!') expect(next.cliOutput).not.toContain('UND_ERR_NOT_SUPPORTED') }) it("should not error on content-length: 0 if reques
{ "filepath": "test/production/ipc-forbidden-headers/ipc-forbidden-headers.test.ts", "language": "typescript", "file_size": 1192, "cut_index": 518, "middle_length": 229 }
tTestSetup } from 'e2e-utils' const fileNames = ['1', '2.ext', '3.html'] describe('GS(S)P with file extension', () => { describe('production mode', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, }) if (skipped) return it('should support slug wi...
map((path) => next.render(path)) const contents = await Promise.all(contentPromises) contents.forEach((content, i) => expect(content).toContain(fileNames[i])) }) it('should contain extension in name of json files in _next/data', async
(`.next/server/pages/${name}.json`)).toBe(true) } }) it('should render properly for routes with extension', async () => { const paths = fileNames.map((name) => `/${name}`) const contentPromises = paths.
{ "filepath": "test/production/gsp-extension/gsp-extension.test.ts", "language": "typescript", "file_size": 1433, "cut_index": 524, "middle_length": 229 }
ations', () => { const { next } = nextTestSetup({ skipStart: true, files: { 'pages/index.js': ` export default function Page() { return <p>hello world</p> } `, 'middleware.js': ` import { NextResponse } from 'next/server' export default...
async () => { const res = await next.build() expect(res.exitCode).toBe(1) expect(res.cliOutput).toContain( 'middleware contains invalid middleware config: Expected string, received boolean at "unstable_allowDynamic", or Expected array, re
build when unstable_allowDynamic is not a string',
{ "filepath": "test/production/edge-config-validations/index.test.ts", "language": "typescript", "file_size": 947, "cut_index": 582, "middle_length": 52 }
from 'e2e-utils' import { findAllTelemetryEvents } from 'next-test-utils' describe('build-lifecycle-hooks', () => { const { next } = nextTestSetup({ files: __dirname, env: { NEXT_TELEMETRY_DEBUG: '1', }, }) it('should run runAfterProductionCompile', async () => { const output = next.cliOut...
UILD_FEATURE_USAGE') expect(events).toContainEqual({ featureName: 'runAfterProductionCompile', invocationCount: 1, }) }) it('should allow throwing error in runAfterProductionCompile', async () => { try { await next.stop()
toContain(`Total files in ${next.testDir}/.next folder:`) expect(output).toContain('Completed runAfterProductionCompile in') // Ensure telemetry event is recorded const events = findAllTelemetryEvents(output, 'NEXT_B
{ "filepath": "test/production/build-lifecycle-hooks/index.test.ts", "language": "typescript", "file_size": 1714, "cut_index": 537, "middle_length": 229 }
tTestSetup } from 'e2e-utils' describe('standalone mode - metadata routes', () => { const { next } = nextTestSetup({ files: __dirname, dependencies: { swr: 'latest', }, }) beforeAll(async () => { // Hide source files to make sure route.js can read files from source // in order to hit t...
-found/does-not-exist') expect(res.status).toBe(404) const html = await res.text() expect(html).toContain('app-not-found') }) it('should handle private _next unmatched route correctly', async () => { const res = await next.fetch('/_nex
const iconRes = await next.fetch('/icon.svg') expect(faviconRes.status).toBe(200) expect(iconRes.status).toBe(200) }) it('should handle correctly not-found.js', async () => { const res = await next.fetch('/not
{ "filepath": "test/production/standalone-mode/basic/index.test.ts", "language": "typescript", "file_size": 1340, "cut_index": 524, "middle_length": 229 }
describe('create-next-app', () => { let nextTgzFilename: string beforeAll(() => { nextTgzFilename = resolveNextTgzFilename() }) it('should not create if the target directory is not empty', async () => { await useTempDir(async (cwd) => { const projectName = 'non-empty-dir' await mkdir(joi...
process.env.NEXT_RSPACK ? ['--rspack'] : []), ], nextTgzFilename, { cwd, reject: false, } ) expect(res.exitCode).toBe(1) expect(res.stdout).toMatch(/contains files that could conflict/)
ctName, '--ts', '--app', '--no-linter', '--no-tailwind', '--no-src-dir', '--no-import-alias', '--no-react-compiler', '--no-agents-md', ...(
{ "filepath": "test/production/create-next-app/index.test.ts", "language": "typescript", "file_size": 7267, "cut_index": 716, "middle_length": 229 }
prompts', () => { let nextTgzFilename: string beforeAll(() => { nextTgzFilename = resolveNextTgzFilename() }) it('should prompt user for choice if directory name is absent', async () => { await useTempDir(async (cwd) => { const projectName = 'no-dir-name' const childProcess = createNextAp...
).toBe(0) projectFilesShouldExist({ cwd, projectName, files: ['package.json'], }) resolve() }) // enter project name childProcess.stdin.write(`${projectName}\n`)
'--no-agents-md', ], { cwd, }, nextTgzFilename ) await new Promise<void>((resolve) => { childProcess.on('exit', async (exitCode) => { expect(exitCode
{ "filepath": "test/production/create-next-app/prompts.test.ts", "language": "typescript", "file_size": 9039, "cut_index": 716, "middle_length": 229 }
lly-packed workspace tarballs available to * `create-next-app` tests. The result is forwarded to spawned CNA * processes via `NEXT_TEST_PKG_PATHS` so the CNA template can install * siblings (`next-rspack`, `eslint-config-next`, ...) from their own * tarballs without reverse-engineering the repo layout. */ import ...
tgz` files (used * when running jest directly via `pnpm test-start-turbo` etc.). * * Returns `null` when no source is available, so callers can produce * targeted error messages. */ export function resolveTestPkgPaths(): Map<string, string> | null
utePathToPackedTarball> for every * locally-packed workspace package available to tests. * * Resolution order: * 1. `NEXT_TEST_PKG_PATHS` (JSON, set by `run-tests.js`). * 2. Discovery from the repo's `packages/<name>/packed.
{ "filepath": "test/production/create-next-app/lib/test-pkg-paths.ts", "language": "typescript", "file_size": 2460, "cut_index": 563, "middle_length": 229 }
_EXAMPLE_PATH, projectFilesShouldExist, resolveNextTgzFilename, run, useTempDir, } from '../utils' describe('create-next-app with package manager bun', () => { let nextTgzFilename: string let files: string[] beforeAll(async () => { nextTgzFilename = resolveNextTgzFilename() await command('bun',...
-bun flag', async () => { await useTempDir(async (cwd) => { const projectName = 'use-bun' const res = await run( [ projectName, '--ts', '--app', '--use-bun', '--no-linter',
me CI runners pre-install Bun. // Locally, we don't pin Bun either. const lockFile = semver.gte(bunVersion, '1.2.0') ? 'bun.lock' : 'bun.lockb' files = [...DEFAULT_FILES, lockFile] }) it('should use bun for --use
{ "filepath": "test/production/create-next-app/package-manager/bun.test.ts", "language": "typescript", "file_size": 3080, "cut_index": 614, "middle_length": 229 }
uldNotExist, resolveNextTgzFilename, run, useTempDir, } from '../utils' const lockFile = 'pnpm-lock.yaml' const files = [...DEFAULT_FILES, lockFile] // Match the monorepo's pinned pnpm so CNA's `pnpm install` doesn't drift to // whichever version corepack happens to fetch as "latest" at test time. const rootPac...
const projectName = 'use-pnpm' const res = await run( [ projectName, '--ts', '--app', '--use-pnpm', '--no-linter', '--no-src-dir', '--no-tailwind', '--no-im
{ nextTgzFilename = resolveNextTgzFilename() await command('corepack', ['prepare', '--activate', rootPackageManager]) }) it('should use pnpm for --use-pnpm flag', async () => { await useTempDir(async (cwd) => {
{ "filepath": "test/production/create-next-app/package-manager/pnpm.test.ts", "language": "typescript", "file_size": 4865, "cut_index": 614, "middle_length": 229 }
projectFilesShouldExist, } from '../utils' import { mapSrcFiles, projectSpecification } from '../lib/specification' import { projectDepsShouldBe } from '../lib/utils' function shouldBeApiTemplateProject({ cwd, projectName, mode, srcDir, }: { cwd: string projectName: string mode: 'js' | 'ts' srcDir?:...
ps: mapSrcFiles(projectSpecification[template][mode].devDeps, srcDir), }) } describe('create-next-app --api (Headless App)', () => { let nextTgzFilename: string beforeAll(() => { nextTgzFilename = resolveNextTgzFilename() }) it('should cre
sShouldBe({ type: 'dependencies', cwd, projectName, deps: mapSrcFiles(projectSpecification[template][mode].deps, srcDir), }) projectDepsShouldBe({ type: 'devDependencies', cwd, projectName, de
{ "filepath": "test/production/create-next-app/templates/app-api.test.ts", "language": "typescript", "file_size": 3302, "cut_index": 614, "middle_length": 229 }
pack } from 'next-test-utils' const isTurbopack = shouldUseTurbopack() // Each test runs a full create-next-app and (for `pages` templates) an // install, build, and start cycle. Webpack builds are slower than Turbopack // and can exceed the default 60-second per-test timeout, so give each matrix // test a generous t...
Running all 3 variants with // webpack pushes the total suite runtime past the 15-minute runner // timeout; Turbopack is fast enough to keep the full coverage. const importAliasValues = isTurbopack ? ['--import-alias=@acme/*', '--import-a
=> { nextTgzFilename = resolveNextTgzFilename() }) const isApp = pagesOrApp === 'app' // The `--import-alias` flag doesn't interact with the bundler, so under // webpack we only exercise a single variant.
{ "filepath": "test/production/create-next-app/templates/matrix.test.ts", "language": "typescript", "file_size": 3765, "cut_index": 614, "middle_length": 229 }
fined, keywords: undefined, referrer: undefined, themeColor: undefined, colorScheme: undefined, viewport: undefined, creator: undefined, publisher: undefined, robots: undefined, alternates: undefined, icons: undefined, manifest: undefined, openGraph: undefined, twitte...
name: undefined, }, themeColor: { color: '', media: undefined, }, viewport: { width: undefined, height: undefined, initialScale: undefined, minimumScale: undefined, maximumScale: undefined,
defined, archives: undefined, assets: undefined, bookmarks: undefined, category: undefined, classification: undefined, other: undefined, }) satisfies Metadata ;({ authors: { url: undefined,
{ "filepath": "test/production/typescript-basic/typechecking/metadata/metadata.ts", "language": "typescript", "file_size": 11644, "cut_index": 921, "middle_length": 229 }
pack internals (stats.json via webpack-bundle-analyzer). ;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)('Chunking', () => { const { next } = nextTestSetup({ files: __dirname, dependencies: { lodash: 'latest', 'webpack-bundle-analyzer': 'latest', }, }) let chunks: string[] l...
} it('should use all url friendly names', () => { expect(chunks).toEqual(chunks.map((name) => encodeURIComponent(name))) }) it('should create a framework chunk', () => { expect(existsChunkNamed('framework')).toBe(true) }) it('should n
stats = JSON.parse(statsRaw) chunks = fs.readdirSync(join(next.testDir, '.next', 'static', 'chunks')) }) const existsChunkNamed = (name: string) => { return chunks.some((chunk) => new RegExp(name).test(chunk))
{ "filepath": "test/production/chunking/chunking.test.ts", "language": "typescript", "file_size": 3224, "cut_index": 614, "middle_length": 229 }
import { join } from 'path' import { nextTestSetup } from 'e2e-utils' import { waitFor } from 'next-test-utils' describe('react-virtualized wrapping next/image', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipStart: true, skipDeployment: true, dependencies: { 'react-vi...
art() proxyChild = spawn( process.execPath, [join(next.testDir, 'server.js'), next.url, '0', '3000'], { stdio: ['ignore', 'pipe', 'inherit'] } ) proxyPort = await new Promise<number>((resolve, reject) => { let buf = ''
= await fetch(`http://localhost:${proxyPort}/_test/cancel-count`) const data = (await res.json()) as { cancelCount: number } return data.cancelCount } beforeAll(async () => { await next.build() await next.st
{ "filepath": "test/production/next-image-new/react-virtualized/react-virtualized.test.ts", "language": "typescript", "file_size": 2234, "cut_index": 563, "middle_length": 229 }
test relied on these being hoisted in the // monorepo root, but the isolated next install only sees declared deps. const postcssPluginDeps = { pixrem: '5.0.0', 'postcss-pseudoelements': '5.0.0', 'postcss-short-size': '4.0.0', 'postcss-trolling': '0.1.7', } describe('CSS Customization', () => { ;(process.env...
cessfully', () => { expect(next.cliOutput).toMatch(/Compiled successfully/) }) it(`should've compiled and prefixed`, async () => { const cssFolder = path.join(next.testDir, '.next/static/css') const files = a
name, 'css-fixtures/custom-configuration'), skipStart: true, dependencies: postcssPluginDeps, }) beforeAll(async () => { await next.build() }) it('should compile suc
{ "filepath": "test/production/css-customization/css-customization.test.ts", "language": "typescript", "file_size": 14220, "cut_index": 921, "middle_length": 229 }
getStaticProps() { // throw new Error('oops from getStaticProps') return { props: { world: 'world', time: new Date().getTime() }, } } const Page = ({ world, time }) => { return ( <> {/* <div id='after-change'>idk</div> */} <p>hello {world}</p> <span>time: {time}</span> <Link hr...
"/blog/[post]" as="/blog/post-1" id="post-1"> to dynamic </Link> <Link href="/blog/[post]" as="/blog/post-100" id="broken-post"> to broken </Link> <Link href="/blog/[post]" as="/blog/post-999"
other </Link> <br /> <Link href="/something" id="something"> to something </Link> <br /> <Link href="/normal" id="normal"> to normal </Link> <br /> <Link href=
{ "filepath": "test/production/prerender-export/pages/index.js", "language": "javascript", "file_size": 2810, "cut_index": 563, "middle_length": 229 }