prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true, dependencies: { firebase: 'latest', }, }) // TODO: investigate re-enabling this test in node 12 environment it.skip('Throws an error when building with firebase dependency with worker_threads', async () => { ...
/grpc_node\.node\. Module did not self-register\./ ) }) it('Throws no error when building with firebase dependency without worker_threads', async () => { await next.build() expect(next.cliOutput).not.toMatch(/Build error occurred/) ex
occurred/) expect(next.cliOutput).toMatch(
{ "filepath": "test/production/firebase-grpc/firebase-grpc.test.ts", "language": "typescript", "file_size": 995, "cut_index": 582, "middle_length": 52 }
res = await next.fetch('/') expect(res.status).toBe(404) const res2 = await next.fetch('/docs/node-pages') expect(res2.status).toBe(200) expect(await res2.text()).toContain('hello world') expect(next.cliOutput).toContain('called modify config in adapter') }) it('should call onBuildComplete w...
{ throw new Error( `Invalid dir value provided for ${field} value ${ctx[field]}` ) } } expect(ctx.nextVersion).toBe(nextVersion) expect(ctx.projectDir).toBe(next.testDir) expect(config?.basePath).toBe('/doc
dapter['onBuildComplete']>[0] = await next.readJSON( 'build-complete.json' ) for (const field of ['distDir', 'projectDir', 'repoRoot']) { expect(ctx[field]).toBeString() if (!fs.existsSync(ctx[field]))
{ "filepath": "test/production/adapter-config/adapter-config.test.ts", "language": "typescript", "file_size": 13963, "cut_index": 921, "middle_length": 229 }
ort { redirect, permanentRedirect, RedirectType } from 'next/navigation' import type { Route } from 'next' export default function Page() { function testRedirect() { // Invalid routes - these should cause type errors: redirect('/wrong-link') redirect('/blog/a?1/b') redirect(`/blog/${'a/b/c'}`) pe...
'}`) permanentRedirect('/external' as Route) // RedirectType should be correctly typed as literal types: redirect('/dashboard/another', RedirectType.replace) redirect('/about', RedirectType.push) permanentRedirect('/dashboard/user', Re
'/redirect') redirect(`/blog/${'a/b'}`) redirect('https://vercel.com') redirect('/invalid' as Route) permanentRedirect('/dashboard/user') permanentRedirect('/blog/a/b') permanentRedirect(`/dashboard/${'123
{ "filepath": "test/production/app-types/src/app/type-checks/redirect/page.tsx", "language": "tsx", "file_size": 1067, "cut_index": 515, "middle_length": 229 }
State, useEffect } from 'react' import unfetchImp from 'unfetch' import isomorphicUnfetchImp from 'isomorphic-unfetch' const testWhatwgFetchMethods = (whatWgFetch) => { return ( whatWgFetch.Headers.name === 'Headers' && whatWgFetch.Request.name === 'Request' && whatWgFetch.Response.name === 'Response' ...
chImp, isomorphicUnfetchReq].every( (lib) => lib.name === 'bound fetch' ) return areImportsMatching && testWhatwgFetchMethods(whatwgFetchReq) && testWhatwgFetchMethods(whatwgFetchImp) ? 'pass' : 'fail' } const Page = () => {
st isomorphicUnfetchReq = require('isomorphic-unfetch') let areImportsMatching = [whatwgFetchImp.fetch, whatwgFetchReq.fetch].every( (lib) => lib.name === 'fetch' ) && [unfetchImp, unfetchReq, isomorphicUnfet
{ "filepath": "test/production/polyfills/pages/fetch.js", "language": "javascript", "file_size": 1275, "cut_index": 524, "middle_length": 229 }
ort { nextTestSetup } from 'e2e-utils' import { join } from 'path' describe('Top Level Error', () => { describe('production mode', () => { describe('with getInitialProps', () => { const { next, skipped } = nextTestSetup({ files: join(__dirname, 'with-get-initial-props'), skipDeployment: tru...
iles: join(__dirname, 'without-get-initial-props'), skipDeployment: true, }) if (skipped) return it('should render error page', async () => { const browser = await next.browser('/') const text = await browser.wait
r.waitForElementByCss('#error-p').text() expect(text).toBe('Error Rendered with: top level error') }) }) describe('without getInitialProps', () => { const { next, skipped } = nextTestSetup({ f
{ "filepath": "test/production/render-error-on-top-level-error/render-error-on-top-level-error.test.ts", "language": "typescript", "file_size": 1103, "cut_index": 515, "middle_length": 229 }
retry } from 'next-test-utils' describe('allow-development-build', () => { describe('with NODE_ENV set to development', () => { const { next } = nextTestSetup({ files: __dirname, env: { NODE_ENV: 'development', }, nextConfig: { experimental: { allowDevelopmentBui...
nsoleLog: true, }) await retry(async () => { const logs = await browser.log() const errorLogs = logs.filter((log) => log.source === 'error') expect(errorLogs).toEqual( expect.arrayContaining([
in your environment' ) }) it.each(['app-page', 'pages-page'])( `should show React development errors in %s`, async (page) => { const browser = await next.browser(page, { pushErrorAsCo
{ "filepath": "test/production/allow-development-build/allow-development-build.test.ts", "language": "typescript", "file_size": 2529, "cut_index": 563, "middle_length": 229 }
('ci-missing-typescript-deps', () => { describe('missing typescript dep', () => { const { next } = nextTestSetup({ files: { 'pages/index.tsx': ` export default function Page() { return <p>hello world</p> } `, }, env: { CI: '1', }, ...
ge(s) installed.` ) expect(next.cliOutput).toContain(`Please install`) expect(next.cliOutput).not.toContain('Call retries were exceeded') expect(next.cliOutput).not.toContain('WorkerError') }) }) describe('with @types/react
await next.start().catch((err) => { error = err }) expect(error).toBeDefined() expect(next.cliOutput).toContain( `It looks like you're trying to use TypeScript but do not have the required packa
{ "filepath": "test/production/ci-missing-typescript-deps/index.test.ts", "language": "typescript", "file_size": 2168, "cut_index": 563, "middle_length": 229 }
port { nextTestSetup } from 'e2e-utils' describe('Errors on output to public', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true, }) it('Throws error when `distDir` is set to public', async () => { await next.patchFile( 'next.config.js', `module.exports = { distD...
t next.patchFile( 'next.config.js', `module.exports = { distDir: 'public', output: 'export' }` ) await next.build() expect(next.cliOutput).toMatch( /The 'public' directory is reserved in Next\.js and can not be/ ) }) })
en export out dir is public', async () => { awai
{ "filepath": "test/production/errors-on-output-to-public/errors-on-output-to-public.test.ts", "language": "typescript", "file_size": 823, "cut_index": 514, "middle_length": 52 }
. to test // type-error reporting. Under Cache Components the build aborts up front // with an incompatibility error before TS errors can be collected, so the // entire suite is skipped — `describe.skip` also prevents `nextTestSetup` // hooks from firing, so the failing build never runs. ;(process.env.__NEXT_CACHE_COMP...
'skipped for non-start mode', () => {}) return } let errors: string | undefined beforeAll(async () => { await next.build() const stderr = next.cliOutput errors = stderr.match( /===== TS errors =====(.+)===== T
kipStart: true, dependencies: { '@next/mdx': 'latest', '@mdx-js/loader': 'latest', '@mdx-js/react': 'latest', }, packageJson: { type: 'module' }, }) if (!isNextStart) { it(
{ "filepath": "test/production/app-types/app-types.test.ts", "language": "typescript", "file_size": 4808, "cut_index": 614, "middle_length": 229 }
from 'e2e-utils' describe('Dynamic Code Evaluation (DCE)', () => { const { next } = nextTestSetup({ skipStart: true, dependencies: { 'function-bind': 'latest' }, files: __dirname, }) // This test is basically for https://github.com/vercel/next.js/discussions/51910 // to make sure that some libs th...
Edge Runtime` ) }) ;(process.env.IS_TURBOPACK_TEST ? it.skip : it)( "should show the user's import trace", async () => { await next.patchFile( 'middleware.js', ` import { foo } from './lib/foo' export funct
() => { const { exitCode, cliOutput } = await next.build() expect(exitCode).toBe(0) expect(cliOutput).not.toContain( `Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in
{ "filepath": "test/production/edge-dynamic-code-eval/index.test.ts", "language": "typescript", "file_size": 1629, "cut_index": 537, "middle_length": 229 }
library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library...
s is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. Thi
{ "filepath": "test/production/remove-unused-imports/library/a.js", "language": "javascript", "file_size": 7212, "cut_index": 716, "middle_length": 229 }
fetchViaHTTP } from 'next-test-utils' import path from 'path' const files = { 'pages/index.js': ` export default function Page() { return <p>hello world</p> } `, 'middleware.js': ` import { NextResponse } from 'next/server' if (typeof EdgeRuntime === 'undefined') { console.log("EdgeR...
me is addressable', () => { const { next } = nextTestSetup({ files, dependencies: {}, }) test('EdgeRuntime evaluates to a string', async () => { const resp = await fetchViaHTTP(next.url, '/') expect(await resp.text()).toContain('hell
ersion': EdgeRuntime, 'x-runtime-version-dynamic': getDynamicRuntimeVersion(self) } }) } function getDynamicRuntimeVersion(from) { return from.EdgeRuntime; } `, } describe('Edge Runti
{ "filepath": "test/production/edge-runtime-is-addressable/index.test.ts", "language": "typescript", "file_size": 2428, "cut_index": 563, "middle_length": 229 }
{ nextTestSetup } from 'e2e-utils' // This isolated test installs extra dependencies (`lost`, `postcss-nested`, // `styled-jsx-plugin-postcss`) and a custom .babelrc.js disables SWC, which // makes the isolated install + `next build` much slower than the default 120s // jest beforeAll timeout. jest.setTimeout(10 * 60...
d on postcss 6 and a `deasync` native addon that deadlocks // inside Next.js's webpack build worker on modern Node.js. lost: '9.0.2', 'postcss-nested': '7.0.2', 'styled-jsx-plugin-postcss': '4.0.1', }, }) it('
= nextTestSetup({ files: __dirname, dependencies: { // Use versions compatible with postcss 8. Older pinned versions // (`lost@8`, `postcss-nested@2`, `styled-jsx-plugin-postcss@0.1`) // depen
{ "filepath": "test/production/styled-jsx-plugin/styled-jsx-plugin.test.ts", "language": "typescript", "file_size": 1148, "cut_index": 518, "middle_length": 229 }
zMHokF ahIj2X9CszHvqenAJtkglLuRbTaPWaUBdxkOg82FMvWKzobG1uOQXcI84oM2Tb9dB814fuoumn8cUrlpjXFclIm3wGQSamyD9ijoJb874PLmnyBg6ZBilHy0DcuZeM1zKnpxeOw570khLruHBtuB2mpMdquHa7gD BgAzWiGhklzq5Du3K013uI9RvOj1onIukVJWUtjyvz1s9wb19neRhHKtwOzaGeFwV2Rwfez4F4TOGwH7I6f2m188846jyALueDqzpz2ZUE8R0iWfPtjn7IQElGodcz0dyNb9jzmfu6QlMmrMnr07kxdH...
p2dwdXmGGCKcrSXAgDw8ium7cFvGB6KlZCDEOC0sYlHlWItL3DE2TENt6ukvsQdHLbiU3P AeCs4RSVNIYDVh8lryN1m4saCYQ5WOgtNnTTj43K6Aqq77LIlD0mCaQRVsadKNztN8iXvVLq9g5fWjIif6PB1mo26ikofbGXC1mHos6iQUtt5JAdwlPMnLZz7cZAt3mhYlFEfZU2CHpkbkZ7dkBWZ5rTQqdrebjY s5dneb7rtmYRlVQygRRwzH9z
0dgIaXVvvLFLY6EMy2kIzyIgYETznAgHQkI0MdhgEngH9RzqJuehKjexjhaDtmx1aPfdyP7CUPf5mobiFiOuhGDF59TW3VEfL5xIbx3m5HhT5bWskdxggQ1PstHc6lGatfQPAaWNtl Cgo7R44Ns1naFmfEul3mHoHiq7qvK2jjnNrzLO3ubb6yEuOwml6lO2ddS0a6z9BHMo7YMa0DCGeaqWbdfKXVFqzBhO
{ "filepath": "test/production/bundle-size/app/app/client.js", "language": "javascript", "file_size": 4984, "cut_index": 614, "middle_length": 229 }
eturn data.nextDataRequests } async function resetDataRequests() { await fetch(`http://localhost:${proxyPort}/_test/data-requests/reset`) } async function setStall(on: boolean) { await fetch( `http://localhost:${proxyPort}/_test/stall/${on ? 'on' : 'off'}` ) } beforeAll(async () => { ...
toString() const m = buf.match(/__PORT__:(\d+)/) if (m) { proxyChild.stdout!.off('data', onData) resolve(Number(m[1])) } } proxyChild.stdout!.on('data', onData) proxyChild.once('exit', (code) =>
erver.js'), next.url, '0'], { stdio: ['ignore', 'pipe', 'inherit'] } ) proxyPort = await new Promise<number>((resolve, reject) => { let buf = '' const onData = (chunk: Buffer) => { buf += chunk.
{ "filepath": "test/production/preload-viewport/preload-viewport.test.ts", "language": "typescript", "file_size": 18917, "cut_index": 1331, "middle_length": 229 }
tures</h1> <p> <Link href="/ssg/dynamic/[slug]?slug=one" as="/ssg/fixture/mismatch"> Dynamic Route (one level) — Prerendered </Link> : this is a Dynamic Page with a single dynamic segment that{' '} <strong>was returned</strong> from <code>getStaticPaths</code>.<br /> <Link href...
}, }} as="/ssg/fixture/mismatch" > Multi Dynamic Route (two levels) — Prerendered </Link> : this is a Dynamic Page with two dynamic segments that{' '} <strong>were returned</strong> from <code>getStaticPaths<
' '} <strong>was not returned</strong> from <code>getStaticPaths</code>. </p> <p> <Link href={{ pathname: '/ssg/dynamic-nested/[slug1]/[slug2]', query: { slug1: 'one', slug2: 'two'
{ "filepath": "test/production/preload-viewport/pages/ssg/fixture/mismatch.js", "language": "javascript", "file_size": 3066, "cut_index": 614, "middle_length": 229 }
from 'path' import { FileRef, nextTestSetup } from 'e2e-utils' // Reproduces https://github.com/vercel/next.js/issues/93336 describe('typescript paths with deprecated, inherited baseUrl', () => { const fixtureDir = path.join(__dirname, 'fixtures/inherited') const { skipped, next } = nextTestSetup({ files: { ...
(fixtureDir, 'web/tsconfig.json')), app: new FileRef(path.join(fixtureDir, 'web/app')), }, subDir: 'web', dependencies: { // Specifically testing compilerOptions that were deprecated in 6.0. // This test would fail in 7.0
e.json') ), '../packages': new FileRef(path.join(fixtureDir, 'packages')), 'next.config.js': new FileRef( path.join(fixtureDir, 'web/next.config.js') ), 'tsconfig.json': new FileRef(path.join
{ "filepath": "test/production/typescript-paths-baseUrl/typescript-paths-baseUrl-inherited.test.ts", "language": "typescript", "file_size": 1315, "cut_index": 524, "middle_length": 229 }
ort { Writable } from 'stream' import path from 'path' import crypto from 'crypto' import { Buffer } from 'buffer' import vm from 'vm' import { useEffect, useState } from 'react' export default function NodeBrowserPolyfillPage() { const [state, setState] = useState({}) useEffect(() => { let closedStream = fals...
runInNewContext('a + 5', { a: 100 }), stream: closedStream, }) }, []) useEffect(() => { if (state.vm) { window.didRender = true } }, [state]) return ( <> <div id="node-browser-polyfills" dangerous
itable.end() setState({ path: path.join('/hello/world', 'test.txt'), hash: crypto.createHash('sha256').update('hello world').digest('hex'), buffer: Buffer.from('hello world').toString('utf8'), vm: vm.
{ "filepath": "test/production/pages-dir/production/fixture/pages/node-browser-polyfills.js", "language": "javascript", "file_size": 1079, "cut_index": 515, "middle_length": 229 }
rCondition(`!!window.next.router.isReady`) await browser.forward() await browser.waitForElementByCss('.about-page') }) if (process.env.BROWSER_NAME !== 'safari') { it.each([ { hash: '#hello?' }, { hash: '#?' }, { hash: '##' }, { hash: '##?' }, { hash: '##hello?' }, {...
er(`/${search || ''}${hash || ''}`) await check( () => browser.eval('window.next.router.isReady ? "ready" : "not ready"'), 'ready' ) expect(await browser.eval('window.location.pathname')).toBe('/')
{ search: '?hello=', hash: '#a', query: { hello: '' } }, ])( 'should handle query/hash correctly during query updating $hash $search', async ({ hash, search, query }) => { const browser = await next.brows
{ "filepath": "test/production/pages-dir/production/test/index.test.ts", "language": "typescript", "file_size": 42356, "cut_index": 2151, "middle_length": 229 }
ring every 500ms async function checkInjected(browser) { const start = Date.now() while (Date.now() - start < 5000) { const bodyText = await getBrowserBodyText(browser) if (/INJECTED/.test(bodyText)) { throw new Error('Vulnerable to XSS attacks') } await waitFor(500) } } export default (nex...
resolve(response.statusCode) } ) request.on('error', (err) => reject(err)) request.end() }) } try { expect(await invalidRequest()).toBe(400) expect(await invalidRequ
new Promise((resolve, reject) => { const request = http.request( { hostname: `localhost`, port: next.appPort, path: `*`, }, (response) => {
{ "filepath": "test/production/pages-dir/production/test/security.ts", "language": "typescript", "file_size": 10509, "cut_index": 921, "middle_length": 229 }
tSetup } from 'e2e-utils' import { findAllTelemetryEvents } from 'next-test-utils' import { join } from 'path' const mockedGoogleFontResponses = require.resolve( './google-font-mocked-responses.js' ) // Turbopack intentionally does not support these events ;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)...
tryEvents( next.cliOutput, 'NEXT_BUILD_FEATURE_USAGE' ) expect(events).toContainEqual({ featureName: 'next/font/google', invocationCount: 1, }) expect(events).toContainEqual({ featureName: 'ne
_FONT_GOOGLE_MOCKED_RESPONSES: mockedGoogleFontResponses, NEXT_TELEMETRY_DEBUG: '1', }, }) it('should send next/font/google and next/font/local usage event', async () => { const events = findAllTeleme
{ "filepath": "test/production/next-font/telemetry.test.ts", "language": "typescript", "file_size": 1961, "cut_index": 537, "middle_length": 229 }
TOM_DEPLOYMENT_ID', ''], ['NEXT_DEPLOYMENT_ID', ' and runtimeServerDeploymentId'], ['NEXT_DEPLOYMENT_ID_IMMUTABLE', ''], ])( 'deployment-id-handling enabled with %s%s', (envKey, runtimeServerDeploymentId) => { if ( envKey === 'NEXT_DEPLOYMENT_ID_IMMUTABLE' && !process.env.IS_TURBOPACK_TEST )...
ndefined, }, disableAutoSkewProtection: true, }) const validateTokenForRequest = (url: string) => { const token = url.includes('/_next/static/immutable/') ? // Turbopack-emitted chunks immutableAssetToken
: deploymentId const { next } = nextTestSetup({ files: join(__dirname, 'app'), env: { [envKey]: deploymentId, RUNTIME_SERVER_DEPLOYMENT_ID: runtimeServerDeploymentId ? '1' : u
{ "filepath": "test/production/deployment-id-handling/deployment-id-handling.test.ts", "language": "typescript", "file_size": 7963, "cut_index": 716, "middle_length": 229 }
statSync } from 'fs' import { join } from 'path' // TODO: Implement experimental.fallbackNodePolyfills ;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)( 'Disable fallback polyfills', () => { async function getIndexPageSize() { // Read build manifest to get chunk files for the index page ...
stDir, '.next', chunkPath) try { const stats = statSync(fullChunkPath) totalSize += stats.size } catch (error) { console.warn(`Could not read chunk: ${chunkPath}`, error.message) } } // Con
indexPageChunks = buildManifest.pages['/'] || [] // Calculate total size of all chunks for the index page let totalSize = 0 for (const chunkPath of indexPageChunks) { const fullChunkPath = join(next.te
{ "filepath": "test/production/disable-fallback-polyfills/index.test.ts", "language": "typescript", "file_size": 3018, "cut_index": 563, "middle_length": 229 }
tTurbopack } from 'e2e-utils' describe('route-bundle-stats', () => { const { next, isNextDeploy } = nextTestSetup({ files: __dirname, }) if (isNextDeploy) { it('should skip', () => {}) return } const STATS_PATH = '.next/diagnostics/route-bundle-stats.json' itTurbopack( 'writes .next/diag...
JsBytes).toBe('number') expect(entry.firstLoadUncompressedJsBytes).toBeGreaterThan(0) expect(Array.isArray(entry.firstLoadChunkPaths)).toBe(true) expect(entry.firstLoadChunkPaths.length).toBeGreaterThan(0) for (const chunkP
rue) expect(stats.length).toBeGreaterThan(0) for (const entry of stats) { expect(typeof entry.route).toBe('string') expect(entry.route).toMatch(/^\//) expect(typeof entry.firstLoadUncompressed
{ "filepath": "test/production/route-bundle-stats/route-bundle-stats.test.ts", "language": "typescript", "file_size": 1694, "cut_index": 537, "middle_length": 229 }
utils' describe('Promise in next config', () => { ;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)( 'production mode', () => { const { next, isNextStart } = nextTestSetup({ files: __dirname, skipStart: true, }) if (!isNextStart) { it('skipped for non-star...
return { webpack: async (config) => { return config } } } ` ) await next.build() expect(next.cliOutput).toMatch( /> Promise returned in next config\. ht
module.exports = (phase, { isServer }) => {
{ "filepath": "test/production/config-promise-error/config-promise-error.test.ts", "language": "typescript", "file_size": 897, "cut_index": 547, "middle_length": 52 }
t path from 'path' import { nextTestSetup } from 'e2e-utils' describe('build trace with extra entries in monorepo', () => { describe('production mode', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipStart: true, skipDeployment: true, }) if (skipped) return ...
ect(exitCode).toBe(0) const appDirRoute1Trace = JSON.parse( await next.readFile('app/.next/server/app/route1/route.js.nft.json') ) expect(appDirRoute1Trace.files).toContain( '../../../../../other/included.txt' )
}) exp
{ "filepath": "test/production/build-trace-extra-entries-monorepo/build-trace-extra-entries-monorepo.test.ts", "language": "typescript", "file_size": 800, "cut_index": 517, "middle_length": 14 }
tTestSetup } from 'e2e-utils' describe('static-404', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true, }) it('should export 404 page without custom _error', async () => { await next.build() await next.start() const html = await next.render('/non-existent') await...
throw new Error('exported 404 unexpectedly!!!') } return { statusCode, } } } ` ) await next.build() await next.deleteFile('pages/_error.js') }) it('sh
ror.js', ` import Error from 'next/error' export default class MyError extends Error { static getInitialProps({ statusCode, req }) { if (req.url === '/404' || req.url === '/404.html') {
{ "filepath": "test/production/static-404/static-404.test.ts", "language": "typescript", "file_size": 1434, "cut_index": 524, "middle_length": 229 }
beforeAll(async () => { await next.build() await next.deleteFile('pages') requiredFilesManifest = await next.readJSON( join('.next/required-server-files.json') ) let files = await fs.readdir(join(next.testDir, '.next')) for (const file of files) { ...
let nextApp = nextServer({ conf: {}, dir: next.testDir, quiet: false, minimalMode: true, }) // @ts-expect-error server = await startApp(nextApp) // @ts-expect-error ap
xt', file)) ) { continue } console.log('removing', join('.next', file)) await next.deleteFile(join('.next', file)) } process.env.NEXT_PRIVATE_TEST_HEADERS = '1'
{ "filepath": "test/production/required-server-files-ssr-404/test/index.test.ts", "language": "typescript", "file_size": 23509, "cut_index": 1331, "middle_length": 229 }
t * as React from 'react' import type { Route } from 'next' import Form from 'next/form' export default function Page() { const invalidRoutes = ( <> <Form action="/wrong-link"></Form> <Form action="/blog/a?1/b"></Form> <Form action={`/blog/${'a/b/c'}`}></Form> </> ) const validRoutes =...
id' as Route}></Form> <Form action={async (formData) => { 'use server' console.log('function action', formData.get('myInput')) }} ></Form> </> ) return ( <> {invalidRoutes} {validRout
ction={'/inval
{ "filepath": "test/production/app-types/src/app/type-checks/form/page.tsx", "language": "tsx", "file_size": 805, "cut_index": 517, "middle_length": 14 }
( <main> <h1>SSG Data Prefetch Fixtures</h1> <p> <Link href="/ssg/basic">Non-dynamic route</Link>: this is a normal Next.js page that does not use dynamic routing. </p> <p> <Link href="/ssg/dynamic/[slug]" as="/ssg/dynamic/one"> Dynamic Route (one level) — Prerendered <...
ode>. </p> <p> <Link href="/ssg/dynamic-nested/[slug1]/[slug2]" as="/ssg/dynamic-nested/one/two" > Multi Dynamic Route (two levels) — Prerendered </Link> : this is a Dynamic Page with two dynamic segm
as="/ssg/dynamic/two"> Dynamic Route (one level) — Not Prerendered </Link> : this is a Dynamic Page with a single dynamic segment that{' '} <strong>was not returned</strong> from <code>getStaticPaths</c
{ "filepath": "test/production/preload-viewport/pages/ssg/fixture/index.js", "language": "javascript", "file_size": 2621, "cut_index": 563, "middle_length": 229 }
{ Component } from 'react' import Router from 'next/router' let counter = 0 export default class extends Component { increase() { counter++ this.forceUpdate() } visitQueryStringPage() { const href = { pathname: '/nav/querystring', query: { id: 10 } } const as = { pathname: '/nav/querystring/10...
" prefetch id="no-such-page-prefetch"> No Such Page (with prefetch) </Link> <p>This is the home.</p> <div id="counter">Counter: {counter}</div> <button id="increase" onClick={() => this.increase()}> Incre
nk> <br /> <Link href="/no-such-page
{ "filepath": "test/production/pages-dir/production/fixture/pages/counter.js", "language": "javascript", "file_size": 902, "cut_index": 547, "middle_length": 52 }
sFromBuildManifest } from 'next-test-utils' import { NextInstance } from 'e2e-utils' import path from 'node:path' import fs from 'fs-extra' export default (next: NextInstance) => { describe('process.env', () => { it('should set process.env.NODE_ENV in production', async () => { const browser = await next.b...
ect(allClientCodeForPage).toMatch( /__THIS_SHOULD_ONLY_BE_DEFINED_IN_BROWSER_CONTEXT__/ ) expect(allClientCodeForPage).not.toMatch( /__THIS_SHOULD_ONLY_BE_DEFINED_IN_SERVER_CONTEXT__/ ) }) it('should eliminate cli
s.browser', () => { it('should eliminate server only code on the client', async () => { const allClientCodeForPage = getContentOfPageFilesFromBuildManifest( next.testDir, '/process-env' ) exp
{ "filepath": "test/production/pages-dir/production/test/process-env.ts", "language": "typescript", "file_size": 2409, "cut_index": 563, "middle_length": 229 }
from 'e2e-utils' import { retry } from 'next-test-utils' import { join } from 'node:path' describe('deployment-id-handling disabled', () => { const deploymentId = Date.now() + '' const { next } = nextTestSetup({ files: join(__dirname, 'app'), env: { COOKIE_SKEW: '1', NEXT_DEPLOYMENT_ID: 'thanky...
nd dpl query to all assets for $urlPath', async ({ urlPath }) => { const $ = await next.render$(urlPath) expect($('#deploymentId').text()).not.toBe(deploymentId) const scripts = Array.from($('script')) expect(scripts.length).t
okie')).toBe( '__vdpl=thankyounext; Path=/; HttpOnly' ) }) it.each([ { urlPath: '/' }, { urlPath: '/pages-edge' }, { urlPath: '/from-app' }, { urlPath: '/from-app/edge' }, ])( 'should not appe
{ "filepath": "test/production/deployment-id-handling/deployment-id-cookie-handling.test.ts", "language": "typescript", "file_size": 1950, "cut_index": 537, "middle_length": 229 }
nextTestSetup } from 'e2e-utils' import { join } from 'path' describe('app-dir-hide-suppressed-error-during-next-export', () => { const { next } = nextTestSetup({ skipStart: true, files: { 'next.config.js': new FileRef(join(__dirname, 'next.config.js')), app: new FileRef(join(__dirname, 'app')),...
Output).toInclude('occurred prerendering page "/"') expect(next.cliOutput).toInclude('Export encountered errors on 1 path') expect(next.cliOutput).not.toInclude( 'The specific message is omitted in production builds to avoid leaking sensitive
Include('Page build time error') expect(next.cli
{ "filepath": "test/production/app-dir-hide-suppressed-error-during-next-export/index.test.ts", "language": "typescript", "file_size": 862, "cut_index": 529, "middle_length": 52 }
tSetup } from 'e2e-utils' import { join } from 'path' describe('fallback export error', () => { const { next } = nextTestSetup({ files: { pages: new FileRef(join(__dirname, 'pages')), }, nextConfig: { output: 'export', }, skipStart: true, }) it('should have built', async () => { ...
await next.patchFile( 'next.config.js', ` module.exports = { output: 'export', exportPathMap() { return { '/': { page: '/' }, } } } ` ) try { const result
ole.log(result.cliOutput) expect(result.exitCode).toBe(0) expect(result.cliOutput).not.toContain( 'Found pages with `fallback` enabled' ) }) it('should not error with valid exportPathMap', async () => {
{ "filepath": "test/production/fallback-export-error/index.test.ts", "language": "typescript", "file_size": 1932, "cut_index": 537, "middle_length": 229 }
tSetup } from 'e2e-utils' import { check, renderViaHTTP, waitFor } from 'next-test-utils' import { join } from 'path' describe('fatal-render-error', () => { const { next } = nextTestSetup({ files: new FileRef(join(__dirname, 'app')), dependencies: {}, }) it('should render page without error correctly', ...
ser.eval('window.renderAttempts')).toBeLessThan(10) const html = await browser.eval('document.documentElement.innerHTML') expect(html).not.toContain('from _app') expect(html).toContain( 'Application error: a client-side exception has occ
and _error without loop on direct visit', async () => { const browser = await next.browser('/with-error') // wait a bit to see if we are rendering multiple times unexpectedly await waitFor(500) expect(await brow
{ "filepath": "test/production/fatal-render-error/index.test.ts", "language": "typescript", "file_size": 1771, "cut_index": 537, "middle_length": 229 }
rom 'next/dist/compiled/gzip-size' describe('bundle-size', () => { const { next } = nextTestSetup({ files: __dirname, }) // TODO bring these numbers down for Turbopack, especially the softnav one // TODO these numbers simply change too often right now const BASE_SIZES = { pages: undefined, // proces...
.env.IS_TURBOPACK_TEST ? 12_000 : 500, }, { title: 'App Router: between RSC-only identical pages', from: '/app/a', to: '/app/b', fromInitialJs: BASE_SIZES.app, toInitialJs: BASE_SIZES.app, softNavJs: process.env.
0_000, } it.each([ { title: 'Pages Router: between identical pages', from: '/pages/a', to: '/pages/b', fromInitialJs: BASE_SIZES.pages, toInitialJs: BASE_SIZES.pages, softNavJs: process
{ "filepath": "test/production/bundle-size/bundle-size.test.ts", "language": "typescript", "file_size": 4110, "cut_index": 614, "middle_length": 229 }
d by preload-viewport.test.ts. The script lives 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 `_test/data-requests` and `_test/stall` endpoints. const http = require('http') const http...
ntent-type', 'application/json') res.end(JSON.stringify({ nextDataRequests })) return } if (req.url === '/_test/data-requests/reset') { nextDataRequests.length = 0 res.end('ok') return } if (req.url === '/_test/stall/on') {
1) } let stallJs = false const nextDataRequests = [] const proxy = httpProxy.createProxyServer({ target }) const server = http.createServer(async (req, res) => { if (req.url === '/_test/data-requests') { res.setHeader('co
{ "filepath": "test/production/preload-viewport/server.js", "language": "javascript", "file_size": 1594, "cut_index": 537, "middle_length": 229 }
als with esmExternals: 'loose'", () => { ;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)( 'production mode', () => { const { next, isNextStart } = nextTestSetup({ files: __dirname, }) if (!isNextStart) { it('skipped for non-start mode', () => {}) return ...
xpected) }) it('should render the ssr page', async () => { const html = await next.render('/ssr') expect(html).toMatch(expected) }) it('should render the ssg page', async () => { const html = await next.ren
ext.render('/static') expect(html).toMatch(e
{ "filepath": "test/production/externals-esm-loose/externals-esm-loose.test.ts", "language": "typescript", "file_size": 963, "cut_index": 582, "middle_length": 52 }
eerio from 'cheerio' describe('Export with next/legacy/image component', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true, }) afterEach(async () => { await next.patchFile( 'next.config.js', '// prettier-ignore\nmodule.exports = { /* replaceme */ }\n' ) a...
lace( '{ /* replaceme */ }', JSON.stringify({ output: 'export', images: { loader: 'cloudinary', path: 'https://example.com/', }, }) ) ) const { exitCode } = await n
<Image alt="icon" src="/i.png" width="10" height="10" loader={loader} /> </div> ) ` ) }) it('should build with cloudinary loader', async () => { await next.patchFile('next.config.js', (content) => content.rep
{ "filepath": "test/production/export-image-loader-legacy/export-image-loader-legacy.test.ts", "language": "typescript", "file_size": 2993, "cut_index": 563, "middle_length": 229 }
ig#exportTrailingSlash set to false', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true, }) beforeAll(async () => { await next.build() }) it('should export pages as [filename].html instead of [filename]/index.html', async () => { expect(await next.hasFile('out/index....
'out/index.html') const $ = cheerio.load(html) expect($('p').text()).toBe('I am a home page') const htmlSingle = await next.readFile('out/posts/single.html') const $single = cheerio.load(htmlSingle) expect($single('p').text()).toBe('I
)).toBe(true) const html = await next.readFile(
{ "filepath": "test/production/export-subfolders/export-subfolders.test.ts", "language": "typescript", "file_size": 941, "cut_index": 606, "middle_length": 52 }
lt (next: NextInstance, render) => { async function get$(path: string, query?: any) { const html = await render(path, query) return cheerio.load(html) } describe('Dynamic import', () => { describe('default behavior', () => { it('should render dynamic import components', async () => { con...
r css files', async () => { const $ = await get$('/dynamic/many-dynamic-css') const cssFiles = $('link[rel=stylesheet]') expect(cssFiles.length).toBe(3) }) it('should bundle two css modules for one dynamically imported
() => { const $ = await get$('/dynamic/css') const cssFiles = $('link[rel=stylesheet]') expect(cssFiles.length).toBe(1) }) it('should render three dynamically imported components and load thei
{ "filepath": "test/production/pages-dir/production/test/dynamic.ts", "language": "typescript", "file_size": 5971, "cut_index": 716, "middle_length": 229 }
from 'e2e-utils' import { check, renderViaHTTP } from 'next-test-utils' describe('custom-error-500', () => { const { next } = nextTestSetup({ files: { 'pages/index.js': ` export function getServerSideProps() { throw new Error('custom error') } export default funct...
Error.getInitialProps = ({ err }) => { console.log(\`called Error.getInitialProps \${!!err}\`) return { hasError: !!err } } export default Error `, }, dependencies
s/500</p> </> ) } `, 'pages/_error.js': ` function Error({ hasError }) { return ( <> <p>/_error</p> </> ) }
{ "filepath": "test/production/custom-error-500/index.test.ts", "language": "typescript", "file_size": 1736, "cut_index": 537, "middle_length": 229 }
ort path from 'path' import { nextTestSetup } from 'e2e-utils' describe('build with proxy trace', () => { describe('production mode', () => { const { next, skipped } = nextTestSetup({ files: path.join(__dirname, 'app'), skipStart: true, skipDeployment: true, }) if (skipped) return ...
puts).toStrictEqual(['dist/**', '!dist/cache/**']) expect(accessTrace.accessed.envVarKeys).toBeArray() expect(accessTrace.accessed.envVarKeys).toContain( 'SSG_ROUTE_ENV_VAR_HEADER_TEXT' ) expect(accessTrace.accessed.network)
SSG_ROUTE_ENV_VAR_HEADER_TEXT: 'Welcome', }, }) expect(exitCode).toBe(0) const accessTrace = JSON.parse( await next.readFile('.turbo/turborepo-trace.json') ) expect(accessTrace.out
{ "filepath": "test/production/turborepo-access-trace/turborepo-access-trace.test.ts", "language": "typescript", "file_size": 1085, "cut_index": 515, "middle_length": 229 }
m from 'resolve-from' import { nextTestSetup } from 'e2e-utils' type File = { filename: string content: string } const appDirFiles: File[] = [ { filename: 'app/page.js', content: ` export default function Page() { return <p>hello world</p> } `, }, { filename: 'app/layout.js', ...
next } = nextTestSetup({ skipStart: true, files: {}, dependencies: { 'node-pty': '0.10.1', }, packageJson: { pnpm: { onlyBuiltDependencies: ['node-pty'], }, }, }) beforeEach(async () => { await fs
t pagesFiles: File[] = [ { filename: 'pages/another.js', content: ` export default function Page() { return ( <p>another page</p> ) } `, }, ] describe('build-spinners', () => { const {
{ "filepath": "test/production/build-spinners/index.test.ts", "language": "typescript", "file_size": 4392, "cut_index": 614, "middle_length": 229 }
Setup } from 'e2e-utils' describe('config validation - warnings only', () => { const { next } = nextTestSetup({ skipStart: true, files: __dirname, }) it('should show warnings but not block the build', async () => { const { exitCode, cliOutput } = await next.build() // Build should succeed e...
ption'" ) expect(cliOutput).toContain('at "experimental"') // Should NOT show fatal error message expect(cliOutput).not.toContain('Fatal next config errors') // Build should complete successfully expect(cliOutput).toContain('Compi
bject: 'unknownExperimentalOption', 'anotherUnknownO
{ "filepath": "test/production/config-validation-warnings/index.test.ts", "language": "typescript", "file_size": 864, "cut_index": 529, "middle_length": 52 }
"next-env.d.ts", "**/*.mts", "**/*.ts", "**/*.tsx" ], "exclude": [ "node_modules" ] } " `) } else { expect(await next.readFile('tsconfig.json')).toMatchInlineSnapshot(` "{ ...
solution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react-jsx", "plugins": [ { "name": "next" } ], "s
: true, "skipLibCheck": true, "strict": false, "noEmit": true, "incremental": true, "module": "esnext", "esModuleInterop": true, "moduleRe
{ "filepath": "test/production/tsconfig-verifier/tsconfig-verifier.test.ts", "language": "typescript", "file_size": 34761, "cut_index": 2151, "middle_length": 229 }
from 'e2e-utils' import { retry } from 'next-test-utils' describe('error-hydration', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should not log server-side errors', async () => { const browser = await next.browser('/with-error') const messages = await browser.log() expect(...
as any).__ERROR_PAGE_GET_INITIAL_PROPS_INVOKED_CLIENT_SIDE__ ) ).toBe(undefined) }) it('should log a message for client-side errors, including the full, custom error', async () => { const browser = await next.browser('/no-error') awa
it('should not invoke the error page getInitialProps client-side for server-side errors', async () => { const browser = await next.browser('/with-error') expect( await browser.eval( () => (window
{ "filepath": "test/production/error-hydration/error-hydration.test.ts", "language": "typescript", "file_size": 1913, "cut_index": 537, "middle_length": 229 }
tries', () => { describe('production mode', () => { const { next, isNextStart, isTurbopack } = nextTestSetup({ files: path.join(__dirname, 'app'), skipStart: true, }) if (!isNextStart || isTurbopack) { it('skipped for non-start or turbopack mode', () => {}) return } it('s...
t/server/pages/another.js.nft.json') ) const imageTrace = JSON.parse( await next.readFile('.next/server/pages/image-import.js.nft.json') ) const appDirRoute1Trace = JSON.parse( await next.readFile('.next/server/app/r
ext/server/pages/_app.js.nft.json') ) const indexTrace = JSON.parse( await next.readFile('.next/server/pages/index.js.nft.json') ) const anotherTrace = JSON.parse( await next.readFile('.nex
{ "filepath": "test/production/build-trace-extra-entries/build-trace-extra-entries.test.ts", "language": "typescript", "file_size": 4876, "cut_index": 614, "middle_length": 229 }
Output', () => { describe('Default Export', () => { const { next } = nextTestSetup({ files: path.join(__dirname, 'fixtures/default-export'), skipStart: true, }) it('should build and have expected export outputs', async () => { await next.build() expect(JSON.parse(await next.read...
toMatchInlineSnapshot(` { "outDirectory": "out", "success": true, "version": 1, } `) }) }) describe('Custom Export', () => { const { next } = nextTestSetup({ files: path.join(__dirname,
e, "version": 1, } `) const detail = JSON.parse(await next.readFile('.next/export-detail.json')) expect({ ...detail, outDirectory: path.basename(detail.outDirectory), }).
{ "filepath": "test/production/export-intent/export-intent.test.ts", "language": "typescript", "file_size": 4595, "cut_index": 614, "middle_length": 229 }
mport { FileRef, nextTestSetup, type Playwright } from 'e2e-utils' import { join } from 'path' import { check } from 'next-test-utils' describe('app-dir-prefetch-non-iso-url', () => { const { next } = nextTestSetup({ files: { 'next.config.js': new FileRef(join(__dirname, 'next.config.js')), app: new ...
=> { let browser: Playwright try { browser = await next.browser('/') await browser.elementByCss('#to-non-iso').click() await check(() => browser.elementByCss('#page').text(), '/[slug]') } finally { if (browser) {
entByCss('#to-iso').click() await check(() => browser.elementByCss('#page').text(), '/[slug]') } finally { if (browser) { await browser.close() } } }) it('should go to non-iso url', async ()
{ "filepath": "test/production/app-dir-prefetch-non-iso-url/index.test.ts", "language": "typescript", "file_size": 1045, "cut_index": 513, "middle_length": 229 }
from 'e2e-utils' import { join } from 'path' describe('distDir package.json commonjs boundary', () => { const { next } = nextTestSetup({ files: __dirname, // Use "type": "module" in the project package.json so the boundary file // is what determines whether `.next/server/**/*.js` is loaded as CJS. pa...
eadFile('.next/required-server-files.json') ) // Adapters consume `requiredServerFiles.files` to seed the per-page // shared assets. The boundary marker must be in this list because // per-page nft traces do not include it. expect(manif
le('.next/package.json') ) expect(distPackageJson).toEqual({ type: 'commonjs' }) }) it('lists the distDir package.json in required-server-files.json', async () => { const manifest = JSON.parse( await next.r
{ "filepath": "test/production/required-server-files-package-boundary/required-server-files-package-boundary.test.ts", "language": "typescript", "file_size": 1817, "cut_index": 537, "middle_length": 229 }
/ intervals/open connections shouldn't block build from exiting setInterval(() => {}, 250) module.exports = { onDemandEntries: { // Make sure entries are not getting disposed. maxInactiveAge: 1000 * 60 * 60, }, rewrites() { // add a rewrite so the code isn't dead-code eliminated return [ { ...
permanent: false, }, { source: '/redirect-query-test/:path', destination: '/about?foo=:path', permanent: false, }, ] }, images: { // Make sure we have sane default CSP, even when SVG is enabled dan
about', permanent: false, }, { source: '/nonexistent', destination: '/about', permanent: false, }, { source: '/shadowed-page', destination: '/about',
{ "filepath": "test/production/pages-dir/production/fixture/next.config.js", "language": "javascript", "file_size": 1029, "cut_index": 513, "middle_length": 229 }
('next.config evaluation error', () => { describe('production mode', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipStart: true, skipDeployment: true, }) if (skipped) return async function buildAndGetOutput(): Promise<string> { const start = next.cliOu...
ect(output).toContain('Invalid typed array length') expect(output).toContain( 'Failed to load next.config.js, see more info here https://nextjs.org/docs/messages/next-config-error' ) }) it('should report a helpful error when th
wait next.patchFile( 'next.config.js', ` module.exports = () => { return { foo: new Uint8Array(5_000_000_000) } } ` ) const output = await buildAndGetOutput() exp
{ "filepath": "test/production/config-evaluation-error/config-evaluation-error.test.ts", "language": "typescript", "file_size": 2093, "cut_index": 563, "middle_length": 229 }
tTestSetup } from 'e2e-utils' import { retry, getClientBuildManifestLoaderChunkUrlPath, } from 'next-test-utils' describe('Middleware Production Prefetch', () => { const { next } = nextTestSetup({ files: __dirname, env: { MIDDLEWARE_TEST: 'asdf', }, }) it('prefetch correctly for unexistent...
age' ) expect(attrs.some((src) => src && src.includes(chunk))).toBe(true) }) }) it('does not prefetch provided path if it will be rewritten', async () => { const browser = await next.browser('/') await browser.elementByCss('#ss
lementsByCss('script') const attrs = await Promise.all( scripts.map((script) => script.getAttribute('src')) ) const chunk = getClientBuildManifestLoaderChunkUrlPath( next.testDir, '/ssg-p
{ "filepath": "test/production/middleware-prefetch/middleware-prefetch.test.ts", "language": "typescript", "file_size": 1422, "cut_index": 524, "middle_length": 229 }
p from 'fs/promises' import path from 'path' describe('500-page app-router-only', () => { const { next, isNextStart, isNextDeploy } = nextTestSetup({ files: __dirname, }) if (isNextDeploy) { it('should render app router 500 page when route error', async () => { const $ = await next.render$('/route...
'pages', '500.html'), 'utf8' ) // Not use pages router to generate 500.html expect(html).toContain('__next_error__') // Server errors show "This page couldn\u2019t load" expect(html).toContain('This page couldn\u2019t
load') }) } if (isNextStart) { it('should use app router to generate 500.html when no pages _error.tsx exists', async () => { const html = await fsp.readFile( path.join(next.testDir, '.next', 'server',
{ "filepath": "test/production/500-page/app-router-only/app-router-only.test.ts", "language": "typescript", "file_size": 2102, "cut_index": 563, "middle_length": 229 }
tTestSetup } from 'e2e-utils' import fsp from 'fs/promises' import path from 'path' describe('500-page - mixed-router-no-custom-pages-error', () => { const { next, skipped } = nextTestSetup({ files: __dirname, }) if (skipped) { return } it('should not use app router global-error for 500.html when n...
) const pagesManifestJson = JSON.parse(pagesManifest) expect(pagesManifestJson).toMatchInlineSnapshot(` { "/404": "pages/404.html", "/_app": "pages/_app.js", "/_document": "pages/_document.js", "/_error": "pages
ternal Server Error') }) it('pages manifest should only contain 404 and 500', async () => { const pagesManifest = await fsp.readFile( path.join(next.testDir, '.next', 'server', 'pages-manifest.json'), 'utf8'
{ "filepath": "test/production/500-page/mixed-router-no-custom-pages-error/mixed-router-no-error.test.ts", "language": "typescript", "file_size": 1383, "cut_index": 524, "middle_length": 229 }
e client' export default function Page() { return ( <> <button onClick={async () => { const response = await fetch('/app-route', { method: 'OPTIONS' }) console.log(await response.json()) }} > Trigger Options Request (/app route) </button> <button...
Trigger Options Request (/pages page) </button> <button onClick={async () => { const response = await fetch('/api/pages-api-handler', { method: 'OPTIONS', }) console.log(await response.text(
ns Request (/app page) </button> <button onClick={async () => { const response = await fetch('/pages-page', { method: 'OPTIONS' }) console.log(await response.text()) }} >
{ "filepath": "test/production/options-request/app/page.tsx", "language": "tsx", "file_size": 1103, "cut_index": 515, "middle_length": 229 }
from 'e2e-utils' describe('Static 404 Export', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true, }) // Issue #36855 // https://github.com/vercel/next.js/issues/36855 it('only export 404.html when trailingSlash: false', async () => { await next.build() expect(await ...
wait next.build() await next.patchFile( 'next.config.js', `module.exports = (phase) => { return { output: 'export', trailingSlash: false, } }` ) expect(await next.hasFile('out/404/index.html')).toBe(true) expect(awa
.html and 404/index.html when trailingSlash: true', async () => { await next.patchFile( 'next.config.js', `module.exports = (phase) => { return { output: 'export', trailingSlash: true, } }` ) a
{ "filepath": "test/production/export-404/export-404.test.ts", "language": "typescript", "file_size": 1520, "cut_index": 537, "middle_length": 229 }
ort { nextTestSetup } from 'e2e-utils' describe('config validation - fatal errors', () => { const { next } = nextTestSetup({ skipStart: true, files: __dirname, }) it('should show warnings first, then throw fatal error', async () => { const { exitCode, cliOutput } = await next.build() // Build s...
g errors found in next.config.js that must be fixed' ) expect(cliOutput).toContain( "Unrecognized key(s) in object: 'invalidOption'" ) expect(cliOutput).toContain('at "images"') expect(cliOutput).toContain( 'These configurat
recognized key(s) in object: 'unknownExperimentalOption', 'anotherUnknownOption'" ) expect(cliOutput).toContain('at "experimental"') // Should show fatal error expect(cliOutput).toContain( 'Fatal next confi
{ "filepath": "test/production/config-validation-fatal-errors/index.test.ts", "language": "typescript", "file_size": 1062, "cut_index": 515, "middle_length": 229 }
{ webpack(cfg, { isServer, nextRuntime }) { const origEntry = cfg.entry cfg.entry = async () => { const origEntries = await origEntry() if (isServer && nextRuntime === 'nodejs') { const curEntry = origEntries['pages/_app'] origEntries['pages/_app'] = [ path.join(__dirnam...
e1': ['./include-me/**/*', 'node_modules/pkg-behind-symlink/*'], '/*': ['include-me-global.txt'], }, outputFileTracingExcludes: { // Subpaths should also work '/index': ['public/exclude-me/**/*'], '/route1': ['./public/exclude-me/**/*']
'/pages/index': ['include-me/**/*'], '/app/rout
{ "filepath": "test/production/build-trace-extra-entries/app/next.config.js", "language": "javascript", "file_size": 876, "cut_index": 559, "middle_length": 52 }
from 'path' import { nextTestSetup } from 'e2e-utils' describe('Babel custom - babel-env', () => { const { next } = nextTestSetup({ files: path.join(__dirname, 'fixtures/babel-env'), skipStart: true, }) it('should allow setting babelrc env', async () => { const { exitCode } = await next.build() ...
nextTestSetup({ files: path.join(__dirname, 'fixtures/targets-string'), skipStart: true, }) it('should allow setting targets to a string', async () => { const { exitCode } = await next.build() expect(exitCode).toBe(0) }) }) describe
tart: true, }) it('should allow setting targets.browsers', async () => { const { exitCode } = await next.build() expect(exitCode).toBe(0) }) }) describe('Babel custom - targets-string', () => { const { next } =
{ "filepath": "test/production/babel-custom/babel-custom.test.ts", "language": "typescript", "file_size": 1304, "cut_index": 524, "middle_length": 229 }
ading request body in middleware', () => { const { next } = nextTestSetup({ files: { 'middleware.js': ` const { NextResponse } = require('next/server'); export default async function middleware(request) { if (!request.body) { return new Response(null, { status: 400 });...
headers: { data: JSON.stringify({ root: true, ...json }), }, }) } `, 'pages/api/hi.js': ` export default function hi(req, res) { res.json({ ...req.body,
rams.has("next")) { const res = NextResponse.next(); res.headers.set('x-from-root-middleware', '1'); return res; } return new Response(null, { status: 200,
{ "filepath": "test/production/reading-request-body-in-middleware/index.test.ts", "language": "typescript", "file_size": 4581, "cut_index": 614, "middle_length": 229 }
import { nextTestSetup } from 'e2e-utils' import { retry } from 'next-test-utils' describe('Production Usage', () => { describe('production mode', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, }) if (skipped) return it('should navigate forward ...
Nav')).toBe(true) await browser.elementByCss('#to-index').click() await retry(async () => { expect(await browser.hasElementByCssSelector('#to-another')).toBe(true) }) expect(await browser.eval('window.beforeNav')).toBe(true)
// waitForElement doesn't seem to work properly in safari 10 await retry(async () => { expect(await browser.hasElementByCssSelector('#to-index')).toBe(true) }) expect(await browser.eval('window.before
{ "filepath": "test/production/production-nav/production-nav.test.ts", "language": "typescript", "file_size": 1013, "cut_index": 512, "middle_length": 229 }
output const firstNodeModules = file.indexOf('/node_modules/') const lastNodeModules = file.lastIndexOf('/node_modules/') if (firstNodeModules !== lastNodeModules) { return file.slice(lastNodeModules) } return file }) ), ] result.sort() re...
not meant for testing correctness (which is done by the behavioral tests), but as a // regression test to ensure that some stray `path.join` doesn't cause all of the Next.js package to // get included. // // Also skip alternate React versions, as they woul
s test for Turbopack as it is more conservative (i.e. aggressive) in including // referenced files and might include too many. (The Webpack snapshots would different slightly from // the Turbopack ones below.) // // This test is
{ "filepath": "test/production/next-server-nft/next-server-nft.test.ts", "language": "typescript", "file_size": 41422, "cut_index": 2151, "middle_length": 229 }
('Middleware validation during build', () => { describe('production mode', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipStart: true, skipDeployment: true, }) if (skipped) return const middlewareError = 'Middleware is returning a response body' describ...
uilding response body with a variable', code: `export default function () { const body = 'this is not allowed, but hard to detect with AST' return new Response(body) }`, }, { title: 'build
title: 'building body with JSON.stringify', code: `export default function () { return new Response(JSON.stringify({ error: 'this is not allowed' })) }`, }, { title: 'b
{ "filepath": "test/production/middleware-build-errors/middleware-build-errors.test.ts", "language": "typescript", "file_size": 2823, "cut_index": 563, "middle_length": 229 }
with path prefix', () => { let cdnPort: number let cdn: http.Server let cdnAccessLog: string[] = [] const { next } = nextTestSetup({ files: __dirname, skipStart: true, dependencies: {}, }) beforeAll(async () => { cdnPort = 0 cdn = http.createServer((clientReq, clientRes) => { co...
localhost:${next.appPort}` clientRes.writeHead(proxyRes.statusCode!, proxyRes.headers) proxyRes.on('error', (e) => { require('console').error(e) }) clientRes.on('error', (e) => { require('cons
ext.appPort, path: proxyPath, method: clientReq.method, headers: clientReq.headers, }, (proxyRes) => { proxyRes.headers['Access-Control-Allow-Origin'] = `http://
{ "filepath": "test/production/absolute-assetprefix/absolute-assetprefix.test.ts", "language": "typescript", "file_size": 3985, "cut_index": 614, "middle_length": 229 }
from 'e2e-utils' describe('Invalid Page automatic static optimization', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true, }) it('Fails softly with descriptive error', async () => { const { cliOutput } = await next.build() expect(cliOutput).toMatch( /Build optimiz...
pages/also-valid.js', ` export default function Page() { return <p>hello world</p> } ` ) await next.deleteFile('pages/invalid.js') await next.deleteFile('pages/also-invalid.js') await next.patchFile( 'pag
'handles non-error correctly', async () => { await next.patchFile( 'pages/valid.js', ` export default function Page() { return <p>hello world</p> } ` ) await next.patchFile( '
{ "filepath": "test/production/invalid-page-automatic-static-optimization/invalid-page-automatic-static-optimization.test.ts", "language": "typescript", "file_size": 1525, "cut_index": 537, "middle_length": 229 }
await next.build({ args: ['--debug-build-paths', 'pages/foo.tsx'], }) expect(buildResult.exitCode).toBe(0) expect(buildResult.cliOutput).toBeDefined() // Should only build the specified page expect(buildResult.cliOutput).toContain('Route (pages)') expect(build...
ges/bar.tsx'], }) expect(buildResult.exitCode).toBe(0) expect(buildResult.cliOutput).toBeDefined() // Should build both specified pages expect(buildResult.cliOutput).toContain('Route (pages)') expect(buildRe
t(buildResult.cliOutput).not.toContain('Route (app)') }) it('should build multiple pages routes', async () => { const buildResult = await next.build({ args: ['--debug-build-paths', 'pages/foo.tsx,pa
{ "filepath": "test/production/debug-build-path/debug-build-paths.test.ts", "language": "typescript", "file_size": 15930, "cut_index": 921, "middle_length": 229 }
execSync } from 'child_process' const dependencies = { 'es-check': '9.6.4', browserslist: '4.28.1', } describe('escheck-output', () => { describe('es2020', () => { let browserslist = [ 'chrome 64', 'edge 79', 'firefox 67', 'opera 51', 'safari 12', ] const { next } = nex...
ult browserslist', () => { let browserslist = ['chrome 111', 'edge 111', 'firefox 111', 'safari 16.4'] const { next } = nextTestSetup({ files: __dirname, dependencies, packageJson: { browserslist, }, }) it(
'node_modules/.bin/es-check es2020 ".next/static/**/*.js" --noCache', { cwd: next.testDir, encoding: 'utf8' } ) expect(esCheckOutput).toContain('info: ✓ ES-Check passed!') }) }) describe('defa
{ "filepath": "test/production/escheck-output/index.test.ts", "language": "typescript", "file_size": 2631, "cut_index": 563, "middle_length": 229 }
from 'e2e-utils' import { fetchViaHTTP } from 'next-test-utils' describe('emitDecoratorMetadata SWC option', () => { const { next } = nextTestSetup({ files: join(__dirname, 'app'), dependencies: { 'reflect-metadata': '0.1.13', 'path-to-regexp': '6.2.0', tsyringe: '4.6.0', }, }) it(...
llo, world!') } finally { if (browser) { await browser.close() } } }) it('should compile with emitDecoratorMetadata enabled for API', async () => { const res = await fetchViaHTTP(next.url, '/api/something') expect(r
s('#message').text() expect(message).toBe('He
{ "filepath": "test/production/emit-decorator-metadata/index.test.ts", "language": "typescript", "file_size": 986, "cut_index": 582, "middle_length": 52 }
'childProcesses', false], ] as const)( 'turbopack-node-backend (%s)', (turbopackPluginRuntimeStrategy, expectSamePid) => { const { next, isTurbopack } = nextTestSetup({ files: __dirname, env: { TEST_TURBOPACK_PLUGIN_RUNTIME_STRATEGY: turbopackPluginRuntimeStrategy, }, }) const...
response.json() expect(data.buildPid).toBeDefined() expect(data.loaderPid).toBeDefined() if (expectSamePid) { expect(data.loaderPid).toBe(data.buildPid) } else { expect(data.loaderPid).not.toBe(data.buildPid)
esponse.status).toBe(200) const data = await
{ "filepath": "test/production/turbopack-node-backend/turbopack-node-backend.test.ts", "language": "typescript", "file_size": 929, "cut_index": 606, "middle_length": 52 }
ster) // --host-target Share host target/ dir with container for caching // --rebuild Force Docker image rebuild // --test Smoke-test built binaries (native arch only) // filter Substring match on target name (e.g. "musl", "x86_64") const { execFileSync } = require('child_process') const ...
gnu', }, { target: 'x86_64-unknown-linux-musl', arch: 'x86_64', abi: 'musl', napiPlatform: 'linux-x64-musl', }, { target: 'aarch64-unknown-linux-musl', arch: 'aarch64', abi: 'musl', napiPlatform: 'linux-arm64-musl',
target: 'x86_64-unknown-linux-gnu', arch: 'x86_64', abi: 'gnu', napiPlatform: 'linux-x64-gnu', }, { target: 'aarch64-unknown-linux-gnu', arch: 'aarch64', abi: 'gnu', napiPlatform: 'linux-arm64-
{ "filepath": "scripts/docker-native-build.js", "language": "javascript", "file_size": 5593, "cut_index": 716, "middle_length": 229 }
h') const { spawn } = require('child_process') const fs = require('fs/promises') const cwd = process.cwd() async function main() { const tarballs = await fs.readdir(path.join(cwd, 'public')) const nextTarball = tarballs.find((item) => !item.includes('-swc')) await fs.rename( path.join(cwd, 'public', nextTa...
arsedPackageJson = JSON.parse( await fs.readFile(unpackedPackageJson, 'utf8') ) const { optionalDependencies } = parsedPackageJson for (const key of Object.keys(optionalDependencies)) { optionalDependencies[key] = optionalDependencies[key].r
cwd, }) child.on('exit', (code) => { if (code) { return reject(`Failed with code ${code}`) } resolve() }) }) const unpackedPackageJson = path.join(cwd, 'package/package.json') const p
{ "filepath": "scripts/inject-deploy-url.js", "language": "javascript", "file_size": 1698, "cut_index": 537, "middle_length": 229 }
ENV = 'production' // Change this to 'experimental' to opt into the React experimental channel (needed for server actions, ppr) process.env.__NEXT_PRIVATE_PREBUNDLED_REACT = 'next' let currentNode = null let outliers = [] const chalk = { yellow: (str) => `\x1b[33m${str}\x1b[0m`, green: (str) => `\x1b[32m${str}\...
const end = performance.now() currentNode.totalDuration = end - start currentNode.selfDuration = currentNode.children.reduce( (acc, child) => acc - child.selfDuration, currentNode.totalDuration ) parent?.children.push(current
nt = currentNode currentNode = { id: filename, selfDuration: 0, totalDuration: 0, children: [], } const start = performance.now() const result = originalCompile.apply(this, arguments)
{ "filepath": "scripts/minimal-server.js", "language": "javascript", "file_size": 5309, "cut_index": 716, "middle_length": 229 }
les: { 'public/vercel.svg': '<svg width="24" height="24" xmlns="http://www.w3.org/2000/svg"/>', 'components/comp.js': ` export default function Comp() { return <h1>Hello Dynamic</h1>; } `, 'styles/index.module.css': '.home { color: orange }', 'page...
nt.woff2" }); const Comp = dynamic(() => import("../components/comp"), { loading: () => <h1>Loading...</h1>, }); export default function Page() { return <> <Comp /> <Image
/index.module.css"; import localFont from "next/font/local"; import { Inter } from "next/font/google"; const inter = Inter({ subsets: ["latin"] }); const myFont = localFont({ src: "./my-fo
{ "filepath": "test/production/jest/index.test.ts", "language": "typescript", "file_size": 5225, "cut_index": 716, "middle_length": 229 }
tTestSetup } from 'e2e-utils' describe('next/jest newLinkBehavior', () => { const { next } = nextTestSetup({ files: { 'pages/index.jsx': ` import Link from 'next/link' export default function Page() { return <Link href='https://example.com'><div>Hello World!</div></Link> ...
st = require('next/jest') const createJestConfig = nextJest({ dir: './' }) module.exports = createJestConfig({ testEnvironment: 'jest-environment-jsdom', }) `, }, dependencies: { jest: '29.7.0', '
ender(<Page />) const link = screen.getByRole('link', { name: 'Hello World!' }) expect(link.getAttribute('href')).toBe('https://example.com') }) `, 'jest.config.js': ` const nextJe
{ "filepath": "test/production/jest/new-link-behavior.test.ts", "language": "typescript", "file_size": 1385, "cut_index": 524, "middle_length": 229 }
import path from 'path' const appDir = path.join(__dirname, 'app') // react-relay is not compatible with React 19 and therefore Next.js 15 describe.skip('next/jest', () => { nextTestSetup({ files: { components: new FileRef(path.join(appDir, 'components')), pages: new FileRef(path.join(appDir, 'pages...
eateMockEnvironment() const { getByText } = render( <RelayEnvironmentProvider environment={environment}> <Page /> </RelayEnvironmentProvider> ) environment.mock.resolveMostRe
nment, MockPayloadGenerator } from 'relay-test-utils' import Page from '@/pages' describe('test graphql tag transformation', () => { it('should work', async () => { let environment = cr
{ "filepath": "test/production/jest/relay/relay-jest.test.ts", "language": "typescript", "file_size": 2413, "cut_index": 563, "middle_length": 229 }
ce80db9f1b8ab>> * @lightSyntaxTransform * @nogrep */ /* tslint:disable */ /* eslint-disable */ // @ts-nocheck import { ConcreteRequest, Query } from 'relay-runtime' export type pagesQuery$variables = {} export type pagesQueryVariables = pagesQuery$variables export type pagesQuery$data = { readonly viewer: { ...
l, args: null, concreteType: 'User', kind: 'LinkedField', name: 'user', plural: false, selections: [ v0 /*: any*/, { alias: null, args: null, kind: 'ScalarField', n
response: pagesQuery$data } const node: ConcreteRequest = (function () { var v0 = { alias: null, args: null, kind: 'ScalarField', name: 'id', storageKey: null, }, v1 = { alias: nul
{ "filepath": "test/production/jest/relay/app/types/pagesQuery.graphql.ts", "language": "typescript", "file_size": 2374, "cut_index": 563, "middle_length": 229 }
th from 'path' import type { NextAdapter } from 'next' import { FILES } from './files' // Webpack itself isn't deterministic ;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)( 'adapter-content-hashes', () => { describe.each([ { name: 'standard', files: FILES.standard }, { name: 'cache co...
]>[0] = await next.readJSON( 'build-complete.json' ) function validateOutput(output: { runtime?: 'edge' | 'nodejs' filePath: string assets?: Record<string, string> assetsHashes?: Record<str
n(__dirname, './my-adapter.mjs'), }, }) it('should emit server-side hashes to adapter', async () => { const { repoRoot, outputs, }: Parameters<NextAdapter['onBuildComplete'
{ "filepath": "test/production/deterministic-build/adapter-content-hashes.test.ts", "language": "typescript", "file_size": 2080, "cut_index": 563, "middle_length": 229 }
import path from 'path' export const FILES = { standard: { app: new FileRef(path.join(__dirname, 'standard', 'app')), pages: new FileRef(path.join(__dirname, 'standard', 'pages')), public: new FileRef(path.join(__dirname, 'standard', 'public')), 'instrumentation.ts': new FileRef( path.join(__d...
}, cacheComponents: { app: new FileRef(path.join(__dirname, 'cache-components', 'app')), 'next.config.js': new FileRef( path.join(__dirname, 'cache-components', 'next.config.js') ), 'proxy.ts': new FileRef( path.join(__dirn
join(__dirname, 'standard', 'next.config.js') ),
{ "filepath": "test/production/deterministic-build/files.ts", "language": "typescript", "file_size": 906, "cut_index": 547, "middle_length": 52 }
waitFor } from 'next-test-utils' describe('SSG Prerender No Revalidate', () => { const { next } = nextTestSetup({ files: __dirname, }) function runTests(route: string) { const pagePath = route === '/' ? '/index' : route it(`[${route}] should not revalidate when set to false`, async () => { co...
) expect(await next.readFile(fileName)).toBe(initialFileHtml) await waitFor(500) newHtml = await next.render(route) expect(initialHtml).toBe(newHtml) expect(await next.readFile(fileName)).toBe(initialFileHtml) expect(
xt.render(route) expect(initialHtml).toBe(newHtml) expect(await next.readFile(fileName)).toBe(initialFileHtml) await waitFor(500) newHtml = await next.render(route) expect(initialHtml).toBe(newHtml
{ "filepath": "test/production/prerender-no-revalidate/prerender-no-revalidate.test.ts", "language": "typescript", "file_size": 2092, "cut_index": 563, "middle_length": 229 }
xtTestSetup } from 'e2e-utils' import { waitFor } from 'next-test-utils' describe('route cancel via CSS', () => { describe('production mode', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, }) if (skipped) return it('should cancel slow page loads...
await browser.elementByCss('#link-2').click() await waitFor(3000) const text2 = await browser.elementByCss('#page-text').text() expect(text2).toMatch(/2/) expect(await browser.eval('window.routeCancelled')).toBe('yes') }) })
mentByCssSelector('#page-text')).toBeFalsy()
{ "filepath": "test/production/route-load-cancel-css/route-load-cancel-css.test.ts", "language": "typescript", "file_size": 834, "cut_index": 523, "middle_length": 52 }
dev server bundle. * * Usage: * node scripts/analyze-bundle.js [options] * * Options: * --open Open the report in browser (default: false) * --verbose Show detailed module reasons * --json Also output stats.json file * --list-modules List all bundled modules to console * ...
Externals = hasFlag('list-externals') const nextDir = path.join(__dirname, '..', 'packages', 'next') const bundlePath = path.join( nextDir, 'dist/compiled/dev-server/start-server.js' ) const reportPath = path.join( nextDir, 'dist/compiled/dev-serv
.argv.slice(2) const hasFlag = (name) => args.includes(`--${name}`) const openBrowser = hasFlag('open') const verbose = hasFlag('verbose') const outputJson = hasFlag('json') const listModules = hasFlag('list-modules') const list
{ "filepath": "scripts/analyze-dev-server-bundle.js", "language": "javascript", "file_size": 3961, "cut_index": 614, "middle_length": 229 }
: execOriginal } = require('child_process') const { createSignedCommit, upsertBranchRef, } = require('./github-utils/signed-commit') const exec = promisify(execOriginal) const { RELEASE_GITHUB_TOKEN = '', PR_GITHUB_TOKEN = '', RELEASE_GITHUB_APP_SLUG = '', RELEASE_GITHUB_APP_USER_ID = '', SCRIPT = '', ...
console.log('missing RELEASE_GITHUB_APP_USER_ID env') process.exit(1) } if (!SCRIPT) { console.log('missing SCRIPT env') process.exit(1) } const REPO_OWNER = 'vercel' const REPO_NAME = 'next.js' async function main() { const octokit = new Octoki
f (!PR_GITHUB_TOKEN) { console.log('missing PR_GITHUB_TOKEN env') process.exit(1) } if (!RELEASE_GITHUB_APP_SLUG) { console.log('missing RELEASE_GITHUB_APP_SLUG env') process.exit(1) } if (!RELEASE_GITHUB_APP_USER_ID) {
{ "filepath": "scripts/automated-update-workflow.js", "language": "javascript", "file_size": 3962, "cut_index": 614, "middle_length": 229 }
=PATH Test project directory (default: /private/tmp/next-boot-test) * --bundled Use bundled dev server (default) * --unbundled Use unbundled dev server * --compare Run both bundled and unbundled for comparison * --turbopack Use Turbopack (default) * --webpack Use Web...
s', '5'), 10) const testDir = getArg('test-dir', '/private/tmp/next-boot-test') const compare = hasFlag('compare') const useWebpack = hasFlag('webpack') const bundlerFlag = useWebpack ? '--webpack' : '--turbopack' const nextDir = path.join(__dirname, '..'
, defaultValue) => { const arg = args.find((a) => a.startsWith(`--${name}=`)) return arg ? arg.split('=')[1] : defaultValue } const hasFlag = (name) => args.includes(`--${name}`) const iterations = parseInt(getArg('iteration
{ "filepath": "scripts/benchmark-next-dev-boot.js", "language": "javascript", "file_size": 7318, "cut_index": 716, "middle_length": 229 }
t fs = require('fs') const path = require('path') const globOrig = require('glob') const { promisify } = require('util') const glob = promisify(globOrig) function collectPaths(routes, paths = []) { for (const route of routes) { if (route.path && !route.redirect) { paths.push(route.path) } if (rout...
ilter( (file) => !paths.includes(`/${file}`) && file !== 'errors/template.md' ) if (missingFiles.length) { hadError = true console.log(`Missing paths in ${manifest}:\n${missingFiles.join('\n')}`) } else { console.log(`No missing path
const files = await glob(path.join(dir, '**/*.md')) const manifestData = JSON.parse(await fs.promises.readFile(manifest, 'utf8')) const paths = [] collectPaths(manifestData.routes, paths) const missingFiles = files.f
{ "filepath": "scripts/check-manifests.js", "language": "javascript", "file_size": 1547, "cut_index": 537, "middle_length": 229 }
tarballDirectory = path.join(os.tmpdir(), 'vercel-nextjs-preview-tarballs'), baseUrlArg, ] = process.argv.slice(2) const baseUrl = baseUrlArg || 'https://vercel-packages.vercel.app/next' const repoRoot = path.resolve(__dirname, '..') await fs.mkdir(tarballDirectory, { recursive: true }) // The preview ...
= (await fs.readdir(nativePackagesDir)).filter( (name) => !name.startsWith('.') ) console.info(`Creating tarballs for next-swc packages`) const nextSwcPackageNames = new Set() await Promise.all( platforms.map(async (platform) => { co
ages/next/package.json'), 'utf8') ) const version = nextPackageJson.version console.info(`Designated version: ${version}`) const nativePackagesDir = path.join(repoRoot, 'crates/next-napi-bindings/npm') const platforms
{ "filepath": "scripts/create-preview-tarballs.js", "language": "javascript", "file_size": 5909, "cut_index": 716, "middle_length": 229 }
bo cache API via scripts/turbo-cache.mjs. // Uses docker export/import (flat filesystem) instead of save/load (layered) // to avoid including redundant base image layers. Compressed with zstd. // // Usage: // node scripts/docker-image-cache.js # restore from cache or build + upload // node scripts/docker-...
}, }) const REPO_ROOT = path.resolve(__dirname, '..') const IMAGE_NAME = 'next-swc-builder:latest' // docker export/import strips all image metadata. These --change flags // restore the ENV and WORKDIR that the Dockerfile sets, so that tools // like carg
') const fs = require('fs') const os = require('os') const { parseArgs } = require('node:util') const { values: flags } = parseArgs({ args: process.argv.slice(2), options: { force: { type: 'boolean', default: false },
{ "filepath": "scripts/docker-image-cache.js", "language": "javascript", "file_size": 6143, "cut_index": 716, "middle_length": 229 }
entChunks, retry } from 'next-test-utils' describe('chunk-load-failure', () => { const { next } = nextTestSetup({ files: __dirname, }) async function getNextDynamicChunk() { const browserChunks = await listClientChunks( path.join(next.testDir, next.distDir) ) let nextDynamicChunks = browse...
eError: Error | undefined const browser = await next.browser('/dynamic', { beforePageLoad(page) { page.route(`**/${nextDynamicChunk}*`, async (route) => { await route.abort('connectionreset') }) page.on('pageerro
mponent') ) expect(nextDynamicChunks).toHaveLength(1) return nextDynamicChunks[0] } it('should report async chunk load failures', async () => { let nextDynamicChunk = await getNextDynamicChunk() let pag
{ "filepath": "test/production/chunk-load-failure/chunk-load-failure.test.ts", "language": "typescript", "file_size": 3201, "cut_index": 614, "middle_length": 229 }
ction mode', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipStart: true, skipDeployment: true, }) if (skipped) return afterEach(async () => { await next.deleteFile('pages') }) it('should show proper error when two dynamic SSG routes have conflic...
on Page() { return '/blog/[slug]' } ` ) await next.patchFile( 'pages/[...catchAll].js', ` export const getStaticProps = () => { return { props: {} } } export const
} export const getStaticPaths = () => { return { paths: [ '/blog/conflicting', '/blog/first' ], fallback: false } } export default functi
{ "filepath": "test/production/conflicting-ssg-paths/conflicting-ssg-paths.test.ts", "language": "typescript", "file_size": 4207, "cut_index": 614, "middle_length": 229 }
('Production Config Usage', () => { describe('production mode', () => { describe('with generateBuildId', () => { const { next, skipped } = nextTestSetup({ files: __dirname + '/fixture-generateBuildId', disableAutoSkewProtection: true, skipDeployment: true, }) if (skipped)...
) describe('env', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipStart: true, skipDeployment: true, }) if (skipped) return it('should fail with leading __ in env key', async ()
ct(text).toMatch(/ComponentDidMount executed on client\./) const html = await browser.eval('document.documentElement.innerHTML') expect(html).toMatch('custom-buildid') await browser.close() }) }
{ "filepath": "test/production/production-config/production-config.test.ts", "language": "typescript", "file_size": 2308, "cut_index": 563, "middle_length": 229 }
tSetup } from 'e2e-utils' import { renderViaHTTP } from 'next-test-utils' import path from 'path' const appDir = path.join(__dirname, 'app') describe('next/jest', () => { const { next } = nextTestSetup({ files: { pages: new FileRef(path.join(appDir, 'pages')), 'tests/index.test.tsx': ` import ...
`, 'jest.config.js': new FileRef(path.join(appDir, 'jest.config.js')), 'next.config.js': new FileRef(path.join(appDir, 'next.config.js')), 'tsconfig.json': new FileRef(path.join(appDir, 'tsconfig.json')), }, dependencies:
estid should be available in the test', async () => { const { getByTestId } = render( <Page /> ) expect(getByTestId('main-text')).toHaveTextContent('Hello World') }) })
{ "filepath": "test/production/jest/remove-react-properties/remove-react-properties-jest.test.ts", "language": "typescript", "file_size": 1591, "cut_index": 537, "middle_length": 229 }
from 'e2e-utils' // Skipped in Turbopack as Turbopack doesn't have this error as it can process these imports. ;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)( 'Invalid static image import in _document', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true, }) ...
_document\.js/) } }) it('Should fail to build when disableStaticImages in next.config.js', async () => { await next.patchFile( 'next.config.js', ` module.exports = { images: { disableStatic
in('Failed to compile') expect(cliOutput).toMatch( /Images.*cannot.*be imported within.*pages[\\/]_document\.js/ ) if (!process.env.NEXT_RSPACK) { expect(cliOutput).toMatch(/Location:.*pages[\\/]
{ "filepath": "test/production/invalid-document-image-import/invalid-document-image-import.test.ts", "language": "typescript", "file_size": 1699, "cut_index": 537, "middle_length": 229 }
{ nextTestSetup } from 'e2e-utils' import { renderViaHTTP } from 'next-test-utils' describe('PostCSS plugin config as string', () => { const { next } = nextTestSetup({ files: { 'pages/index.js': ` export default function Page() { return <p>hello world</p> } `, 'global...
'tailwindcss/nesting': 'postcss-nesting', tailwindcss: {}, }, } `, 'tailwind.config.js': ` module.exports = { content: ['./pages/**/*'], } `, }, dependencies: { 'postc
export default function MyApp({ Component, pageProps }) { return <Component {...pageProps} /> } `, 'postcss.config.js': ` module.exports = { plugins: {
{ "filepath": "test/production/postcss-plugin-config-as-string/index.test.ts", "language": "typescript", "file_size": 1204, "cut_index": 518, "middle_length": 229 }
nv node /** * Analyze a CPU profile to identify hot modules */ const fs = require('fs') const profilePath = process.argv[2] if (!profilePath) { console.error('Usage: node analyze-profile.js <profile.cpuprofile>') process.exit(1) } const profile = JSON.parse(fs.readFileSync(profilePath, 'utf-8')) // Extract no...
ode_modules/' + url.split('node_modules/').pop() } if (!moduleHits[moduleName]) { moduleHits[moduleName] = { hits: 0 } } moduleHits[moduleName].hits += node.hitCount || 0 } }) // Sort by hits const sorted = Object.entries(moduleHit
url = fn.url // Extract module name from path let moduleName = url if (url.includes('next/dist/')) { moduleName = url.split('next/dist/')[1] } else if (url.includes('node_modules/')) { moduleName = 'n
{ "filepath": "scripts/analyze-profile.js", "language": "javascript", "file_size": 1291, "cut_index": 524, "middle_length": 229 }
'node:fs' import path from 'node:path' import url from 'node:url' import execa from 'execa' import { NEXT_DIR, logCommand } from './pack-util' const nextSwcDir = path.join(NEXT_DIR, 'packages/next-swc') export default async function buildNative( buildNativeArgs: string[] ): Promise<void> { const buildCommand = [...
riteTypes() } // Check if this file is being run directly if (import.meta.url === url.pathToFileURL(process.argv[1]).toString()) { buildNative(process.argv.slice(2)).catch((err) => { console.error(err) process.exit(1) }) } async function writ
ut a shell, `pnpm run build-native` returns a 0 exit code on SIGINT? shell: true, env: { NODE_ENV: process.env.NODE_ENV, CARGO_TERM_COLOR: 'always', TTY: '1', }, stdio: 'inherit', }) await w
{ "filepath": "scripts/build-native.ts", "language": "typescript", "file_size": 2440, "cut_index": 563, "middle_length": 229 }
t { configureGitHubAuth, getGitHubToken, getGitHubTokenMissingMessage, verifyGitHubApiAccess, } = require('./release-github-auth') async function main() { const args = process.argv const branchName = args[args.indexOf('--branch-name') + 1] const tagName = args[args.indexOf('--tag-name') + 1] if (!bran...
t.js/environments/release-stable/deployment-branch-policies?per_page=1', 'release-stable deployment branch policies' ) await execa(`git checkout -b "${branchName}"`, { stdio: 'inherit', shell: true, }) await execa(`git fetch origin ${t
githubToken = getGitHubToken() if (!githubToken) { console.log(getGitHubTokenMissingMessage()) return } await configureGitHubAuth(githubToken) await verifyGitHubApiAccess( githubToken, '/repos/vercel/nex
{ "filepath": "scripts/create-release-branch.js", "language": "javascript", "file_size": 3645, "cut_index": 614, "middle_length": 229 }
{ nextTestSetup } from 'e2e-utils' import { renderViaHTTP } from 'next-test-utils' describe('next/jest', () => { const { next } = nextTestSetup({ files: { 'pages/index.js': `import capitalize from '@hashicorp/platform-util/text/capitalize' export default function Home() { return capitalize('t...
scripts: { // Runs jest and bails if jest fails build: 'next build && jest', }, }, installCommand: 'pnpm i', buildCommand: `pnpm build`, dependencies: { '@hashicorp/platform-util': '0.2.0', '@types/reac
})`, 'jest.config.js': `module.exports = require('next/jest')({ dir: './' })()`, 'next.config.js': `module.exports = { transpilePackages: ['@hashicorp/platform-util'], }`, }, packageJson: {
{ "filepath": "test/production/jest/transpile-packages.test.ts", "language": "typescript", "file_size": 1181, "cut_index": 518, "middle_length": 229 }
{ FileRef, nextTestSetup } from 'e2e-utils' import path from 'path' import execa from 'execa' const appDir = path.join(__dirname, 'app') describe('next/jest', () => { const { next } = nextTestSetup({ skipStart: true, files: { app: new FileRef(path.join(appDir, 'app')), [`tests/index.test.tsx`]:...
.7.0', '@testing-library/react': '15.0.2', '@testing-library/jest-dom': '5.17.0', }, }) it('Should not throw preload is undefined error', async () => { const { stdout, stderr } = await execa( 'pnpm', ['jest', 'tests/ind
.getByRole('img') expect(logo).toBeDefined() }) `, 'jest.config.js': new FileRef(path.join(appDir, 'jest.config.js')), }, dependencies: { jest: '29.7.0', 'jest-environment-jsdom': '29
{ "filepath": "test/production/jest/next-image-preload/next-image-preload.test.ts", "language": "typescript", "file_size": 1232, "cut_index": 518, "middle_length": 229 }