prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
t async function getStaticProps({ params: { slug } }) {
if (slug[0] === 'delayby3s') {
await new Promise((resolve) => setTimeout(resolve, 3000))
}
return {
props: {
slug,
},
}
}
export async function getStaticPaths() {
return {
paths: [
{ params: { slug: ['first'] } },
'/ca... | }
}
export default function Page({ slug }) {
// Important to not check for `slug` existence (testing that build does not
// render fallback version and error)
return (
<>
<p id="catchall">Hi {slug.join(' ')}</p>{' '}
<Link href="/" | rd]', '[fourth]'] } },
],
fallback: false,
| {
"filepath": "test/production/prerender-export/pages/catchall-explicit/[...slug].js",
"language": "javascript",
"file_size": 910,
"cut_index": 547,
"middle_length": 52
} |
t/link'
import { useRouter } from 'next/router'
export async function getStaticPaths() {
return {
paths: [],
fallback: false,
}
}
export async function getStaticProps({ params }) {
await new Promise((resolve) => setTimeout(resolve, 1000))
return {
props: {
params,
hello: 'world',
... | (
<>
<p>Post: {post}</p>
<span>time: {time}</span>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/" id="home">
to home
</Link>
</>
| lback) {
return <p>hi fallback</p>
}
return | {
"filepath": "test/production/prerender-export/pages/fallback-only/[slug].js",
"language": "javascript",
"file_size": 873,
"cut_index": 559,
"middle_length": 52
} |
t/link'
import { useRouter } from 'next/router'
export async function getStaticPaths() {
return {
paths: [],
fallback: false,
}
}
export async function getStaticProps({ params }) {
await new Promise((resolve) => setTimeout(resolve, 1000))
return {
props: {
params,
hello: 'world',
... | (
<>
<p>Post: {post}</p>
<span>time: {time}</span>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/" id="home">
to home
</Link>
</>
| lback) {
return <p>hi fallback</p>
}
return | {
"filepath": "test/production/prerender-export/pages/blocking-fallback/[slug].js",
"language": "javascript",
"file_size": 873,
"cut_index": 559,
"middle_length": 52
} |
ort { resolveNextTgzFilename, run, useTempDir } from './utils'
describe('create-next-app ESLint configuration', () => {
let nextTgzFilename: string
beforeAll(() => {
nextTgzFilename = resolveNextTgzFilename()
})
it('should generate eslint.config.mjs for TypeScript project with ESLint', async () => {
... | { cwd }
)
expect(exitCode).toBe(0)
const projectDir = join(cwd, projectName)
// Should have eslint.config.mjs
expect(existsSync(join(projectDir, 'eslint.config.mjs'))).toBe(true)
// Should NOT have biome.json
| '--no-tailwind',
'--no-src-dir',
'--no-react-compiler',
'--no-agents-md',
'--app',
'--no-import-alias',
'--skip-install',
],
nextTgzFilename,
| {
"filepath": "test/production/create-next-app/eslint-config.test.ts",
"language": "typescript",
"file_size": 3168,
"cut_index": 614,
"middle_length": 229
} |
]
devDeps: string[]
}
export type ProjectSpecification = {
global: ProjectSettings
} & {
[key in TemplateType]: {
[key in TemplateMode]: ProjectSettings
}
}
/**
* Required files for a given project template and mode.
*/
export const projectSpecification: ProjectSpecification = {
global: {
files: [... | on',
],
deps: [],
devDeps: [],
},
ts: {
files: [
'pages/index.tsx',
'pages/_app.tsx',
'pages/api/hello.ts',
'tsconfig.json',
'next-env.d.ts',
],
deps: [],
devDeps: [
| SPACK ? ['next-rspack'] : []),
],
devDeps: ['eslint', 'eslint-config-next'],
},
default: {
js: {
files: [
'pages/index.js',
'pages/_app.js',
'pages/api/hello.js',
'jsconfig.js | {
"filepath": "test/production/create-next-app/lib/specification.ts",
"language": "typescript",
"file_size": 6144,
"cut_index": 716,
"middle_length": 229
} |
ojectFilesShouldExist,
resolveNextTgzFilename,
run,
useTempDir,
} from '../utils'
const lockFile = 'package-lock.json'
const files = [...DEFAULT_FILES, lockFile]
describe('create-next-app with package manager npm', () => {
let nextTgzFilename: string
beforeAll(() => {
nextTgzFilename = resolveNextTgzFi... | -no-agents-md',
],
nextTgzFilename,
{
cwd,
}
)
expect(res.exitCode).toBe(0)
projectFilesShouldExist({
cwd,
projectName,
files,
})
})
})
it('should use npm w | projectName,
'--ts',
'--app',
'--use-npm',
'--no-linter',
'--no-src-dir',
'--no-tailwind',
'--no-import-alias',
'--no-react-compiler',
'- | {
"filepath": "test/production/create-next-app/package-manager/npm.test.ts",
"language": "typescript",
"file_size": 2653,
"cut_index": 563,
"middle_length": 229
} |
_PATH,
projectFilesShouldExist,
resolveNextTgzFilename,
run,
useTempDir,
} from '../utils'
const lockFile = 'yarn.lock'
const files = [...DEFAULT_FILES, lockFile]
describe('create-next-app with package manager yarn', () => {
let nextTgzFilename: string
beforeAll(async () => {
nextTgzFilename = resolv... |
[
projectName,
'--ts',
'--app',
'--use-yarn',
'--no-linter',
'--no-src-dir',
'--no-tailwind',
'--no-import-alias',
'--no-react-compiler',
'--no-age | )
.catch(() => command('npm', ['i', '-g', 'yarn']))
})
it('should use yarn for --use-yarn flag', async () => {
await useTempDir(async (cwd) => {
const projectName = 'use-yarn'
const res = await run( | {
"filepath": "test/production/create-next-app/package-manager/yarn.test.ts",
"language": "typescript",
"file_size": 2914,
"cut_index": 563,
"middle_length": 229
} |
v jest */
import { nextTestSetup } from 'e2e-utils'
describe('Cleaning distDir', () => {
const { next, isTurbopack, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
})
if (skipped) return
beforeEach(async () => {
await next.stop()
await next.remove('.next')
})
async functi... | wait next.hasFile('.next/cache/swc')).toBe(true)
}
}
describe('disabled write', () => {
it('should clean up .next before build start', async () => {
await checkFileWrite(false)
})
it('should not clean up .next before build start | ext.build()
expect(await next.hasFile(customFile)).toBe(existsAfterBuild)
// `.next/cache` should be preserved in all cases
expect(await next.hasFile('.next/cache')).toBe(true)
if (!isTurbopack) {
expect(a | {
"filepath": "test/production/clean-distdir/index.test.ts",
"language": "typescript",
"file_size": 1266,
"cut_index": 524,
"middle_length": 229
} |
port { WindowScroller, List as VirtualizedList } from 'react-virtualized'
export default function Home() {
return (
<div>
<WindowScroller serverHeight={800}>
{({ height, isScrolling, onChildScroll, scrollTop }) => (
<VirtualizedList
autoHeight
height={height}
... | > {
return (
<div>
<Image src={img} placeholder="blur" className="thumbnail" />
<Image src={img} className="large" />
</div>
)
}}
oversc | rowHeight={400}
rowRenderer={() = | {
"filepath": "test/production/next-image-new/react-virtualized/pages/index.js",
"language": "javascript",
"file_size": 970,
"cut_index": 582,
"middle_length": 52
} |
React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
import 'firebase/firestore'
export async function getStaticPaths() {
return {
paths: [
'/blog/post-1',
{ params: { post: 'post-2' } },
'/blog/[post3]',
'/blog/post-4',
'/blog/post.1',
'/bl... | 'try again..')
}
}
return {
props: {
params,
post: params.post,
time: (await import('perf_hooks')).performance.now(),
},
}
}
export default ({ post, time, params }) => {
return (
<>
<p>Post: {post}</p>
| ((resolve) => {
setTimeout(() => resolve(), 1000)
})
}
if (params.post === 'post-100') {
throw new Error('such broken..')
}
if (params.post === 'post-999') {
if (++counter < 6) {
throw new Error( | {
"filepath": "test/production/prerender-export/pages/blog/[post]/index.js",
"language": "javascript",
"file_size": 1225,
"cut_index": 518,
"middle_length": 229
} |
export async function getStaticPaths() {
return {
paths: [{ params: { slug: 'a' } }, { params: { slug: 'b' } }],
fallback: false,
}
}
export async function getStaticProps({ params }) {
await new Promise((resolve) => setTimeout(resolve, 1000))
return {
props: {
params,
hello: 'world',... | eturn (
<>
<p>Post: {post}</p>
<span>time: {time}</span>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/" id="home">
to home
</Link>
| isFallback) {
return <p>hi fallback</p>
}
r | {
"filepath": "test/production/prerender-export/pages/blocking-fallback-some/[slug].js",
"language": "javascript",
"file_size": 925,
"cut_index": 606,
"middle_length": 52
} |
tPkgPathsEnv,
} from './lib/test-pkg-paths'
export const CNA_PATH = require.resolve('create-next-app/dist/index.js')
/**
* Resolves the path to the packed `next` tarball. Uses NEXT_TEST_PKG_PATHS
* when available (set by run-tests.js), otherwise finds packed.tgz files
* directly from the repo packages/ directory.
... | github.com/vercel/next.js/tree/canary'
export const EXAMPLE_PATH = 'examples/basic-css'
export const FULL_EXAMPLE_PATH = `${EXAMPLE_REPO}/${EXAMPLE_PATH}`
export const DEFAULT_FILES = [
'.gitignore',
'package.json',
'app/page.tsx',
'app/layout.tsx' | ould not find packed "next" tarball. ` +
`Run "pnpm turbo run pack-for-isolated-tests" first, ` +
`or run this test via "node run-tests.js".`
)
}
return tarballPath
}
export const EXAMPLE_REPO = 'https:// | {
"filepath": "test/production/create-next-app/utils.ts",
"language": "typescript",
"file_size": 6469,
"cut_index": 716,
"middle_length": 229
} |
execSync, spawn, SpawnOptions } from 'child_process'
import { existsSync } from 'fs'
import { join, resolve } from 'path'
import glob from 'glob'
import Conf from 'next/dist/compiled/conf'
import {
getProjectSetting,
mapSrcFiles,
projectSpecification,
} from './specification'
import {
CustomTemplateOptions,
... | st conf = new Conf({ projectName: 'create-next-app' })
if (clearPreferences) {
conf.clear()
}
console.log(`[TEST] $ ${cli} ${args.join(' ')}`, { options })
const cloneEnv = { ...process.env }
// unset CI env as this skips the auto-install b | )
/**
* Run the built version of `create-next-app` with the given arguments.
*/
export const createNextApp = (
args: string[],
options?: SpawnOptions,
testVersion?: string,
clearPreferences: boolean = true
) => {
con | {
"filepath": "test/production/create-next-app/lib/utils.ts",
"language": "typescript",
"file_size": 4850,
"cut_index": 614,
"middle_length": 229
} |
{ MetadataRoute } from 'next'
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
;() => {
;({
url: '',
lastModified: undefined,
changeFrequency: undefined,
priority: undefined,
alternates: undefined,
images: undefined,
videos: undefined,
}) satisfies MetadataRoute.Sitem... | y: undefined,
restriction: undefined,
platform: undefined,
requires_subscription: undefined,
uploader: undefined,
live: undefined,
tag: undefined,
},
],
}) satisfies MetadataRoute.Sitemap[number]
| loc: undefined,
player_loc: undefined,
duration: undefined,
expiration_date: undefined,
rating: undefined,
view_count: undefined,
publication_date: undefined,
family_friendl | {
"filepath": "test/production/typescript-basic/typechecking/metadata/sitemap.ts",
"language": "typescript",
"file_size": 1348,
"cut_index": 524,
"middle_length": 229
} |
nder export', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
dependencies: {
firebase: '7.14.5',
},
})
if (skipped) return
let server: Server
let appPort: number
let buildId: string
beforeAll(async () => {
await ne... | ash', async () => {
const routes = [
'/another',
'/something',
'/blog/post-1',
'/blog/post-2/comment-2',
]
for (const route of routes) {
await next.readFile(`out${route}/index.html`)
await next.readFile(`out | eadFile('.next/BUILD_ID')).trim()
})
afterAll(async () => {
if (server) {
await new Promise<void>((resolve) => server.close(() => resolve()))
}
})
it('should copy prerender files and honor exportTrailingSl | {
"filepath": "test/production/prerender-export/prerender-export.test.ts",
"language": "typescript",
"file_size": 7437,
"cut_index": 716,
"middle_length": 229
} |
tils'
describe('create-next-app --example', () => {
let nextTgzFilename: string
beforeAll(() => {
nextTgzFilename = resolveNextTgzFilename()
})
it('should create on valid Next.js example name', async () => {
await useTempDir(async (cwd) => {
const projectName = 'valid-example'
const res =... | ',
'app/layout.tsx',
'node_modules/next',
],
})
})
})
it('should create with GitHub URL', async () => {
await useTempDir(async (cwd) => {
const projectName = 'github-url'
const res = await run(
| {
cwd,
}
)
expect(res.exitCode).toBe(0)
projectFilesShouldExist({
cwd,
projectName,
files: [
'.gitignore',
'package.json',
'app/page.tsx | {
"filepath": "test/production/create-next-app/examples.test.ts",
"language": "typescript",
"file_size": 7100,
"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 = 'app-js'
const { exitCode } = await run(
[
projectName,
... | , template: 'app', mode: 'js' })
await tryNextDev({
cwd,
projectName,
})
})
})
it('should create TypeScript project with --ts flag', async () => {
await useTempDir(async (cwd) => {
const projectName = 'app-ts' | ents-md',
...(process.env.NEXT_RSPACK ? ['--rspack'] : []),
],
nextTgzFilename,
{
cwd,
}
)
expect(exitCode).toBe(0)
shouldBeTemplateProject({ cwd, projectName | {
"filepath": "test/production/create-next-app/templates/app.test.ts",
"language": "typescript",
"file_size": 5305,
"cut_index": 716,
"middle_length": 229
} |
t/link'
import { useRouter } from 'next/router'
export async function getStaticPaths() {
return {
paths: [],
fallback: false,
}
}
export async function getStaticProps({ params }) {
await new Promise((resolve) => setTimeout(resolve, 1000))
return {
props: {
params,
hello: 'world',
... | (
<>
<p>Post: {post}</p>
<span>time: {time}</span>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/" id="home">
to home
</Link>
</>
| lback) {
return <p>hi fallback</p>
}
return | {
"filepath": "test/production/prerender-export/pages/blocking-fallback-once/[slug].js",
"language": "javascript",
"file_size": 873,
"cut_index": 559,
"middle_length": 52
} |
d 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 `_test/cancel-coun... | tp.createServer(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 isComple | Number(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 = ht | {
"filepath": "test/production/next-image-new/react-virtualized/server.js",
"language": "javascript",
"file_size": 1549,
"cut_index": 537,
"middle_length": 229
} |
from 'e2e-utils'
import fs from 'fs-extra'
import {
findPort,
initNextServerScript,
killApp,
renderViaHTTP,
} from 'next-test-utils'
import { join } from 'path'
let MY_DEPLOYMENT_ID = 'test-deployment-id'
describe('standalone mode: runtimeServerDeploymentId', () => {
let server
let appPort
let output = ... | xt.testDir, 'standalone')
)
for (const file of await fs.readdir(next.testDir)) {
if (file !== 'standalone') {
await fs.remove(join(next.testDir, file))
console.log('removed', file)
}
}
const testServer = join(n | oreAll(async () => {
let { exitCode } = await next.build()
// eslint-disable-next-line jest/no-standalone-expect
expect(exitCode).toBe(0)
await fs.move(
join(next.testDir, '.next/standalone'),
join(ne | {
"filepath": "test/production/standalone-mode/runtimeServerDeploymentId/index.test.ts",
"language": "typescript",
"file_size": 1959,
"cut_index": 537,
"middle_length": 229
} |
iles: path.resolve(__dirname, './invalid-runtime/app'),
skipStart: true,
})
test('fails to build on malformed input', async () => {
const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1)
if (process.env.IS_TURBOPACK_TEST) {
expect(cliOutput).toContain(
... | resolve(__dirname, './invalid-middleware'),
skipStart: true,
})
test('fails the build on invalid middleware matcher', async () => {
const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1)
// TODO: Turbo | `Invalid enum value. Expected 'edge' | 'experimental-edge' | 'nodejs', received 'something-odd'`
)
}
})
})
describe('invalid-middleware', () => {
const { next } = nextTestSetup({
files: path. | {
"filepath": "test/production/exported-runtimes-value-validation/index.test.ts",
"language": "typescript",
"file_size": 6012,
"cut_index": 716,
"middle_length": 229
} |
ort { nextTestSetup } from 'e2e-utils'
describe('jsconfig.json', () => {
const { next, isTurbopack } = nextTestSetup({
files: __dirname,
skipStart: true,
})
it('should build normally', async () => {
const { exitCode } = await next.build()
expect(exitCode).toBe(0)
})
it('should fail on inval... | Output).toMatch(
/tsconfig is not parseable: invalid JSON: Unterminated object/
)
} else {
expect(next.cliOutput).toMatch(/Error: Failed to parse "/)
expect(next.cliOutput).toMatch(/JSON5: invalid end of input at 1:2 | ext.build()
expect(exitCode).not.toBe(0)
if (isTurbopack) {
expect(next.cliOutput).toMatch(/An issue occurred while parsing/)
expect(next.cliOutput).toMatch(/jsconfig.json:1:1/)
expect(next.cli | {
"filepath": "test/production/jsconfig/jsconfig.test.ts",
"language": "typescript",
"file_size": 1103,
"cut_index": 515,
"middle_length": 229
} |
dering', () => {
describe('production mode', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
it('correctly measures hydrate followed by render', async () => {
const browser = await next.browser('/')
await browser... | value]) => Object.fromEntries(new URLSearchParams(value)))
.filter((p) => p.label === 'custom')
expect(beacons).toMatchObject([
{ name: 'Next.js-hydration' },
{ name: 'Next.js-render' },
{ name: 'Next.js-route-change- | t browser.eval('window.__BEACONS'))
.map(([, | {
"filepath": "test/production/hydrate-then-render/hydrate-then-render.test.ts",
"language": "typescript",
"file_size": 957,
"cut_index": 582,
"middle_length": 52
} |
und revalidate', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: { 'fs-extra': 'latest' },
})
it('should revalidate page when notFound returned during build', async () => {
let res = await next.fetch('/initial-not-found/first')
let $ = await next.render$('/initial-not-fou... | 404)
expect($('#not-found').text()).toBe('404 page')
await next.patchFile('data.txt', '200')
try {
await retry(async () => {
const r = await next.fetch('/initial-not-found/first')
const $r = await next.render$('/initial- | t-found/second')
expect(res.status).toBe(404)
expect($('#not-found').text()).toBe('404 page')
res = await next.fetch('/initial-not-found')
$ = await next.render$('/initial-not-found')
expect(res.status).toBe( | {
"filepath": "test/production/not-found-revalidate/not-found-revalidate.test.ts",
"language": "typescript",
"file_size": 4976,
"cut_index": 614,
"middle_length": 229
} |
from 'next/router'
export default function Page(props) {
if (useRouter().isFallback) return 'Loading...'
return (
<>
<p id="fallback-true">fallback true page</p>
<p id="props">{JSON.stringify(props)}</p>
</>
)
}
export const getStaticProps = async ({ params }) => {
const { slug } = param... | nd: true,
hello: 'world',
random: Math.random(),
},
revalidate: 1,
}
}
await fs.ensureDir(dir)
return {
notFound: true,
revalidate: 1,
}
}
export const getStaticPaths = async () => {
await fs.remove(path | return {
props: {
params,
fou | {
"filepath": "test/production/not-found-revalidate/pages/fallback-true/[slug].js",
"language": "javascript",
"file_size": 987,
"cut_index": 582,
"middle_length": 52
} |
urn (
<>
<p id="fallback-blocking">fallback blocking page</p>
<p id="props">{JSON.stringify(props)}</p>
</>
)
}
export const getStaticProps = async ({ params }) => {
const { slug } = params
if (!slug) {
throw new Error(`missing slug value for /fallback-true/[slug]`)
}
const dir = pa... | }
await fs.ensureDir(dir)
return {
notFound: true,
revalidate: 1,
}
}
export const getStaticPaths = async () => {
await fs.remove(path.join(process.cwd(), '.tmp/fallback-blocking'))
return {
paths: [],
fallback: 'blocking',
| ath.random(),
},
revalidate: 1,
}
| {
"filepath": "test/production/not-found-revalidate/pages/fallback-blocking/[slug].js",
"language": "javascript",
"file_size": 918,
"cut_index": 606,
"middle_length": 52
} |
heck
const { requestIdStorage } = require('./als')
const defaultCacheHandler =
require('next/dist/server/lib/cache-handlers/default.external').default
/**
* @type {import('next/dist/server/lib/cache-handlers/types').CacheHandler}
*/
const cacheHandler = {
async get(cacheKey) {
return defaultCacheHandler.ge... | efreshTags() {
return defaultCacheHandler.refreshTags()
},
async getExpiration(tags) {
return defaultCacheHandler.getExpiration(tags)
},
async updateTags(tags) {
return defaultCacheHandler.updateTags(tags)
},
}
module.exports = cac | eHandler.set(cacheKey, pendingEntry)
},
async r | {
"filepath": "test/production/custom-server/cache-handler.js",
"language": "javascript",
"file_size": 838,
"cut_index": 520,
"middle_length": 52
} |
} = nextTestSetup({
files: __dirname,
startCommand: 'node server.js',
serverReadyPattern: /^- Local:/,
dependencies: {
'get-port': '5.1.1',
},
})
it.each(['a', 'b', 'c'])('can navigate to /%s', async (page) => {
const $ = await next.render$(`/${page}`)
expect($('p').text()).toBe(... | it('should render pages with installed react', async () => {
const $ = await next.render$(`/2`)
if (isReact18) {
expect($('body').text()).toMatch(/pages: 18\.\d+\.\d+\{/)
} else {
expect($('body').text()).toMatch(/pages: | erver side error')
})
describe('with app dir', () => {
it('should render app with react canary', async () => {
const $ = await next.render$(`/1`)
expect($('body').text()).toMatch(/app: .+-canary/)
})
| {
"filepath": "test/production/custom-server/custom-server.test.ts",
"language": "typescript",
"file_size": 3925,
"cut_index": 614,
"middle_length": 229
} |
require('http')
const { parse } = require('url')
const next = require('next')
const getPort = require('get-port')
const { requestIdStorage } = require('./als')
const quiet = process.env.USE_QUIET === 'true'
let requestId = 0
async function main() {
const port = await getPort()
const hostname = 'localhost'
let c... | c () => {
try {
// Be sure to pass `true` as the second argument to `url.parse`.
// This tells it to parse the query portion of the URL.
const parsedUrl = parse(req.url, true)
let { pathname, query } = parsed | `port` must be provided below
const app = next({ hostname, port, quiet, conf })
const handle = app.getRequestHandler()
app.prepare().then(() => {
createServer((req, res) =>
requestIdStorage.run(requestId++, asyn | {
"filepath": "test/production/custom-server/server.js",
"language": "javascript",
"file_size": 2017,
"cut_index": 537,
"middle_length": 229
} |
om 'e2e-utils'
describe('build trace with extra entries', () => {
describe('production mode', () => {
const { next, isTurbopack, skipped } = nextTestSetup({
files: path.join(__dirname, 'app'),
skipStart: true,
skipDeployment: true,
})
if (skipped) return
it('should build and trace ... | .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/route1/route.js.nft.jso | js.nft.json')
)
const indexTrace = JSON.parse(
await next.readFile('.next/server/pages/index.js.nft.json')
)
const anotherTrace = JSON.parse(
await next.readFile('.next/server/pages/another | {
"filepath": "test/production/build-trace-extra-entries-turbo/build-trace-extra-entries-turbo.test.ts",
"language": "typescript",
"file_size": 2989,
"cut_index": 563,
"middle_length": 229
} |
('File Dependencies', () => {
describe('production mode', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
it('should apply styles defined in global and module css files in a standard page.', async () => {
const browser... | backgroundColor: 'rgb(200, 200, 200)',
})
})
it('should apply styles defined in global and module css files in 404 page', async () => {
const browser = await next.browser('/__not_found__')
await browser.elementByCss('#notFoun | yId('index') as HTMLElement
)
return {
color: computed.color,
backgroundColor: computed.backgroundColor,
}
})
expect(styles).toEqual({
color: 'rgb(0, 0, 255)',
| {
"filepath": "test/production/document-file-dependencies/document-file-dependencies.test.ts",
"language": "typescript",
"file_size": 2083,
"cut_index": 563,
"middle_length": 229
} |
stdout = result.cliOutput
})
it('should not include internal pages', () => {
expect(stdout).toMatch(/\//)
expect(stdout).not.toContain(' /_document')
expect(stdout).not.toContain(' /_app')
expect(stdout).not.toContain(' /_error')
expect(stdout).not.toContain('<buildId>')
exp... | arsePageFirstLoad = (page: string) =>
stdout.match(
new RegExp(
` ${page} .*?(?:(?:\\d|\\.){1,}) .*? ((?:\\d|\\.){1,} (?:\\w{1,}))`
)
)![1]
const parseSharedSize = (sharedPartName: string) => {
| ocess.env.NEXT_PRIVATE_SKIP_SIZE_TESTS) {
return
}
const parsePageSize = (page: string) =>
stdout.match(
new RegExp(` ${page} .*?((?:\\d|\\.){1,} (?:\\w{1,})) `)
)![1]
const p | {
"filepath": "test/production/build-output/build-output.test.ts",
"language": "typescript",
"file_size": 10359,
"cut_index": 921,
"middle_length": 229
} |
port default ({ renderDuration }) => {
const target = Date.now() + (+renderDuration || 200)
while (Date.now() < target);
return <div>{renderDuration}</div>
}
export function getStaticPaths() {
return {
paths: [
[2000, 10],
[5, 5],
[25, 25],
[20, 20],
[10, 10],
[15, 15],
... | opsDuration}`,
},
})),
fallback: true,
}
}
export async function getStaticProps({ params }) {
const { renderDuration, propsDuration } = params
await new Promise((r) => setTimeout(r, +propsDuration))
return { props: { renderDuration } | uration: `${pr | {
"filepath": "test/production/build-output/fixtures/basic-app/pages/slow-static/[propsDuration]/[renderDuration].js",
"language": "javascript",
"file_size": 789,
"cut_index": 514,
"middle_length": 14
} |
successfully', () => {
expect(next.cliOutput).toMatch(/Compiled successfully/)
})
it(`should've emitted a single CSS file`, async () => {
const $ = await next.render$('/')
const cssSheet = $('link[rel="stylesheet"]')
expect(cssSheet.length).toBe(1)
const stylesheet = cssSheet.att... | "`)
}
})
it(`should've injected the CSS on server render`, async () => {
const $ = await next.render$('/')
const cssPreload = $('link[rel="preload"][as="style"]')
expect(cssPreload.length).toBe(1)
expect(cssPreload.a | ).toMatchInlineSnapshot(`".index-module__KWKY6G__redText{color:red}"`)
} else {
expect(
cssContent.replace(/\/\*.*?\*\//g, '').trim()
).toMatchInlineSnapshot(`".index_redText__honUV{color:red} | {
"filepath": "test/production/css-modules/css-modules.test.ts",
"language": "typescript",
"file_size": 16418,
"cut_index": 921,
"middle_length": 229
} |
Setup } from 'e2e-utils'
describe('Handles Errors During Export', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
it('Does not crash workers', async () => {
const { cliOutput } = await next.build()
expect(cliOutput).not.toMatch(/ERR_IPC_CHANNEL_CLOSED/)
expect... | (cliOutput).toContain('/page-13')
expect(cliOutput).toContain('/blog/[slug]: /blog/first')
expect(cliOutput).toContain('/blog/[slug]: /blog/second')
expect(cliOutput).toContain('/custom-error')
expect(cliOutput).toContain('custom error mess | expect(cliOutput).toContain('/page-3')
expect | {
"filepath": "test/production/handles-export-errors/handles-export-errors.test.ts",
"language": "typescript",
"file_size": 851,
"cut_index": 529,
"middle_length": 52
} |
nextTestSetup({
files: __dirname,
skipStart: true,
})
const ssrfProbePath = '/secret-upgrade'
const ssrfProbeBody =
'SSRF_CONFIRMED: You reached the internal service at 127.0.0.1'
let backend: http.Server
let backendPort: number
let intermediary: http.Server
let intermediaryPort: number
con... | )
const chunkSize = Buffer.from(
`${smuggledRequest.length.toString(16).toUpperCase()}\r\n`,
'latin1'
)
const payload = Buffer.concat([
Buffer.from(
`${method} ${rewritePath} HTTP/1.1\r\nHost: 127.0.0.1:${nextPort}\r\ | mber
connectionHeader: string
method?: 'DELETE' | 'OPTIONS'
rewritePath?: string
}) {
const smuggledRequest = Buffer.from(
`GET /secret HTTP/1.1\r\nHost: 127.0.0.1:${nextPort}\r\n\r\n`,
'latin1'
| {
"filepath": "test/production/rewrite-request-smuggling/rewrite-request-smuggling.test.ts",
"language": "typescript",
"file_size": 8756,
"cut_index": 716,
"middle_length": 229
} |
age component', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
afterEach(async () => {
await next.patchFile(
'next.config.js',
'// prettier-ignore\nmodule.exports = { /* replaceme */ }\n'
)
await next.patchFile(
'pages/index.js',
`import... | output: 'export',
images: {
loader: 'cloudinary',
path: 'https://example.com/',
},
})
)
)
const { exitCode } = await next.build()
expect(exitCode).toBe(0)
const html = await | der} />
</div>
)
`
)
})
it('should build with cloudinary loader', async () => {
await next.patchFile('next.config.js', (content) =>
content.replace(
'{ /* replaceme */ }',
JSON.stringify({
| {
"filepath": "test/production/export-image-loader/export-image-loader.test.ts",
"language": "typescript",
"file_size": 3560,
"cut_index": 614,
"middle_length": 229
} |
retry } from 'next-test-utils'
describe('SSG Prerender Revalidate', () => {
const { next } = nextTestSetup({
files: __dirname,
})
function runTests(route: string) {
it(`[${route}] should regenerate page when revalidate time exceeded`, async () => {
const initialHtml = await next.render(route)
... | const newData = await next.render(dataRoute)
expect(newData).not.toBe(initialData)
})
})
}
runTests('/')
runTests('/named')
runTests('/nested')
runTests('/nested/named')
it('should return cache-control header on 304 sta | en revalidate time exceeded`, async () => {
const dataRoute = `/_next/data/${next.buildId}${route === '/' ? '/index' : route}.json`
const initialData = await next.render(dataRoute)
await retry(async () => {
| {
"filepath": "test/production/prerender-revalidate/prerender-revalidate.test.ts",
"language": "typescript",
"file_size": 2439,
"cut_index": 563,
"middle_length": 229
} |
p } from 'e2e-utils'
import { retry, waitFor } from 'next-test-utils'
describe('Root Optional Catch-all Revalidate', () => {
describe('production mode', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
const getProps = async... | ndex)).toEqual(
'getStaticProps({ revalidateReason: "stale" })\n'
)
// Rendering takes time before the new cache entry is filled
await retry(async () => {
const newProps = await getProps('/')
expect(newProps.param | () => {
const props = await getProps('/')
expect(props.params).toEqual({})
const outputIndex = next.cliOutput.length
await waitFor(1000)
await getProps('/')
expect(next.cliOutput.slice(outputI | {
"filepath": "test/production/root-optional-revalidate/root-optional-revalidate.test.ts",
"language": "typescript",
"file_size": 2496,
"cut_index": 563,
"middle_length": 229
} |
rig from 'glob'
import { promisify } from 'util'
import { join } from 'path'
import { nextTestSetup } from 'e2e-utils'
const glob = promisify(globOrig)
describe('CSS optimization for SSR apps', () => {
const { next } = nextTestSetup({
files: __dirname,
disableAutoSkewProtection: true,
dependencies: {
... | ng) => file.endsWith('.css'))
).toEqual(cssFiles)
})
it('should inline critical CSS', async () => {
const html = await next.render('/')
expect(html).toMatch(
/<link rel="stylesheet" href="\/_next\/static\/.*\.css(\?dpl=.*)?" .*>/
| atic'),
})
).map((file) => join('.next/static', file))
const requiredServerFiles = await next.readJSON(
'.next/required-server-files.json'
)
expect(
requiredServerFiles.files.filter((file: stri | {
"filepath": "test/production/critical-css/critical-css.test.ts",
"language": "typescript",
"file_size": 1458,
"cut_index": 524,
"middle_length": 229
} |
import { nextTestSetup } from 'e2e-utils'
describe('with-electron', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should render the home page', async () => {
const html = await next.render('/')
expect(html).toContain('This is the home page')
})
it('should render the about pa... | ations via Router', async () => {
const browser = await next.browser('/')
await browser.elementByCss('#about-via-router').click()
const text = await browser.elementByCss('#about-page p').text()
expect(text).toBe('This is the about page')
| r = await next.browser('/')
await browser.elementByCss('#about-via-link').click()
const text = await browser.elementByCss('#about-page p').text()
expect(text).toBe('This is the about page')
})
it('should do navig | {
"filepath": "test/production/with-electron/with-electron.test.ts",
"language": "typescript",
"file_size": 1003,
"cut_index": 512,
"middle_length": 229
} |
async () => {
await assertSingleGlobalCss(next, false, isTurbopack)
})
})
describe('with lightningcss', () => {
const { next, isTurbopack } = nextTestSetup({
files: join(__dirname, 'fixtures', 'single-global'),
nextConfig: {
productionBrowserSourceMaps: true,
experimental:... | ,
'single-global-special-characters',
'a+b'
),
nextConfig: {
productionBrowserSourceMaps: true,
},
})
it(`should've emitted a single CSS file`, async () => {
await assertSingleGlobalCss(next, false, | })
})
describe('Basic Global Support with special characters in path', () => {
describe('without lightningcss', () => {
const { next, isTurbopack } = nextTestSetup({
files: join(
__dirname,
'fixtures' | {
"filepath": "test/production/css-features/basic-global-support.test.ts",
"language": "typescript",
"file_size": 16347,
"cut_index": 921,
"middle_length": 229
} |
) => {
const { next, isTurbopack } = nextTestSetup({
files: join(__dirname, 'fixtures', 'browsers-old'),
})
it(`should've emitted a single CSS file`, async () => {
const $ = await next.render$('/')
const cssSheet = $('link[rel="stylesheet"]')
expect(cssSheet.length).toBe(1)
const stylesheet... | a:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==)}}"`
)
} else {
expect(cssContentWithoutSourceMap).toMatchInlineSnapshot(
`"a{-webkit-animation:none 0s ease 0s 1 normal none running;animation:none 0s | g, '')
.trim()
if (isTurbopack) {
expect(cssContentWithoutSourceMap).toMatchInlineSnapshot(
`"a{all:initial}@media (-webkit-min-device-pixel-ratio:2),(min-resolution:2dppx){.image{background-image:url(dat | {
"filepath": "test/production/css-features/browserslist.test.ts",
"language": "typescript",
"file_size": 4400,
"cut_index": 614,
"middle_length": 229
} |
packageJson: {
browserslist: ['chrome 60'],
},
})
it(`should've compiled and prefixed`, async () => {
const $ = await next.render$('/')
const cssSheet = $('link[rel="stylesheet"]')
expect(cssSheet.length).toBe(1)
const stylesheetUrl = cssSheet.attr('href... | r{color:green}}.flex-parsing{flex:0 0 calc(50% - var(--vertical-gutter))}.transform-parsing{transform:translate3d(0px, 0px)}.css-grid-shorthand{grid-column:span 2}.g-docs-sidenav .filter::-webkit-input-placeholder{opacity:.8}"`
)
} else i | *?\*\/\n?/g, '')
.trim()
if (isTurbopack && useLightningcss) {
expect(cssContentWithoutSourceMap).toMatchInlineSnapshot(
`"@media (min-width:480px) and (not (min-width:768px)){::placeholde | {
"filepath": "test/production/css-features/css-compilation.test.ts",
"language": "typescript",
"file_size": 31008,
"cut_index": 1331,
"middle_length": 229
} |
join } from 'path'
describe('Custom Properties: Pass-Through IE11', () => {
const { next, isTurbopack } = nextTestSetup({
files: join(__dirname, 'fixtures', 'cp-ie-11'),
})
it(`should've emitted a single CSS file`, async () => {
const $ = await next.render$('/')
const cssSheet = $('link[rel="styles... | cssContent.replace(/\/\*.*?\*\//g, '').trim()
).toMatchInlineSnapshot(`":root{--color:red}h1{color:var(--color)}"`)
}
})
})
describe('Custom Properties: Pass-Through Modern', () => {
const { next, isTurbopack } = nextTestSetup({
files | .*?\*\//g, '')
.trim()
if (isTurbopack) {
expect(
cssContent.replace(/\/\*.*?\*\//g, '').trim()
).toMatchInlineSnapshot(`":root{--color:red}h1{color:var(--color)}"`)
} else {
expect(
| {
"filepath": "test/production/css-features/css-features.test.ts",
"language": "typescript",
"file_size": 2605,
"cut_index": 563,
"middle_length": 229
} |
listClientChunks } from 'next-test-utils'
import path from 'path'
describe('CSS modules ordering — build output (unresolved-css-url)', () => {
const { next, isTurbopack } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'unresolved-css-url'),
skipStart: true,
dependencies: {
sass: '1.54.0'... | for (const file of cssFiles) {
const content = await next.readFile(path.join(next.distDir, file))
const svgCount = content.match(/\(\/vercel\.svg/g)?.length ?? 0
expect(svgCount === 1 || svgCount === 2).toBe(true)
if (isTurbopac | ut', async () => {
const distRoot = path.join(next.testDir, next.distDir)
const cssFiles = (await listClientChunks(distRoot)).filter((f) =>
f.endsWith('.css')
)
expect(cssFiles.length).toBeGreaterThan(0)
| {
"filepath": "test/production/css-features/css-modules-ordering.test.ts",
"language": "typescript",
"file_size": 2243,
"cut_index": 563,
"middle_length": 229
} |
= $('link[rel="stylesheet"]')
expect(cssSheet.length).toBe(1)
const stylesheet = cssSheet.attr('href')!
const cssContent = await next.fetch(stylesheet).then((res) => res.text())
if (isTurbopack) {
expect(
cssContent.replace(/\/\*.*?\*\//g, '').trim()
).toMatchInlineSnapshot(`".ind... | eload.attr('href')).toMatch(
/^\/_next\/static\/.*\.css(\?dpl=.*)?$/
)
const cssSheet = $('link[rel="stylesheet"]')
expect(cssSheet.length).toBe(1)
expect(cssSheet.attr('href')).toMatch(
/^\/_next\/static\/.*\.css(\?dpl=.*)?$/
| }
})
it(`should've injected the CSS on server render`, async () => {
const $ = await next.render$('/')
const cssPreload = $('link[rel="preload"][as="style"]')
expect(cssPreload.length).toBe(1)
expect(cssPr | {
"filepath": "test/production/css-features/css-modules-support.test.ts",
"language": "typescript",
"file_size": 11817,
"cut_index": 921,
"middle_length": 229
} |
from 'path'
// Turbopack uses LightningCSS which supports scoping `:root` to the CSS module.
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'Custom Properties: Fail for :root {} in CSS Modules',
() => {
const { next } = nextTestSetup({
files: join(__dirname, 'fixtures', 'cp-global-modules'... | n CSS Modules', () => {
const { next, isTurbopack } = nextTestSetup({
files: join(__dirname, 'fixtures', 'cp-el-modules'),
skipStart: true,
})
it('should fail to build', async () => {
const { exitCode, cliOutput } = await next.build()
| t).toContain('Failed to compile')
expect(cliOutput).toContain('pages/styles.module.css')
expect(cliOutput).toContain('Selector ":root" is not pure')
})
}
)
describe('Custom Properties: Fail for global element i | {
"filepath": "test/production/css-features/css-modules.test.ts",
"language": "typescript",
"file_size": 3842,
"cut_index": 614,
"middle_length": 229
} |
${useLightningcss},
},
}
`
}
describe('CSS Support', () => {
describe('CSS Import from node_modules', () => {
describe('experimental.useLightningcss: true', () => {
const { next } = nextTestSetup({
files: join(fixturesDir, 'npm-import-bad'),
dependencies: { nprogress: '0.2.0' },
s... | ).not.toMatch(/Can't resolve '[^']*?nprogress[^']*?'/)
expect(cliOutput).not.toMatch(/Build error occurred/)
})
})
// Webpack runs postcss/lightning toggles; Turbopack always uses Lightning CSS.
;(process.env.IS_TURBOPACK_TEST ? | false case below.
it('should build successfully without false nprogress resolution errors', async () => {
const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(0)
expect(cliOutput | {
"filepath": "test/production/css-features/css-rendering.test.ts",
"language": "typescript",
"file_size": 10890,
"cut_index": 921,
"middle_length": 229
} |
ument is allowed in Turbopack
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'Invalid CSS in _document',
() => {
const { next } = nextTestSetup({
files: join(__dirname, 'fixtures', 'invalid-module-document'),
skipStart: true,
})
it('should fail to build', async () => {
c... | ) {
expect(cliOutput).toMatch(/Location:.*pages[\\/]_document\.js/)
}
})
}
)
describe('Invalid Global CSS', () => {
const { next, isTurbopack } = nextTestSetup({
files: join(__dirname, 'fixtures', 'invalid-global'),
skipStart | ')
expect(cliOutput).toMatch(
/CSS.*cannot.*be imported within.*pages[\\/]_document\.js/
)
// Skip: Rspack loaders cannot access module issuer info for location details
if (!process.env.NEXT_RSPACK | {
"filepath": "test/production/css-features/valid-invalid-css.test.ts",
"language": "typescript",
"file_size": 3834,
"cut_index": 614,
"middle_length": 229
} |
Setup({
files: __dirname,
skipStart: true,
})
it('builds without error when export const config is used outside page', async () => {
const { cliOutput } = await next.build()
expect(cliOutput).not.toMatch(/Failed to compile\./)
})
it('shows valid error when page config is a string', async () =>... | ges/invalid/string-config.js', origContent)
}
})
it('shows valid error when page config has no init', async () => {
const origContent = await next.readFile('pages/invalid/no-init.js')
const newContent = origContent.replace('// export', 'ex | g-config.js', newContent)
try {
const { cliOutput } = await next.build()
expect(cliOutput).toContain(
"Next.js can't recognize the exported `config`"
)
} finally {
await next.patchFile('pa | {
"filepath": "test/production/page-config/page-config.test.ts",
"language": "typescript",
"file_size": 3057,
"cut_index": 614,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'Webpack - Bun Externals',
() => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
let buildExitCode: number
beforeAll(async () => {
const result = await next.build()... | 'bun:sqlite',
'bun:test',
'bun:wrap',
'bun',
]
bunModules.forEach((mod) => {
const escapedMod = mod.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
expect(serverBundle).toInclude(`require("${escapedMod}")` | )
})
it('should externalize Bun builtins in server bundles', async () => {
const serverBundle = await next.readFile('.next/server/pages/index.js')
const bunModules = [
'bun:ffi',
'bun:jsc',
| {
"filepath": "test/production/webpack-bun-externals/webpack-bun-externals.test.ts",
"language": "typescript",
"file_size": 1268,
"cut_index": 524,
"middle_length": 229
} |
rom 'child_process'
import { nextTestSetup } from 'e2e-utils'
import fs from 'fs-extra'
import { findPort, initNextServerScript, killApp } from 'next-test-utils'
import { join } from 'path'
describe('standalone mode: server actions', () => {
let server: ChildProcess
let appPort: number
const { next } = nextTest... | ne/.next/static')
)
for (const file of await fs.readdir(next.testDir)) {
if (file !== 'standalone') {
await fs.remove(join(next.testDir, file))
console.log('removed', file)
}
}
const testServer = join(next.test | Dir, 'standalone')
)
await fs.copy(
join(next.testDir, 'public'),
join(next.testDir, 'standalone/public')
)
await fs.copy(
join(next.testDir, '.next/static'),
join(next.testDir, 'standalo | {
"filepath": "test/production/standalone-mode/server-actions/standalone-mode-server-actions.test.ts",
"language": "typescript",
"file_size": 1916,
"cut_index": 537,
"middle_length": 229
} |
e client'
import { Component, type ReactNode } from 'react'
import { useActionState } from 'react'
class ErrorBoundary extends Component<
{ children: ReactNode },
{ error: string | null }
> {
constructor(props: { children: ReactNode }) {
super(props)
this.state = { error: null }
}
static getDerived... | ={formAction}>
<button>Submit</button>
{result && (
<p id="result" style={{ color: 'green' }}>
{result}
</p>
)}
</form>
)
}
export function FormWithErrorBoundary({
action,
}: {
action: () => Promise<st | .state.error}
</p>
)
}
return this.props.children
}
}
function Form({ action }: { action: () => Promise<string> }) {
const [result, formAction] = useActionState(action, '')
return (
<form action | {
"filepath": "test/production/standalone-mode/server-actions/app/[slug]/form.tsx",
"language": "tsx",
"file_size": 1100,
"cut_index": 515,
"middle_length": 229
} |
ath) when the
// @next/swc-wasm-nodejs package is available on the registry.
packageJson: {
scripts: {
build: 'next build',
},
},
installCommand: 'pnpm i',
buildCommand: 'pnpm build',
nextConfig: {
i18n: {
locales: ['en', 'fr'],
defaultLocale: 'en',
... | equiredFilesManifest
beforeAll(async () => {
process.env.NEXT_PRIVATE_TEST_HEADERS = '1'
const res = await nodeFetch(
`https://registry.npmjs.com/@next/swc-wasm-nodejs/-/swc-wasm-nodejs-${
require('next/package.json').version
| source: '/to-dynamic/:path',
destination: '/dynamic/:path',
},
]
},
},
skipStart: true,
})
let server: ChildProcess
let appPort: number | string
let errors = []
let r | {
"filepath": "test/production/standalone-mode/required-server-files/required-server-files-i18n.test.ts",
"language": "typescript",
"file_size": 27076,
"cut_index": 1331,
"middle_length": 229
} |
xt',
},
],
afterFiles: [
{
source: '/some-catch-all/:path*',
destination: '/',
},
{
source: '/to-dynamic/post-2',
destination: '/dynamic/post-2?hello=world',
},
{
... | 1'
process.env.NEXT_PRIVATE_TEST_HEADERS = '1'
let { exitCode } = await next.build()
if (exitCode !== 0) {
throw new Error(`Failed to build next: ${exitCode}`)
}
requiredFilesManifest = JSON.parse(
await next.readFile('.ne | appPort: number | string
let errors = []
let stderr = ''
let requiredFilesManifest
let minimalMode = true
beforeAll(async () => {
// test build against environment with next support
process.env.NOW_BUILDER = ' | {
"filepath": "test/production/standalone-mode/required-server-files/required-server-files.test.ts",
"language": "typescript",
"file_size": 45277,
"cut_index": 2151,
"middle_length": 229
} |
e
import next from 'next' // force a warning during `next build`
import { useRouter } from 'next/router'
export async function getServerSideProps({ res }) {
res.setHeader('cache-control', 's-maxage=1, stale-while-revalidate=31535999')
const data = await fs.promises.readFile(
path.join(process.cwd(), 'data.txt... | fetch('https://example.vercel.sh').then((res) =>
res.text()
),
},
}
}
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="gssp">getServerSideProps page</p>
<p id="router">{JSON.stri | / make sure fetch if polyfilled
example: await | {
"filepath": "test/production/standalone-mode/required-server-files/pages/gssp.js",
"language": "javascript",
"file_size": 971,
"cut_index": 582,
"middle_length": 52
} |
from 'e2e-utils'
import fs from 'fs-extra'
import glob from 'glob'
import {
findPort,
initNextServerScript,
killApp,
renderViaHTTP,
} from 'next-test-utils'
import { join } from 'path'
describe('standalone mode: ipv6 hostname', () => {
let server
let appPort
let output = ''
const { next } = nextTestSe... | , {
cwd: join(next.testDir, 'standalone/.next/server/pages'),
dot: true,
})
for (const file of files) {
if (file.endsWith('.json') || file.endsWith('.html')) {
await fs.remove(join(next.testDir, '.next/server', file))
|
for (const file of await fs.readdir(next.testDir)) {
if (file !== 'standalone') {
await fs.remove(join(next.testDir, file))
console.log('removed', file)
}
}
const files = glob.sync('**/*' | {
"filepath": "test/production/standalone-mode/ipv6/index.test.ts",
"language": "typescript",
"file_size": 1892,
"cut_index": 537,
"middle_length": 229
} |
tracing-side-effects-false', () => {
const dependencies = require('./package.json').dependencies
const { next, skipped } = nextTestSetup({
files: __dirname,
dependencies,
skipStart: true,
})
if (skipped) {
return
}
it('should trace sideeffect imports even when sideEffects is false', asyn... | index\.js$/)
)
expect(trace.files).toContainEqual(
expect.stringMatching(/node_modules\/foo\/package\.json$/)
)
expect(trace.files).toContainEqual(
expect.stringMatching(/node_modules\/foo\/side-effect\.js$/)
)
expect(tr | al(
expect.stringMatching(/node_modules\/foo\/ | {
"filepath": "test/production/standalone-mode/tracing-side-effects-false/tracing-side-effects-false.test.ts",
"language": "typescript",
"file_size": 992,
"cut_index": 582,
"middle_length": 52
} |
TP,
initNextServerScript,
fetchViaHTTP,
} from 'next-test-utils'
describe('minimal-mode-response-cache', () => {
let server
let port
let appPort
let output = ''
beforeAll(() => {
// test build against environment with next support
process.env.NOW_BUILDER = '1'
process.env.NEXT_PRIVATE_TEST_H... | ole.log('removed', file)
}
}
const files = glob.sync('**/*', {
cwd: join(next.testDir, 'standalone/.next/server'),
nodir: true,
dot: true,
})
for (const file of files) {
if (file.match(/(pages|app)[/\\]/) && ! | testDir, '.next/standalone'),
join(next.testDir, 'standalone')
)
for (const file of await fs.readdir(next.testDir)) {
if (file !== 'standalone') {
await fs.remove(join(next.testDir, file))
cons | {
"filepath": "test/production/standalone-mode/response-cache/index.test.ts",
"language": "typescript",
"file_size": 5794,
"cut_index": 716,
"middle_length": 229
} |
om 'e2e-utils'
describe('build trace with extra entries', () => {
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'production mode',
() => {
const { next, skipped } = nextTestSetup({
files: path.join(__dirname, 'app'),
skipStart: true,
skipDeployment: true,
})... | t.json')
)
const anotherTrace = JSON.parse(
await next.readFile('.next/server/pages/another.js.nft.json')
)
const imageTrace = JSON.parse(
await next.readFile('.next/server/pages/image-import.js.nft.json' | de).toBe(0)
const appTrace = JSON.parse(
await next.readFile('.next/server/pages/_app.js.nft.json')
)
const indexTrace = JSON.parse(
await next.readFile('.next/server/pages/index.js.nf | {
"filepath": "test/production/turbotrace-with-webpack-worker/turbotrace-with-webpack-worker.test.ts",
"language": "typescript",
"file_size": 2473,
"cut_index": 563,
"middle_length": 229
} |
from 'e2e-utils'
// Only Turbopack prints these warnings
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'build-tracing-message',
() => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
it('should warn when tracing all files in the project', async () => ... | xpected file in NFT list
A file was traced that indicates that the whole project was traced unintentionally. Somewhere in the import trace below, there are:
- filesystem operations (like path.join, path.resolve or fs.readFile), or
- ve | ),
next.cliOutput.indexOf('✓ Compiled successfully')
)
.trim()
expect(output).toMatchInlineSnapshot(`
"Turbopack build encountered 1 warnings:
./next.config.js
Encountered une | {
"filepath": "test/production/build-tracing-message/index.test.ts",
"language": "typescript",
"file_size": 1530,
"cut_index": 537,
"middle_length": 229
} |
{ nextTestSetup } from 'e2e-utils'
import path from 'path'
describe('app-type', () => {
describe('app-only', () => {
const { next } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'app-only'),
})
it('should have the app-only app type', async () => {
const requiredServerFiles = JSO... | t/routes-manifest.json')
)
expect(requiredServerFiles.appType).toBe('pages')
})
})
describe('hybrid', () => {
const { next } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'hybrid'),
})
it('should have th | } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'pages-only'),
})
it('should have the pages-only app type', async () => {
const requiredServerFiles = JSON.parse(
await next.readFile('.nex | {
"filepath": "test/production/app-type/app-type.test.ts",
"language": "typescript",
"file_size": 1222,
"cut_index": 518,
"middle_length": 229
} |
from 'e2e-utils'
import { fetchViaHTTP } from 'next-test-utils'
describe('dependencies can use env vars in middlewares', () => {
beforeAll(() => {
process.env.MY_CUSTOM_PACKAGE_ENV_VAR = 'my-custom-package-env-var'
process.env.ENV_VAR_USED_IN_MIDDLEWARE = 'env-var-used-in-middleware'
})
const { next } =... | () { return <div>Hello, world!</div> }
`,
'middleware.js': `
import customPackage from 'my-custom-package';
export default function middleware(_req) {
return new Response(null, {
headers: {
|
browser: 'index.js',
}),
'node_modules/my-custom-package/index.js': `
module.exports = () => process.env.MY_CUSTOM_PACKAGE_ENV_VAR;
`,
'pages/index.js': `
export default function | {
"filepath": "test/production/dependencies-can-use-env-vars-in-middlewares/index.test.ts",
"language": "typescript",
"file_size": 1833,
"cut_index": 537,
"middle_length": 229
} |
skipDeployment: true,
})
if (skipped) return
describe('new line', () => {
it('should have correct query on SSR', async () => {
const browser = await next.browser('/?test=abc%0A')
try {
const text = await browser.elementByCss('#query-content').text()
expect(text).to... | t text = await browser
.waitForElementByCss('#query-content')
.text()
expect(text).toBe('{"abc":"def\\n"}')
} finally {
await browser.close()
}
})
it('should have correct query on sim | next.browser('/')
try {
await browser.waitForCondition('!!window.next.router')
await browser.eval(
`window.next.router.push({pathname:'/',query:{abc:'def\\n'}})`
)
cons | {
"filepath": "test/production/query-with-encoding/query-with-encoding.test.ts",
"language": "typescript",
"file_size": 7476,
"cut_index": 716,
"middle_length": 229
} |
mport { nextTestSetup } from 'e2e-utils'
import { waitFor } from 'next-test-utils'
describe('Root Catch-all Cache', () => {
describe('production mode', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
const getRandom = async... | validate
await waitFor(1000)
const newRandom = await getRandom('/')
expect(random).toBe(newRandom)
}
{
//new response
await waitFor(100)
const newRandom = await getRandom('/')
expect(rando |
{
//cached response (revalidate is 2 seconds)
await waitFor(1000)
const newRandom = await getRandom('/')
expect(random).toBe(newRandom)
}
{
//stale response, triggers re | {
"filepath": "test/production/root-catchall-cache/root-catchall-cache.test.ts",
"language": "typescript",
"file_size": 1044,
"cut_index": 513,
"middle_length": 229
} |
const { next } = nextTestSetup({
files: {
'pages/index.js': `
import styles from './index.module.css'
export default function Page() {
return <p className={styles.home}>hello world</p>
}
`,
'pages/index.module.css': `
.home {
backgr... | mizeCss is broken when ?dpl is added to CSS URLs
disableAutoSkewProtection: true,
})
it('should work', async () => {
const html = await next.render('/')
expect(html).toContain('hello world')
expect(html).toContain('background:orange')
| {
critters: '0.0.16',
},
// TODO opti | {
"filepath": "test/production/standalone-mode/optimizecss/index.test.ts",
"language": "typescript",
"file_size": 922,
"cut_index": 606,
"middle_length": 52
} |
am {import('http').ServerResponse} res
* @returns {{
* onCacheEntry: import('next/dist/server/request-meta').OnCacheEntryHandler,
* onCacheEntryV2: import('next/dist/server/request-meta').OnCacheEntryHandler
* }}
*/
module.exports = (res) => ({
onCacheEntry: (cacheEntry, meta) => {
// If this isn't a sta... | ')
return false
}
// If this is for a RSC request, then mark it as a miss.
if (meta.url.endsWith('.rsc')) {
res.setHeader('x-nextjs-cache-entry-handler', 'MISS_1')
return false
}
// Mark this as a hit against the cac | typeof cacheEntry.value.html.toUnchunkedString !== 'function' ||
!cacheEntry.value.postponed ||
!meta.url ||
typeof meta.url !== 'string'
) {
res.setHeader('x-nextjs-cache-entry-handler', 'MISS_1 | {
"filepath": "test/production/standalone-mode/required-server-files/cache-entry-handlers.js",
"language": "javascript",
"file_size": 1992,
"cut_index": 537,
"middle_length": 229
} |
=
'./cache-entry-handlers.js'
})
const { next } = nextTestSetup({
files: {
app: new FileRef(join(__dirname, 'app')),
'pages/catch-all/[[...rest]].js': new FileRef(
join(__dirname, 'pages', 'catch-all', '[[...rest]].js')
),
lib: new FileRef(join(__dirname, 'lib')),
'c... | new FileRef(
join(__dirname, 'cache-entry-handlers.js')
),
},
overrideFiles: {
'app/not-found.js': new FileRef(
join(__dirname, 'ppr', 'app', 'not-found.js')
),
},
nextConfig: {
cacheHandler: './cache | t')),
'.env': new FileRef(join(__dirname, '.env')),
'.env.local': new FileRef(join(__dirname, '.env.local')),
'.env.production': new FileRef(join(__dirname, '.env.production')),
'cache-entry-handlers.js': | {
"filepath": "test/production/standalone-mode/required-server-files/required-server-files-ppr.test.ts",
"language": "typescript",
"file_size": 20507,
"cut_index": 1331,
"middle_length": 229
} |
ort const getStaticProps = ({ params }) => {
console.log('getStaticProps /optional-ssg/[[...rest]]', params)
switch (params.rest?.[0]) {
case 'redirect-1': {
return {
redirect: { destination: '/somewhere', permanent: false },
}
}
case 'redirect-2': {
return {
redirect:... | }
}
default: {
break
}
}
return {
props: {
random: Math.random(),
params: params || null,
},
revalidate: 1,
}
}
export const getStaticPaths = () => {
return {
paths: [],
fallback: true,
}
}
e | ': {
return {
notFound: true,
revalidate: 5,
}
}
case 'props-no-revalidate': {
return {
props: {
random: Math.random(),
params: params || null,
},
| {
"filepath": "test/production/standalone-mode/required-server-files/pages/optional-ssg/[[...rest]].js",
"language": "javascript",
"file_size": 1090,
"cut_index": 515,
"middle_length": 229
} |
('Build warnings', () => {
describe('minification warnings', () => {
const { next, isTurbopack } = nextTestSetup({
files: __dirname,
skipStart: true,
})
it('should not show warning about minification without any modification', async () => {
const start = next.cliOutput.length
awai... | }`
)
const start = next.cliOutput.length
await next.build()
// eslint-disable-next-line jest/no-standalone-expect
expect(next.cliOutput.slice(start)).toContain(
'optimization has been disabled'
)
| out minification for minimize',
async () => {
await next.patchFile(
'next.config.js',
`module.exports = {
webpack: (config) => {
config.optimization.minimize = false
return config
},
| {
"filepath": "test/production/build-warnings/build-warnings.test.ts",
"language": "typescript",
"file_size": 3031,
"cut_index": 563,
"middle_length": 229
} |
t { nextTestSetup } from 'e2e-utils'
describe('image-generation', () => {
describe('production mode', () => {
const { next, isNextStart } = nextTestSetup({
files: __dirname,
dependencies: {
'@vercel/og': '0.11.1',
},
})
if (!isNextStart) {
it('skipped for non-start mode',... | et('Content-Type')).toBe('image/png')
const buffer = await res.buffer()
// It should be a PNG
expect(
[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every(
(b, i) => buffer[i] === b
)
).toBeTrue()
} | (res.headers.g | {
"filepath": "test/production/image-generation/image-generation.test.ts",
"language": "typescript",
"file_size": 797,
"cut_index": 517,
"middle_length": 14
} |
from 'e2e-utils'
describe('Page Extensions', () => {
describe('production mode', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) return
it('should use the default pageExtensions if set to undefined', async (... | t next.build()
expect(next.cliOutput).toContain(
'Specified pageExtensions is an empty array. Please update it with the relevant extensions or remove it'
)
})
it('should throw if pageExtensions has invalid extensions', async ( | 'Compiled successfully')
})
it('should throw if pageExtensions is an empty array', async () => {
await next.patchFile(
'next.config.js',
`module.exports = { pageExtensions: [] }`
)
awai | {
"filepath": "test/production/page-extensions/page-extensions.test.ts",
"language": "typescript",
"file_size": 1679,
"cut_index": 537,
"middle_length": 229
} |
killApp,
retry,
waitFor,
} from 'next-test-utils'
import fs from 'fs-extra'
import glob from 'glob'
import { LONG_RUNNING_MS } from './src/pages/api/long-running'
import { once } from 'events'
const appDir = join(__dirname, './src')
let appPort: number
let app: ChildProcess
let currentExit: Promise<any> | undefi... | resolveReady = () => {
if (!ready) {
ready = true
r()
}
}
})
const exit = next
.runCommand(args, {
onStdout: (msg) => {
if (readyPattern.test(msg)) resolveReady()
},
onStderr: (msg) => {
| RegExp = /- Local:|✓ Ready|Ready in/i
): Promise<{ child: ChildProcess; exit: Promise<any> }> {
let child!: ChildProcess
let resolveReady!: () => void
let ready = false
const readyPromise = new Promise<void>((r) => {
| {
"filepath": "test/production/graceful-shutdown/index.test.ts",
"language": "typescript",
"file_size": 8253,
"cut_index": 716,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
describe('standalone mode - tracing-static-files', () => {
const dependencies = require('./package.json').dependencies
const { next, skipped } = nextTestSetup({
files: __dirname,
dependencies,
skipStart: true,
})
if (skipped) {
return
}
it('should trace proc... | tive reference
expect(trace.files).toContain(
'../../../data/static-from-app-rel-join.txt'
)
expect(trace.files).toContain(
'../../../data/static-from-app-rel-read.txt'
)
}
if (process.env.IS_TURBOPACK_TEST) | // should trace process.cwd and relative calls relative to the root
expect(trace.files).toContain('../../../data/static-from-app-cwd.txt')
if (process.env.IS_TURBOPACK_TEST) {
// Webpack doesn't trace these rela | {
"filepath": "test/production/standalone-mode/tracing-static-files/tracing-static-files.test.ts",
"language": "typescript",
"file_size": 1429,
"cut_index": 524,
"middle_length": 229
} |
next } = nextTestSetup({
files: {
app: new FileRef(join(__dirname, 'app')),
lib: new FileRef(join(__dirname, 'lib')),
'cache-handler.js': new FileRef(join(__dirname, 'cache-handler.js')),
'middleware.js': new FileRef(join(__dirname, 'middleware.js')),
'data.txt': new FileRef(join(__di... | tring
beforeAll(async () => {
// test build against environment with next support
process.env.NOW_BUILDER = '1'
process.env.NEXT_PRIVATE_TEST_HEADERS = '1'
const { exitCode } = await next.build()
if (exitCode !== 0) {
throw ne | env.production')),
},
nextConfig: {
cacheHandler: './cache-handler.js',
cacheMaxMemorySize: 0,
output: 'standalone',
},
skipStart: true,
})
let server: ChildProcess
let appPort: number | s | {
"filepath": "test/production/standalone-mode/required-server-files/required-server-files-app.test.ts",
"language": "typescript",
"file_size": 12883,
"cut_index": 921,
"middle_length": 229
} |
ire('path')
module.exports = {
webpack(cfg, { isServer, nextRuntime }) {
console.log(cfg.entry)
const origEntry = cfg.entry
cfg.entry = async () => {
const origEntries = await origEntry()
if (isServer && nextRuntime === 'nodejs') {
const curEntry = origEntries['pages/_app']
o... | dex': ['include-me/*'],
},
outputFileTracingExcludes: {
'/index': ['public/exclude-me/**/*'],
},
experimental: {
turbotrace: {
contextDirectory: path.join(__dirname, '..', '..', '..', '..'),
memoryLimit: 2048,
},
webpack | urn cfg
},
outputFileTracingIncludes: {
'/in | {
"filepath": "test/production/turbotrace-with-webpack-worker/app/next.config.js",
"language": "javascript",
"file_size": 863,
"cut_index": 529,
"middle_length": 52
} |
from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('Revalidate asPath Normalizing', () => {
const { next } = nextTestSetup({
files: __dirname,
})
const checkAsPath = async (urlPath: string, expectedAsPath: string) => {
const $ = await next.render$(urlPath)
const asPath = $('#as-path')... | utput = next.cliOutput.slice(outputIndex)
expect(newOutput).toContain('asPath')
})
const newOutput = next.cliOutput.slice(outputIndex)
const asPath = newOutput.split('asPath: ').pop()!.split('\n').shift()
expect(asPath).toBe('/')
}) | const path = `/_next/data/${next.buildId}/index.json`
await retry(async () => {
const data = await next.render(path)
expect(JSON.parse(data).pageProps).toEqual({
hello: 'world',
})
const newO | {
"filepath": "test/production/revalidate-as-path/revalidate-as-path.test.ts",
"language": "typescript",
"file_size": 1942,
"cut_index": 537,
"middle_length": 229
} |
ort fs from 'fs'
import cheerio from 'cheerio'
import { nextTestSetup } from 'e2e-utils'
describe('Export Dynamic Pages', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
let server: http.Server
let port: number
beforeAll(async () => {
await next.build()
const ... | ad(404)
res.end('Not Found')
return
}
const ext = path.extname(filePath)
const contentType =
{
'.html': 'text/html',
'.js': 'application/javascript',
'.css': 'text/cs | th)
} catch {}
let filePath = path.join(outDir, urlPath)
if (!path.extname(filePath)) {
filePath += '.html'
}
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHe | {
"filepath": "test/production/export-dynamic-pages/export-dynamic-pages.test.ts",
"language": "typescript",
"file_size": 2122,
"cut_index": 563,
"middle_length": 229
} |
join } from 'path'
import fs from 'fs-extra'
import cheerio from 'cheerio'
import {
fetchViaHTTP,
findPort,
initNextServerScript,
killApp,
} from 'next-test-utils'
describe('type-module', () => {
const { next } = nextTestSetup({
files: __dirname,
packageJson: {
type: 'module',
},
})
it... | // walks up to the project package.json and tries to load the server
// bundles as ESM, which fails at runtime.
const distPackageJsonPath = join(standalonePath, '.next', 'package.json')
expect(fs.existsSync(distPackageJsonPath)).toBe(true)
| )
// The distDir package.json acts as a commonjs boundary marker so that
// server bundles in `.next/server/**/*.js` are loaded as CJS even when
// the user's project has `"type": "module"`. Without this file, Node
| {
"filepath": "test/production/standalone-mode/type-module/index.test.ts",
"language": "typescript",
"file_size": 2022,
"cut_index": 563,
"middle_length": 229
} |
{ nextTestSetup } from 'e2e-utils'
describe('typeof window replace', () => {
describe('production mode', () => {
const { next, skipped } = nextTestSetup({
files: path.join(__dirname, 'app'),
skipStart: true,
skipDeployment: true,
})
if (skipped) return
let buildManifest: any
b... | = await next.readFile(path.join('.next', file))
allContent += content
}
expect(allContent).toMatch(/Hello.*?,.*?\n?.*?("|')object("|')/)
})
it('Replaces `typeof window` with undefined for server code', async () => {
let a | object for client code', async () => {
let allContent = ''
const files = buildManifest.pages['/'].filter((item: string) =>
item.endsWith('.js')
)
for (const file of files) {
const content | {
"filepath": "test/production/typeof-window-replace/typeof-window-replace.test.ts",
"language": "typescript",
"file_size": 2402,
"cut_index": 563,
"middle_length": 229
} |
ort { nextTestSetup } from 'e2e-utils'
describe('standalone mode - tracing-unparsable', () => {
const dependencies = require('./package.json').dependencies
const { next, skipped } = nextTestSetup({
files: __dirname,
dependencies,
skipStart: true,
})
if (skipped) {
return
}
it('should not... | )
)
expect(trace.files).toContainEqual(
expect.stringMatching(/.*\/node_modules\/foo\/index\.js$/)
)
expect(trace.files).toContainEqual(
expect.stringMatching(/.*\/node_modules\/foo\/value\.js$/)
)
expect(trace.files).to | page.js.nft.json')
expect(trace.files).toContainEqual(
expect.stringMatching(/.*\/node_modules\/foo\/LICENSE$/)
)
expect(trace.files).toContainEqual(
expect.stringMatching(/.*\/node_modules\/foo\/binary$/ | {
"filepath": "test/production/standalone-mode/tracing-unparsable/tracing-unparsable.test.ts",
"language": "typescript",
"file_size": 1097,
"cut_index": 515,
"middle_length": 229
} |
= nextTestSetup({
files: __dirname,
dependencies: { sass: '1.54.0' },
env: {
NEXT_DEPLOYMENT_ID: 'test-deployment-id',
},
disableAutoSkewProtection: true,
})
it('should include dpl query in CSS url() references for images and fonts', async () => {
const $ = await next.render$('/')
... | tents
let allCssContent = ''
for (const cssUrl of cssUrls) {
const res = await next.fetch(cssUrl)
const cssText = await res.text()
allCssContent += cssText + '\n'
}
// Also collect inline style content
for (const styl | if (href && href.includes('.css')) {
cssUrls.push(href)
}
}
// Also check for inline styles that may contain CSS
const styles = Array.from($('style'))
// Fetch all CSS files and collect their con | {
"filepath": "test/production/css-url-deployment-id/css-url-deployment-id.test.ts",
"language": "typescript",
"file_size": 3328,
"cut_index": 614,
"middle_length": 229
} |
mport fs from 'fs-extra'
import { nextTestSetup } from 'e2e-utils'
describe('CPU Profiling', () => {
const { next } = nextTestSetup({
files: path.join(__dirname, 'fixtures/basic-app'),
skipStart: true,
})
describe('next build --experimental-cpu-prof', () => {
it('should create CPU profile files with... | : string) => f.endsWith('.cpuprofile'))
expect(cpuProfiles.length).toBeGreaterThan(0)
for (const profile of cpuProfiles) {
expect(profile).toMatch(
/^(build-main|build-webpack-(server|client|edge-server)|build-turbopack|build | (next.testDir, '.next-profiles')
const profileDirExists = await fs.pathExists(profileDir)
expect(profileDirExists).toBe(true)
const files = await fs.readdir(profileDir)
const cpuProfiles = files.filter((f | {
"filepath": "test/production/cpu-profiling/cpu-profiling.test.ts",
"language": "typescript",
"file_size": 1678,
"cut_index": 537,
"middle_length": 229
} |
{ nextTestSetup } from 'e2e-utils'
describe('handle already sent response', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should work with fetch', async () => {
expect(next.cliOutput).toContain('▲ Next.js')
expect(next.cliOutput).toContain('- Local:')
let res = await next.f... | Props/g) || []).length >= 2) {
break
}
await new Promise((resolve) => setTimeout(resolve, 1000))
}
if (i === 3) {
throw new Error('Timed out waiting for logs to show')
}
// Headers should not be added after respon | Check to see that there's two instances of 'getServerSideProps' in
// the output. If there's only one, then the page was not re-rendered.
let i
for (i = 0; i < 3; i++) {
if ((next.cliOutput.match(/getServerSide | {
"filepath": "test/production/handle-already-sent-response/handle-already-sent-response.test.ts",
"language": "typescript",
"file_size": 1162,
"cut_index": 518,
"middle_length": 229
} |
from 'e2e-utils'
describe('no-op export', () => {
describe('all server-side pages build', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
it('should not error for all server-side pages build', async () => {
await next.patchFile(
'pages/_error.js',... | {
return {
paths: [],
fallback: false
}
}
export default function Page() {
return 'page'
}
`
)
const { exitCode } = await next.build()
expect(exitCode).toBe(0)
})
})
describe('empty exportPathMap', () => {
const | }
}
render() {
return 'error page'
}
}
`
)
await next.patchFile(
'pages/[slug].js',
`
export const getStaticProps = () => {
return {
props: {}
}
}
export const getStaticPaths = () => | {
"filepath": "test/production/no-op-export/no-op-export.test.ts",
"language": "typescript",
"file_size": 1548,
"cut_index": 537,
"middle_length": 229
} |
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 [
{
source: '/some-rewrite',
destination: '/',
},
]
},
redirects()... | },
{
source: '/shadowed-page',
destination: '/about',
permanent: false,
},
{
source: '/redirect-query-test/:path',
destination: '/about?foo=:path',
permanent: false,
},
]
},
}
| estination: '/about',
permanent: false,
| {
"filepath": "test/production/production-start-no-build/next.config.js",
"language": "javascript",
"file_size": 820,
"cut_index": 512,
"middle_length": 52
} |
m 'next'
import { nextTestSetup } from 'e2e-utils'
import { version as nextVersion } from 'next/package.json'
process.env.TEST_EXPORT = '1'
describe('adapter-config export', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
it('should call onBuildComplete with correct conte... | ',
'app/node-app/[slug]/page.tsx',
'app/node-app/@dialog/default.tsx',
'app/node-app/@dialog/[slug]/page.tsx',
]
for (const file of nonExportFiles) {
await next.remove(file)
}
await next.build()
expect(next.cli | pp/isr-route/route.ts',
'app/isr-route/[slug]/route.ts',
'app/edge-app/page.tsx',
'pages/api/edge-pages.ts',
'pages/api/node-pages.ts',
'pages/edge-pages/index.tsx',
'pages/node-pages/index.tsx | {
"filepath": "test/production/adapter-config/adapter-config-export.test.ts",
"language": "typescript",
"file_size": 2727,
"cut_index": 563,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
describe('Invalid config syntax', () => {
describe('production mode', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) return
it('should error when next.config.js contains syntax... | should error when next.config.mjs contains syntax error', async () => {
// Remove any existing config files first to avoid Next.js prioritizing .js over .mjs
await next.deleteFile('next.config.js').catch(() => {})
await next.patchFile(
| expect(next.cliOutput).toContain(
'Failed to load next.config.js, see more info here https://nextjs.org/docs/messages/next-config-error'
)
expect(next.cliOutput).toContain('SyntaxError')
})
it(' | {
"filepath": "test/production/config-syntax-error/config-syntax-error.test.ts",
"language": "typescript",
"file_size": 1405,
"cut_index": 524,
"middle_length": 229
} |
P build errors', () => {
const { next, isTurbopack } = nextTestSetup({
files: __dirname,
skipStart: true,
})
;(isTurbopack ? it.skip : it)(
'should fail build from module not found',
async () => {
await next.patchFile(
'pages/test.js',
`
__non_webpack_require__('a-cool... | export function getStaticProps() {
require('fs').readFileSync('a-cool-file')
return {
props: {}
}
}
export default function () {
return null
}
`
)
const { cliOutput } = await ne | onst { cliOutput } = await next.build()
expect(cliOutput).toContain('a-cool-module')
}
)
it('should fail build from ENOENT in getStaticProps', async () => {
await next.patchFile(
'pages/test.js',
`
| {
"filepath": "test/production/gsp-build-errors/gsp-build-errors.test.ts",
"language": "typescript",
"file_size": 3753,
"cut_index": 614,
"middle_length": 229
} |
import createMdx from '@next/mdx'
const withMdx = createMdx()
export default withMdx({
typedRoutes: true,
pageExtensions: ['js', 'jsx', 'ts', 'tsx', 'mdx'],
async rewrites() {
return [
{
source: '/rewrite',
destination: 'https://nextjs.org',
},
{
source: '/rewrite... | [
{
source: '/redirect',
destination: 'https://nextjs.org',
permanent: false,
},
{
source: '/redirect(/v1)?/guides/:param/page',
destination: 'https://nextjs.org',
permanent: false,
} | ce: '/rewrite-all/:param*',
destination: 'https://nextjs.org',
},
{
source: '/rewrite-param/:param/page',
destination: 'https://nextjs.org',
},
]
},
async redirects() {
return | {
"filepath": "test/production/app-types/next.config.js",
"language": "javascript",
"file_size": 1013,
"cut_index": 512,
"middle_length": 229
} |
rt Link from 'next/link'
export function Card<T extends string>({ href }: { href: Route<T> | URL }) {
return (
<Link href={href}>
<div>My Card</div>
</Link>
)
}
export default function page() {
const test = 'a/b'
const shouldFail = (
<>
<Card href="/(newroot)/dashboard/another" />
... | /dashboard">test</Link>
<Link href={`/blog/a/${test}`}>test</Link>
<Link href="/rewrite-any">test</Link>
<Link href="/rewrite-one-or-more">test</Link>
<Link href="/rewrite-param/page">test</Link>
<Link href="/rewrite-param/x/p | Link href="/blog/">test</Link>
<Link href="/blog/a?1/b">test</Link>
<Link href="/blog/a#1/b">test</Link>
<Link href="/blog/v/w/z">test</Link>
<Link href="/(newroot)/dashboard/another" />
<Link href=" | {
"filepath": "test/production/app-types/src/app/type-checks/link/page.tsx",
"language": "tsx",
"file_size": 2655,
"cut_index": 563,
"middle_length": 229
} |
import { nextTestSetup } from 'e2e-utils'
describe('Polyfills', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
unfetch: '4.2.0',
'isomorphic-unfetch': '3.0.0',
'whatwg-fetch': '3.0.0',
},
})
it('should alias fetch', async () => {
const browser = awai... | page count in output', async () => {
const output = next.cliOutput
expect(output).toMatch(/Generating static pages.*\(0\/5\)/g)
expect(output).toMatch(/Generating static pages.*\(5\/5\)/g)
expect(output.match(/Generating static pages/g).len | th `id` of `process`', async () => {
const browser = await next.browser('/process')
const text = await browser.elementByCss('#process').text()
expect(text).toBe('Hello, stranger')
})
it('should contain generated | {
"filepath": "test/production/polyfills/polyfills.test.ts",
"language": "typescript",
"file_size": 1018,
"cut_index": 512,
"middle_length": 229
} |
Setup } from 'e2e-utils'
import {
getClientBuildManifestLoaderChunkUrlPath,
retry,
} from 'next-test-utils'
describe('Failing to load _error', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('handles failing to load _error correctly', async () => {
const chunk = getClientBuildManife... | },
})
await browser.eval(`window.beforeNavigate = true`)
await browser.elementByCss('#to-broken').click()
await retry(async () => {
const beforeNavigate = await browser.eval('window.beforeNavigate')
expect(beforeNavigate).to | route.abort('blockedbyclient')
})
| {
"filepath": "test/production/error-load-fail/error-load-fail.test.ts",
"language": "typescript",
"file_size": 862,
"cut_index": 529,
"middle_length": 52
} |
tTestSetup } from 'e2e-utils'
import { check, renderViaHTTP } from 'next-test-utils'
describe('ENOENT during require', () => {
const { next } = nextTestSetup({
files: {
'pages/_app.js': `
import App from 'next/app'
if (typeof window === 'undefined') {
if (process.env.NEXT... | export default function Page() {
return <p>hello world</p>
}
`,
},
dependencies: {},
})
it('should show ENOENT error correctly', async () => {
await check(async () => {
await renderViaHTTP(next.url, '/' | export function getStaticProps() {
console.log('revalidate /')
return {
props: {
now: Date.now()
},
revalidate: 1
}
}
| {
"filepath": "test/production/enoent-during-require/index.test.ts",
"language": "typescript",
"file_size": 1252,
"cut_index": 524,
"middle_length": 229
} |
g library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a... | library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big l | brary. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big | {
"filepath": "test/production/remove-unused-imports/library/b.js",
"language": "javascript",
"file_size": 3792,
"cut_index": 614,
"middle_length": 229
} |
import { nextTestSetup } from 'e2e-utils'
describe('Side-effect imports with noUncheckedSideEffectImports', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
dependencies: { sass: '1.54.0' },
skipStart: true,
})
if (skipped) return
let buildResult: Awaited<ReturnType<(typeof next... | toContain('client-only')
expect(buildResult.cliOutput).not.toContain('globals.css')
expect(buildResult.cliOutput).not.toContain('globals.sass')
expect(buildResult.cliOutput).not.toContain('globals.scss')
expect(buildResult.exitCode).toBe(0) | of these modules, TSC will error with:
// `Type error: Cannot find module '...' or its corresponding type declarations.`
expect(buildResult.cliOutput).not.toContain('server-only')
expect(buildResult.cliOutput).not. | {
"filepath": "test/production/typescript-checked-side-effect-imports/index.test.ts",
"language": "typescript",
"file_size": 1006,
"cut_index": 512,
"middle_length": 229
} |
p } from 'e2e-utils'
import { findPort, startStaticServer, stopApp } from 'next-test-utils'
import { join } from 'path'
const itHeaded = process.env.HEADLESS ? it.skip : it
describe('bfcache-routing', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
let port: number
let ... | stored from bfcache after an mpa navigation',
async () => {
// bfcache is not currently supported by CDP, so we need to run this particular test in headed mode
// https://bugs.chromium.org/p/chromium/issues/detail?id=1317959
const br | join(next.testDir, 'out')
port = await findPort()
app = await startStaticServer(exportDir, undefined, port)
})
afterAll(() => {
stopApp(app)
})
itHeaded(
'should not suspend indefinitely when page is re | {
"filepath": "test/production/bfcache-routing/index.test.ts",
"language": "typescript",
"file_size": 2542,
"cut_index": 563,
"middle_length": 229
} |
/ This page tests that Bun modules are properly externalized
export default function Page() {
return <div>Webpack Bun Externals Test</div>
}
export async function getServerSideProps() {
const results = {}
try {
require('bun:ffi')
results['bun:ffi'] = 'loaded'
} catch (e) {
results['bun:ffi'] = 'ex... | (not found)'
}
try {
require('bun:wrap')
results['bun:wrap'] = 'loaded'
} catch (e) {
results['bun:wrap'] = 'external (not found)'
}
try {
require('bun')
results['bun'] = 'loaded'
} catch (e) {
results['bun'] = 'extern |
results['bun:sqlite'] = 'loaded'
} catch (e) {
results['bun:sqlite'] = 'external (not found)'
}
try {
require('bun:test')
results['bun:test'] = 'loaded'
} catch (e) {
results['bun:test'] = 'external | {
"filepath": "test/production/webpack-bun-externals/pages/index.js",
"language": "javascript",
"file_size": 1053,
"cut_index": 513,
"middle_length": 229
} |
from 'fs-extra'
import path from 'path'
function extractSourceMappingURL(jsContent) {
// Matches both //# and //@ sourceMappingURL=...
const match = jsContent.match(/\/\/[#@] sourceMappingURL=([^\s]+)/)
expect(match).toBeDefined()
return match ? match[1] : null
}
describe('Middleware source maps', () => {
... | .files) {
const filePath = path.join(next.testDir, '.next', file)
expect(await fs.pathExists(filePath)).toEqual(true)
let sourcemap = decodeURI(
extractSourceMappingURL(await fs.readFile(filePath, 'utf8'))
)
| /middleware-manifest.json'
)
for (const key in middlewareManifest.middleware) {
const middleware = middlewareManifest.middleware[key]
expect(middleware.files).toBeDefined()
for (const file of middleware | {
"filepath": "test/production/generate-middleware-source-maps/index.test.ts",
"language": "typescript",
"file_size": 2159,
"cut_index": 563,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.