prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
tRedboxHeader, getDeploymentId, retry, } from 'next-test-utils' describe('Image Component basePath Tests', () => { const { next, skipped } = nextTestSetup({ files: __dirname, disableAutoSkewProtection: true, // Image URL assertions construct expected URLs via // `getDeploymentId(next.testDir, ......
string beforeAll(() => { dpl = getDeploymentId(next.testDir, isNextDev).getDeploymentIdQuery(true) }) async function getImageUrls(browser) { return await Promise.all( (await browser.elementsByCss('img')).map(async (link) => ne
URL omits the `&dpl=...` query that Vercel injects at // runtime. The assertions are about local-build URL shape, not deploy // CDN URLs, so skip in deploy. skipDeployment: true, }) if (skipped) return let dpl:
{ "filepath": "test/e2e/next-image-new/base-path/base-path.test.ts", "language": "typescript", "file_size": 4636, "cut_index": 614, "middle_length": 229 }
allow Routing', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should not shallowly navigate back in history when current page was not shallow', async () => { const browser = await next.browser('/first') const props = JSON.parse(await browser.elementByCss('#props').text()) exp...
text()) expect(props3).toEqual(props) }) await browser.elementByCss('#to-another').click() await retry(async () => { const text = await browser.elementByCss('#props').text() expect(text).toMatch(/another/) }) const p
Css('#props').text()) expect(props2).toEqual(props) }) await browser.elementByCss('#remove-query-shallow').click() await retry(async () => { const props3 = JSON.parse(await browser.elementByCss('#props').
{ "filepath": "test/e2e/client-shallow-routing/client-shallow-routing.test.ts", "language": "typescript", "file_size": 3120, "cut_index": 614, "middle_length": 229 }
, } } describe('Prerender Preview Mode', () => { const { next, isNextDev, isNextStart } = nextTestSetup({ files: __dirname, dependencies: { cookie: '0.7.2', }, }) if (isNextStart) { it('should return prerendered page on first request', async () => { const html = await next.render('...
} = getData(html) expect(nextData).toMatchObject({ isFallback: false }) expect(nextData.isPreview).toBeUndefined() expect(pre).toBe('false and null') expect(routerData.isPreview).toBe(false) }) } it('should throw error whe
e('false and null') expect(routerData.isPreview).toBe(false) }) it('should return prerendered page on second request', async () => { const html = await next.render('/') const { nextData, pre, routerData
{ "filepath": "test/e2e/prerender-preview/prerender-preview.test.ts", "language": "typescript", "file_size": 12011, "cut_index": 921, "middle_length": 229 }
i18n } = require('./next.config') const pages = [ { url: '/about', page: '/about', params: null }, { url: '/blog/about', page: '/[slug]/about', params: { slug: 'blog' } }, ] function checkDataRoute(data: any, page: string) { expect(data).toHaveProperty('pageProps') expect(data.pageProps).toHaveProperty('page'...
describe('with locale prefix', () => { describe.each(i18n.locales)('/%s', (locale) => { const prefixed = pages.map((page) => ({ ...page, url: `/${locale}${page.url}`, })) it.each(prefixed)( 'should render $
prefixed // are not supported. skipDeployment: true, env: { // Disable internal header stripping so we can test the invoke output. __NEXT_NO_STRIP_INTERNAL_HEADERS: '1', }, }) if (skipped) return
{ "filepath": "test/e2e/i18n-data-route/i18n-data-route.test.ts", "language": "typescript", "file_size": 2769, "cut_index": 563, "middle_length": 229 }
xt-test-utils' import fs from 'fs-extra' import path from 'path' const warningText = `You are using a non-standard "NODE_ENV" value in your environment` describe('Non-Standard NODE_ENV', () => { ;(isNextDev ? describe : describe.skip)('dev mode', () => { describe('no NODE_ENV set', () => { const { next } ...
to valid value', async () => { expect(next.cliOutput).not.toContain(warningText) }) }) describe('NODE_ENV=development (custom server)', () => { const { next } = nextTestSetup({ files: __dirname, startCommand: '
}) }) describe('NODE_ENV=development', () => { const { next } = nextTestSetup({ files: __dirname, env: { NODE_ENV: 'development' }, }) it('should not show the warning with NODE_ENV set
{ "filepath": "test/e2e/non-standard-node-env-warning/non-standard-node-env-warning.test.ts", "language": "typescript", "file_size": 4949, "cut_index": 614, "middle_length": 229 }
rated SignedSource<<187ead9fb6e7b26d71c9161bda6ab902>> * @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 pagesQ...
ns: [], kind: 'Fragment', metadata: null, name: 'pagesQuery', selections: v0 /*: any*/, type: 'Query', abstractKey: null, }, kind: 'Request', operation: { argumentDefinitions: [], kind: 'Operation
de: ConcreteRequest = (function () { var v0 = [ { alias: null, args: null, kind: 'ScalarField', name: 'greeting', storageKey: null, }, ] return { fragment: { argumentDefinitio
{ "filepath": "test/e2e/relay-graphql-swc-single-project/queries/__generated__/pagesQuery.graphql.ts", "language": "typescript", "file_size": 1380, "cut_index": 524, "middle_length": 229 }
xtProd = !(global as any).isNextDev && !(global as any).isNextDeploy describe('streaming SSR with custom next configs', () => { const { next } = nextTestSetup({ files: join(__dirname, 'streaming-ssr'), }) it('should match more specific route along with dynamic routes', async () => { const res1 = await f...
and render when slash is appended', async () => { const page = '/hello' const redirectRes = await fetchViaHTTP( next.url, page, {}, { redirect: 'manual' } ) const res = await fetchViaHTTP(next.url, page + '/') co
}) it('should render styled-jsx styles in streaming', async () => { const html = await renderViaHTTP(next.url, '/') expect(html).toMatch(/color:(?:blue|#00f)/) }) it('should redirect paths without trailing-slash
{ "filepath": "test/e2e/streaming-ssr/index.test.ts", "language": "typescript", "file_size": 5482, "cut_index": 716, "middle_length": 229 }
from 'e2e-utils' import { fetchViaHTTP } from 'next-test-utils' describe('Edge compiler module exports preference', () => { if ((global as any).isNextDeploy) { // this test is skipped when deployed because it manually creates a package in the node_modules directory // which is unsupported it('should skip...
'x-imported': lib } }) } `, 'node_modules/my-lib/package.json': JSON.stringify({ name: 'my-lib', version: '1.0.0', main: 'index.js', browser: 'browser.js', }),
} `, 'middleware.js': ` import { NextResponse } from 'next/server'; import lib from 'my-lib'; export default (req) => { return NextResponse.next({ headers: {
{ "filepath": "test/e2e/edge-compiler-module-exports-preference/index.test.ts", "language": "typescript", "file_size": 1677, "cut_index": 537, "middle_length": 229 }
> { const { next, isTurbopack, isNextDeploy } = nextTestSetup({ files: __dirname, skipStart: true, skipDeployment: true, }) if (isNextDeploy) return ;(isNextStart ? it : it.skip)( 'should throw build error when import statement is used with missing file', async () => { await next.patch...
) { expect(cliOutput).toContain('pages/static-img.js') } else { expect(cliOutput).toContain('./pages/static-img.js') } expect(cliOutput).not.toContain('Import trace for requested module') }
async () => { const { cliOutput } = await next.build() expect(cliOutput).toContain( "Module not found: Can't resolve '../public/foo/test-rect-broken.jpg" ) if (isTurbopack
{ "filepath": "test/e2e/next-image-legacy/default/default-static.test.ts", "language": "typescript", "file_size": 8708, "cut_index": 716, "middle_length": 229 }
turn ( <div> <p>Blurry Placeholder</p> <Image priority id="blurry-placeholder" src="/test.ico" width="400" height="400" placeholder="blur" blurDataURL="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='400' viewBox='0...
PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlT/wAALCAAKAAoBAREA/8QAMwABAQEAAAAAAAAAAAAAAAAAAAcJEAABAwUAAwAAAAAAAAAAAAAFAAYRAQMEEyEVMlH/2gAIAQEAAD8Az1bLPaxhiuk0QdeCOLDtHixN2dmd2bsc5FPX7VTREX//2Q==' x='0' y='0' height='100%25' width='100%25'/%3E%3C/svg%3E" />
uncA type='discrete' tableValues='1 1' /%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter='url(%23blur)' href='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4
{ "filepath": "test/e2e/next-image-legacy/default/pages/blurry-placeholder.js", "language": "javascript", "file_size": 4073, "cut_index": 614, "middle_length": 229 }
port React from 'react' import Image from 'next/legacy/image' const Page = () => { return ( <div> <h1>Warn when "sizes" is not used</h1> <Image layout="fixed" src="/test.png" width={400} height={400} sizes="50vw" /> <Image layout="intrinsic"...
sizes="50vw" /> <div style={{ position: 'relative', width: '200px', height: '200px' }}> <Image src="/test.gif" layout="fill" objectFit="cover" sizes="50vw" /> </div> <footer>footer</footer> </div> ) } export defa
ight={400}
{ "filepath": "test/e2e/next-image-legacy/default/pages/invalid-sizes.js", "language": "javascript", "file_size": 793, "cut_index": 514, "middle_length": 14 }
{ nextTestSetup } from 'e2e-utils' describe('Image Loader Config with Edge Runtime', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should add "src" to img1 based on the loader config', async () => { const browser = await next.browser('/') expect(await browser.elementById('img1')...
er = await next.browser('/') expect(await browser.elementById('img2').getAttribute('src')).toBe( '/logo.png?wid=640&qual=35' ) }) it('should add "srcset" to img2 based on the loader prop', async () => { const browser = await next.bro
expect(await browser.elementById('img1').getAttribute('srcset')).toBe( '/logo.png#w:640,q:50 1x, /logo.png#w:828,q:50 2x' ) }) it('should add "src" to img2 based on the loader prop', async () => { const brows
{ "filepath": "test/e2e/next-image-new/loader-config-edge-runtime/loader-config-edge-runtime.test.ts", "language": "typescript", "file_size": 1169, "cut_index": 518, "middle_length": 229 }
mport React from 'react' import { getImageProps } from 'next/image' import testJpg from '../public/test.jpg' const Page = () => { const { props: img1 } = getImageProps({ id: 'internal-image', src: '/test.png', width: 400, height: 400, }) const { props: img2 } = getImageProps({ id: 'static-ima...
Config</h1> <p>Scroll down...</p> <div style={{ height: '1000vh' }} /> <img {...img1} /> <br /> <img {...img2} /> <br /> <img {...img3} /> <div style={{ height: '1000vh' }} /> <img {...img4} /> </d
width: 400, height: 400, }) const { props: img4 } = getImageProps({ id: 'eager-image', src: '/test.webp', width: 400, height: 400, loading: 'eager', }) return ( <div> <h1>Unoptimized
{ "filepath": "test/e2e/next-image-new/unoptimized/pages/get-img-props.js", "language": "javascript", "file_size": 1029, "cut_index": 513, "middle_length": 229 }
tTestSetup, isNextDev } from 'e2e-utils' describe('Image Component assetPrefix Tests', () => { const { next, isTurbopack } = nextTestSetup({ files: __dirname, }) it('should include assetPrefix when placeholder=blur during dev', async () => { if (!isNextDev) return const browser = await next.browser(...
se64 data url with placeholder=blur during production', async () => { if (isNextDev) return const browser = await next.browser('/') const id = 'test1' const bgImage = await browser.eval( `document.getElementById('${id}').style['backgr
ain('data:image/svg+xml;') } else { expect(bgImage).toMatch( /\/_next\/image\?url=https%3A%2F%2Fexample\.vercel\.sh%2Fpre%2F_next%2Fstatic%2Fmedia%2Ftest(.+).jpg&w=8&q=70/ ) } }) it('should use ba
{ "filepath": "test/e2e/next-image-new/asset-prefix/asset-prefix.test.ts", "language": "typescript", "file_size": 1413, "cut_index": 524, "middle_length": 229 }
v className="flex flex-col items-center justify-center min-h-screen py-2"> <main className="flex flex-col items-center justify-center w-full flex-1 px-20 text-center"> <h1 className="text-blue-600 text-6xl font-bold"> Welcome to{' '} <a className="text-blue-600" href="https://nextjs.or...
g/docs" className="p-6 mt-6 text-left border w-96 rounded-xl hover:text-blue-600 focus:text-blue-600" > <h3 className="text-2xl font-bold">Documentation &rarr;</h3> <p className="mt-4 text-xl"> Fi
lg bg-gray-100 rounded-md"> pages/index.js </code> </p> <div className="flex flex-wrap items-center justify-around max-w-4xl mt-6 sm:w-full"> <a href="https://nextjs.or
{ "filepath": "test/e2e/postcss-config-cjs/app/pages/index.js", "language": "javascript", "file_size": 2481, "cut_index": 563, "middle_length": 229 }
import { useState } from 'react' import { useRouter } from 'next/router' export function getStaticProps({ preview, previewData }) { return { props: { hasProps: true, random: Math.random(), preview: !!preview, previewData: previewData || null, }, } } export default function ({ hasPr...
id="reload-props" onClick={async () => { await router.replace(router.asPath) setReloaded(true) }} > Reload static props </button> <p id="router">{JSON.stringify({ isPreview: router.isPrevi
? JSON.stringify(preview) + ' and ' + JSON.stringify(previewData) : 'Has No Props'} </pre> <pre id="ssg-random">{random}</pre> {reloaded ? <pre id="ssg-reloaded">Reloaded</pre> : null} <button
{ "filepath": "test/e2e/prerender-preview/pages/index.js", "language": "javascript", "file_size": 1022, "cut_index": 512, "middle_length": 229 }
extTestSetup, isNextDev, isNextStart } from 'e2e-utils' ;((isNextDev && process.env.TURBOPACK_BUILD) || (isNextStart && process.env.TURBOPACK_DEV) ? describe.skip : describe)('Relay Compiler Transform - Single Project Config', () => { const { next } = nextTestSetup({ files: __dirname, dependencies: { ...
r install so generated artifacts match the schema before dev/start. installCommand: 'pnpm install && npx relay-compiler', }) it('should resolve index page correctly', async () => { const html = await next.render('/') expect(html).toContain
er // afte
{ "filepath": "test/e2e/relay-graphql-swc-single-project/relay-graphql-swc-single-project.test.ts", "language": "typescript", "file_size": 818, "cut_index": 522, "middle_length": 14 }
import { fetchViaHTTP, renderViaHTTP } from 'next-test-utils' import fs from 'fs-extra' import { join } from 'path' describe('og-api', () => { const { next, skipped } = nextTestSetup({ files: new FileRef(join(__dirname, 'app')), skipDeployment: process.env.TEST_OUTPUT_STANDALONE === 'true', }) if (skipp...
BeGreaterThan(0) }) it('should work in app route', async () => { const res = await fetchViaHTTP(next.url, '/og') expect(res.status).toBe(200) expect(res.headers.get('content-type')).toContain('image/png') const body = await res.blob()
async () => { const res = await fetchViaHTTP(next.url, '/api/og') expect(res.status).toBe(200) expect(res.headers.get('content-type')).toContain('image/png') const body = await res.blob() expect(body.size).to
{ "filepath": "test/e2e/og-api/index.test.ts", "language": "typescript", "file_size": 2802, "cut_index": 563, "middle_length": 229 }
lementById('basic-image').naturalWidth` ) expect(result).toBeGreaterThan(0) }) expect(await getImageUrls(browser)).toContain( `${next.url}/_next/image?url=%2Ftest.jpg&w=828&q=75${dpl}` ) }) it('should preload priority images', async () => { const browser = await next.browser('/pr...
await link.getAttribute('imagesizes') entries.push({ imagesrcset, imagesizes }) } expect(entries).toEqual([ { imagesizes: '', imagesrcset: `/_next/image?url=%2Ftest.jpg&w=640&q=75${dpl} 1x, /_next/image?url=%2Ftest.jpg&
}) const links = await browser.elementsByCss('link[rel=preload][as=image]') const entries = [] for (const link of links) { const imagesrcset = await link.getAttribute('imagesrcset') const imagesizes =
{ "filepath": "test/e2e/next-image-legacy/default/default.test.ts", "language": "typescript", "file_size": 50578, "cut_index": 2151, "middle_length": 229 }
' import { getDeploymentId } from 'next-test-utils' describe('Image Component basePath + trailingSlash Tests', () => { const { next, skipped } = nextTestSetup({ files: __dirname, disableAutoSkewProtection: true, // Image URL assertions construct expected URLs via // `getDeploymentId(next.testDir, ......
string let assetDpl: string beforeAll(() => { dpl = getDeploymentId(next.testDir, isNextDev).getDeploymentIdQuery(true) assetDpl = getDeploymentId(next.testDir, isNextDev).getAssetQuery(true) }) it('should correctly load image src from im
URL omits the `&dpl=...` query that Vercel injects at // runtime. The assertions are about local-build URL shape, not deploy // CDN URLs, so skip in deploy. skipDeployment: true, }) if (skipped) return let dpl:
{ "filepath": "test/e2e/next-image-new/both-basepath-trailingslash/both-basepath-trailingslash.test.ts", "language": "typescript", "file_size": 2160, "cut_index": 563, "middle_length": 229 }
ublic/foo/test-rect.jpg' import Image from 'next/image' import testJPG from '../public/test.jpg' import testPNG from '../public/test.png' import testWEBP from '../public/test.webp' import testAVIF from '../public/test.avif' import testSVG from '../public/test.svg' import testGIF from '../public/test.gif' import testBM...
AgICA8c3RvcCBzdG9wLWNvbG9yPSIjMzMzIiBvZmZzZXQ9IjIwJSIgLz4KICAgICAgPHN0b3Agc3RvcC1jb2xvcj0iIzIyMiIgb2Zmc2V0PSI1MCUiIC8+CiAgICAgIDxzdG9wIHN0b3AtY29sb3I9IiMzMzMiIG9mZnNldD0iNzAlIiAvPgogICAgPC9saW5lYXJHcmFkaWVudD4KICA8L2RlZnM+CiAgPHJlY3Qgd2lkdGg9IjIwMCIgaGVpZ2
xml;base64,Cjxzdmcgd2lkdGg9IjIwMCIgaGVpZ2h0PSIyMDAiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgPGRlZnM+CiAgICA8bGluZWFyR3JhZGllbnQgaWQ9ImciPgogIC
{ "filepath": "test/e2e/next-image-new/base-path/pages/static-img.js", "language": "javascript", "file_size": 2699, "cut_index": 563, "middle_length": 229 }
nvironment, FetchFunction, fetchQuery, Network, RecordSource, Store, } from 'relay-runtime' import { GetServerSideProps } from 'next' import { pagesQuery as pagesQueryType } from '../queries/__generated__/pagesQuery.graphql' import pagesQuery from '../queries/pagesQuery' type Props = { greeting: string } ex...
JSON.stringify({ query: params.text, variables, }), }) return await response.json() } } export const getServerSideProps: GetServerSideProps = async ({ req }) => { const environment = new Environment({ store: new Sto
arams, variables) { const url = host ? `http://${host}/api/query` : `/api/query` const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body:
{ "filepath": "test/e2e/relay-graphql-swc-single-project/pages/index.tsx", "language": "tsx", "file_size": 1403, "cut_index": 524, "middle_length": 229 }
=> 'hi'` describe('Config Experimental Warning', () => { ;(isNextDev ? describe : describe.skip)('development mode', () => { describe('default config from function', () => { const { next } = nextTestSetup({ files: { 'pages/index.js': pageContent, 'next.config.js': ` ...
om function', async () => { const output = stripAnsi(next.cliOutput) expect(output).not.toMatch(experimentalHeader) }) }) describe('config from object', () => { const { next } = nextTestSetup({ files: __dirname,
// We enable this by default in CI strictRouteTypes: false, } } } `, }, }) it('should not show warning with default config fr
{ "filepath": "test/e2e/config-experimental-warning/config-experimental-warning.test.ts", "language": "typescript", "file_size": 8549, "cut_index": 716, "middle_length": 229 }
from 'e2e-utils' describe('Image Loader Config', () => { const { next } = nextTestSetup({ files: __dirname, }) describe('component', () => { it('should work with loaderFile config', async () => { const browser = await next.browser('/') expect(await browser.elementById('img1').getAttribute('s...
expect(await browser.elementById('img2').getAttribute('srcset')).toBe( '/logo.png?wid=256&qual=35 1x, /logo.png?wid=640&qual=35 2x' ) }) }) describe('getImageProps', () => { it('should work with loaderFile config', async ()
) }) it('should work with loader prop', async () => { const browser = await next.browser('/') expect(await browser.elementById('img2').getAttribute('src')).toBe( '/logo.png?wid=640&qual=35' )
{ "filepath": "test/e2e/next-image-new/loader-config/loader-config.test.ts", "language": "typescript", "file_size": 1750, "cut_index": 537, "middle_length": 229 }
{ nextTestSetup } from 'e2e-utils' describe('favicon-short-circuit', () => { const { next, isNextDev } = nextTestSetup({ files: __dirname, }) if (isNextDev) { it('should short circuit the favicon in development', async () => { const res = await next.fetch('/favicon.ico') // Expect we got t...
, async () => { const res = await next.fetch('/favicon.ico') // Expect we got the right status and headers. expect(res.status).toBe(404) expect(res.headers.get('content-type')).toBe('text/html; charset=utf-8') // Expect we g
expect(text).toBeEmpty() // Expect we didn't compile the not found route. expect(next.cliOutput).not.toContain('compiling /not-found') }) } else { it('should not short circuit the favicon in production'
{ "filepath": "test/e2e/favicon-short-circuit/favicon-short-circuit.test.ts", "language": "typescript", "file_size": 1170, "cut_index": 518, "middle_length": 229 }
React from 'react' import Image from 'next/legacy/image' const Page = () => { return ( <div> <h1>Warn for this loader that doesnt use width</h1> <Image id="no-width" src="/test.png" width={100} height={100} loader={({ src }) => `${src}`} /> <Image ...
width={100} height={100} loader={({ src, width }) => `https://example.vercel.sh${src}?width=${width * 2}` } /> <Image id="width-querystring-size" src="/test.tiff" width={100}
-querystring-w" src="/test.webp" width={100} height={100} loader={({ src, width }) => `${src}?w=${width / 2}`} /> <Image id="width-querystring-width" src="/test.gif"
{ "filepath": "test/e2e/next-image-legacy/default/pages/invalid-loader.js", "language": "javascript", "file_size": 1171, "cut_index": 518, "middle_length": 229 }
tTestSetup } from 'e2e-utils' describe('next-phase', () => { const { next, isNextDev, skipped } = nextTestSetup({ // This test is skipped when deployed because it asserts against runtime // logs that cannot be queried in a deployed environment. skipDeployment: true, files: { 'app/layout.js': `e...
} `, }, }) if (skipped) return it('should render page with next phase correctly', async () => { await next.fetch('/') await next.fetch('/foo') const phases = { dev: 'phase-development-server', build: 'phase-pro
'pages/foo.js': `export default function Page() { return <p>{'pages'}</p> }`, 'next.config.js': ` module.exports = (phase, { defaultConfig }) => { console.log(phase) return defaultConfig
{ "filepath": "test/e2e/next-phase/index.test.ts", "language": "typescript", "file_size": 1469, "cut_index": 524, "middle_length": 229 }
estSetup, type Playwright } from 'e2e-utils' import { check, waitFor } from 'next-test-utils' import type { HistoryState } from 'next/dist/shared/lib/router/router' const emitPopsStateEvent = (browser: Playwright, state: HistoryState) => browser.eval( `window.dispatchEvent(new PopStateEvent("popstate", { state:...
/static') const state: HistoryState = { url: '/[dynamic]?', as: '/static', options: {}, __N: true, key: '', } expect(await browser.elementByCss('#page-type').text()).toBe('static') // 1st event is ignored
w FileRef(join(__dirname, 'app/pages')), // Don't use next.config.js to avoid getting i18n }, dependencies: {}, }) test('Ignore event without query param', async () => { const browser = await next.browser('
{ "filepath": "test/e2e/ignore-invalid-popstateevent/without-i18n.test.ts", "language": "typescript", "file_size": 2025, "cut_index": 563, "middle_length": 229 }
eslint-disable jest/no-standalone-expect */ import { join } from 'path' import { fetchViaHTTP } from 'next-test-utils' import { FileRef, nextTestSetup } from 'e2e-utils' const itif = (condition: boolean) => (condition ? it : it.skip) const isModeDeploy = process.env.NEXT_TEST_MODE === 'deploy' describe('Middleware ...
nst res = await fetchViaHTTP(next.url, path) expect(res.status).toBe(200) expect(res.headers.get('x-from-middleware')).toBeDefined() } }) it.each(['/hello', '/invalid/docs/hello'])( 'should not match', async (path) => { c
ware-rewrite-of-nextjs-with-basepath-does-not-work-on-vercel itif(!isModeDeploy)('should match', async () => { for (const path of [ '/docs/hello', `/docs/_next/data/${next.buildId}/hello.json`, ]) { co
{ "filepath": "test/e2e/middleware-custom-matchers-basepath/test/index.test.ts", "language": "typescript", "file_size": 1709, "cut_index": 537, "middle_length": 229 }
rt { FileRef, nextTestSetup } from 'e2e-utils' import cheerio from 'cheerio' import type { Response } from 'node-fetch' describe('Middleware Request Headers Overrides', () => { const { next } = nextTestSetup({ files: { pages: new FileRef(join(__dirname, '../app/pages')), 'next.config.js': new FileRef...
{ title: 'getServerSideProps', path: '/ssr-page', toJson: async (res: Response) => { const $ = cheerio.load(await res.text()) return JSON.parse($('#headers').text()) }, }, ])('$title Backend', ({ path, toJson
', path: '/api/dump-headers-serverless', toJson: (res: Response) => res.json(), }, { title: 'Edge Functions', path: '/api/dump-headers-edge', toJson: (res: Response) => res.json(), },
{ "filepath": "test/e2e/middleware-request-header-overrides/test/index.test.ts", "language": "typescript", "file_size": 3593, "cut_index": 614, "middle_length": 229 }
t' import cheerio from 'cheerio' import { nextTestSetup } from 'e2e-utils' import { retry } from 'next-test-utils' describe('Custom routes i18n support index rewrite', () => { const { next } = nextTestSetup({ files: __dirname, }) const locales = ['nl-NL', 'nl-BE', 'nl', 'fr-BE', 'fr', 'en'] it('should re...
orrectly', async () => { for (const locale of locales) { const browser = await next.browser( `${locale === 'en' ? '' : `/${locale}`}/hello` ) expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({ p
expect(JSON.parse($('#props').text())).toEqual({ params: { slug: ['company', 'about-us'], }, locale, hello: 'world', }) } }) it('should handle index rewrite on client c
{ "filepath": "test/e2e/i18n-support-index-rewrite/i18n-support-index-rewrite.test.ts", "language": "typescript", "file_size": 1668, "cut_index": 537, "middle_length": 229 }
tTestSetup } from 'e2e-utils' import cheerio from 'cheerio' const config = require('./next.config') async function verify(res, locale) { expect(res.status).toBe(200) // Verify that we loaded the right page and the locale is correct. const html = await res.text() const $ = cheerio.load(html) expect($('#page...
redirect: 'manual' }) await verify(res, config.i18n.defaultLocale) }) it.each(config.i18n.locales)('/%s should 200', async (locale) => { const res = await next.fetch(`/${locale}`, { redirect: 'manual' }) await verify(res, locale) })
irname, // TODO: re-enable after this behavior is corrected skipDeployment: true, }) if (skipped) { return } it('should verify the default locale works', async () => { const res = await next.fetch('/', {
{ "filepath": "test/e2e/i18n-disallow-multiple-locales/i18n-disallow-multiple-locales.test.ts", "language": "typescript", "file_size": 1487, "cut_index": 524, "middle_length": 229 }
h' import { nextTestSetup } from 'e2e-utils' import { findPort, initNextServerScript, killApp } from 'next-test-utils' describe('Trailing Slash Rewrite Proxying', () => { const { next, isNextDev, skipped } = nextTestSetup({ files: __dirname, skipStart: true, // Spawns a custom proxy server in front of `n...
NextDev) { await next.build() } await next.start() }) afterAll(async () => { await killApp(proxyServer) }) it('should resolve index page correctly', async () => { const html = await next.render('/') expect(html).toContai
findPort() proxyServer = await initNextServerScript( join(__dirname, 'server.js'), /ready on/i, { ...process.env, PORT: String(proxyPort) } ) next.env.EXTERNAL_PORT = String(proxyPort) if (!is
{ "filepath": "test/e2e/trailing-slashes-rewrite/trailing-slashes-rewrite.test.ts", "language": "typescript", "file_size": 1692, "cut_index": 537, "middle_length": 229 }
throw new Error( `did not find window.errorLoad, current url: ${await browser.url()}` ) } if (isDev) break } } // Always resolve to a numeric port. We cannot use `next.fetch(...)` for // URLs that start with `//` or contain `\\` because `next.fetch` internally // runs them t...
solvePort()) => next.browser(url, { baseUrl }) if (!isExport) { it('should normalize repeated slashes in redirects correctly', async () => { const res = await fetchViaHTTP( resolvePort(), '/redirect-forward-slashes',
he path onto the origin // verbatim, preserving the repeated-slash/backslash behavior under test. const resolvePort = () => (getPort ? getPort() : Number(next.appPort)) const openBrowser = (url: string, baseUrl: number = re
{ "filepath": "test/e2e/repeated-slashes/repeated-slashes.test.ts", "language": "typescript", "file_size": 17434, "cut_index": 1331, "middle_length": 229 }
from 'next/link' if (typeof window !== 'undefined') { window.caughtErrors = [] const origError = window.console.error window.console.error = function (...args) { window.caughtErrors.push(args.join(' ')) return origError(...args) } } export default function Invalid() { return ( <> <p id="i...
oogle.com#hello" id="href-with-slashes-hash"> to //google.com#hello </Link> <br /> <Link href="/another" as="\/\/google.com" id="page-with-as-backslashes"> to /another as \\/\\/google.com </Link> <br />
" id="href-with-slashes"> to //google.com </Link> <br /> <Link href="//google.com?hello=1" id="href-with-slashes-query"> to //google.com?hello=1 </Link> <br /> <Link href="//g
{ "filepath": "test/e2e/repeated-slashes/app/pages/invalid.js", "language": "javascript", "file_size": 1410, "cut_index": 524, "middle_length": 229 }
ort { nextTestSetup } from 'e2e-utils' import { retry } from 'next-test-utils' const EXPECTED_WARNING = 'The Edge Runtime is deprecated. You can use the "nodejs" runtime instead.' describe('edge-runtime-deprecated', () => { const { next, isNextDev } = nextTestSetup({ files: __dirname, }) it('should warn ...
piled, but // another request ensures no duplicate warnings). await next.fetch('/edge-route') } await retry(async () => { expect(next.cliOutput).toContain(EXPECTED_WARNING) }) const occurrences = next.cliOutput.split(EXP
await retry(async () => { expect(next.cliOutput).toContain(EXPECTED_WARNING) }) }) it('should only warn once', async () => { if (isNextDev) { // Trigger compilation of the edge route again (already com
{ "filepath": "test/e2e/edge-runtime-deprecated/edge-runtime-deprecated.test.ts", "language": "typescript", "file_size": 1066, "cut_index": 515, "middle_length": 229 }
from 'e2e-utils' import { fetchViaHTTP } from 'next-test-utils' describe('i18n API support', () => { const { next } = nextTestSetup({ files: { 'pages/api/hello.js': ` export default function handler(req, res) { res.end('hello world') } `, 'pages/api/blog/[slug].js': ...
mple.vercel.sh/', }, ], } }, }, dependencies: {}, }) it('should respond to normal API request', async () => { const res = await fetchViaHTTP(next.url, '/api/hello') expect(res.status).toBe(200) e
ocale: 'en', }, async rewrites() { return { beforeFiles: [], afterFiles: [], fallback: [ { source: '/api/:path*', destination: 'https://exa
{ "filepath": "test/e2e/i18n-api-support/index.test.ts", "language": "typescript", "file_size": 1819, "cut_index": 537, "middle_length": 229 }
t', (request) => { const url = new URL(request.url()) requests.push(url.pathname) }) }, }) if (!(global as any).isNextDev) { browser.elementByCss('#to-article-rewrite').moveTo() await retry(async () => { expect(requests.some((item) => ite...
await next.fetch('/external-rewrite-body', { redirect: 'manual', method: 'POST', body, }) expect(res.status).toBe(200) expect(await res.text()).toEqual(body) }) it('should handle middleware rewrite with bo
()) expect(preQuery).toEqual({ slug: ['foo', 'bar', '123'] }) }) it('should handle next.config.js rewrite with body correctly', async () => { const body = JSON.stringify({ hello: 'world' }) const res =
{ "filepath": "test/e2e/middleware-rewrites/test/index.test.ts", "language": "typescript", "file_size": 31495, "cut_index": 1331, "middle_length": 229 }
extUrl if (url.pathname.includes('article')) { return NextResponse.next() } // this is needed for tests to get the BUILD_ID if (url.pathname.startsWith('/_next/static/__BUILD_ID')) { return NextResponse.next() } if (url.pathname.includes('/to/some/404/path')) { return NextResponse.next({ ...
}, } ) } if ( url.pathname.includes( '/middleware-external-rewrite-body-headers-return-headers' ) ) { const tmpHeaders = new Headers(request.headers) tmpHeaders.set('x-hello-from-middleware1', 'hello') return N
eaders) tmpHeaders.set('x-hello-from-middleware1', 'hello') return NextResponse.rewrite( 'https://next-data-api-endpoint.vercel.app/api/echo-body', { request: { headers: tmpHeaders,
{ "filepath": "test/e2e/middleware-rewrites/app/middleware.js", "language": "javascript", "file_size": 5285, "cut_index": 716, "middle_length": 229 }
cales: ['ja', 'en', 'fr', 'es'], defaultLocale: 'en', }, rewrites() { return { beforeFiles: [ { source: '/beforefiles-rewrite', destination: '/ab-test/a', }, ], afterFiles: [ { source: '/article/:slug*', destination: '/detail/...
{ source: '/config-rewrite-to-dynamic-static/:rewriteSlug', destination: '/ssg', }, { source: '/external-rewrite-body', destination: 'https://next-data-api-endpoint.vercel.app/api/echo-bo
ion: '/fallback-true-blog/first', },
{ "filepath": "test/e2e/middleware-rewrites/app/next.config.js", "language": "javascript", "file_size": 913, "cut_index": 547, "middle_length": 52 }
t default function Home({ locale }) { return ( <div> <div className={locale}>{locale}</div> <ul> <li> <Link href="/i18n" locale="en" id="link-en"> Go to en </Link> </li> <li> <Link href="/en/i18n" locale={false} id="link-en2"> ...
Go to ja2 </Link> </li> <li> <Link href="/i18n" locale="fr" id="link-fr"> Go to fr </Link> </li> </ul> </div> ) } export const getServerSideProps = ({ query }) => ({
nk href="/ja/i18n" locale={false} id="link-ja2">
{ "filepath": "test/e2e/middleware-rewrites/app/pages/i18n.js", "language": "javascript", "file_size": 891, "cut_index": 547, "middle_length": 52 }
rom 'next/router' export default function Home() { const router = useRouter() return ( <div> <p className="title">Home Page</p> <div /> <Link href="/article/foo/bar/123" id="to-article-rewrite"> to /article/foo/bar/123 </Link> <div /> <Link href="/rewrite-to-ab-test"...
-afterfiles-rewrite" id="rewrite-to-afterfiles-rewrite" > Rewrite me to afterFiles Rewrite </Link> <div /> <Link href="/rewrite-me-to-vercel">Rewrite me to Vercel</Link> <div /> <Link href="/rewrite-me-ex
<div /> <Link href="/rewrite-to-beforefiles-rewrite" id="rewrite-to-beforefiles-rewrite" > Rewrite me to beforeFiles Rewrite </Link> <div /> <Link href="/rewrite-to
{ "filepath": "test/e2e/middleware-rewrites/app/pages/index.js", "language": "javascript", "file_size": 2503, "cut_index": 563, "middle_length": 229 }
{ nextTestSetup } from 'e2e-utils' import { retry } from 'next-test-utils' describe('AppTree', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should provide router context in AppTree on SSR', async () => { let html = await next.render('/') expect(html).toMatch(/page:.*?\//) ...
r.eval(`document.documentElement.innerHTML`) expect(html).toMatch(/page:.*?\//) }) await browser.elementByCss('#home').click() await retry(async () => { html = await browser.eval(`document.documentElement.innerHTML`) expect(h
owser('/') let html = await browser.eval(`document.documentElement.innerHTML`) expect(html).toMatch(/page:.*?\//) await browser.elementByCss('#another').click() await retry(async () => { html = await browse
{ "filepath": "test/e2e/app-tree/app-tree.test.ts", "language": "typescript", "file_size": 1213, "cut_index": 518, "middle_length": 229 }
import Link from 'next/link' import { useRouter } from 'next/router' export default function Page(props) { if (useRouter().isFallback) { return <p>Loading...</p> } return ( <> <p id="props">{JSON.stringify(props)}</p> <Link href="/fallback-true-blog/first?hello=world" shallow...
llback-true-blog/build-time-2', '/fallback-true-blog/build-time-3', '/fallback-true-blog/build-time-4', ], fallback: true, } } export function getStaticProps({ params }) { return { props: { params, time: Date.now(),
"> to /fallback-true-blog/second </Link> <br /> </> ) } export function getStaticPaths() { return { paths: [ '/fallback-true-blog/first', '/fallback-true-blog/build-time-1', '/fa
{ "filepath": "test/e2e/middleware-rewrites/app/pages/fallback-true-blog/[slug].js", "language": "javascript", "file_size": 1011, "cut_index": 512, "middle_length": 229 }
t origConfigContent: string beforeAll(async () => { externalPort = await findPort() externalServer = http.createServer((req, res) => { res.statusCode = 200 res.end(JSON.stringify({ url: req.url, external: true })) }) await new Promise<void>((resolve, reject) => { externalServer.list...
.port if (!isNextDev) { ctx.buildId = (await next.readFile('.next/BUILD_ID')).trim() ctx.buildPagesDir = join(next.testDir, '.next/server/pages') } else { ctx.buildId = 'development' } }) afterAll(() => { externalServ
ng(externalPort)) ) origConfigContent = await next.readFile('next.config.js') if (!isNextDev) { await next.build() } await next.start() ctx.appDir = next.testDir ctx.appPort = new URL(next.url)
{ "filepath": "test/e2e/i18n-support/i18n-support.test.ts", "language": "typescript", "file_size": 18687, "cut_index": 1331, "middle_length": 229 }
ilingSlash: true, i18n: { // localeDetection: false, locales: [ 'nl-NL', 'nl-BE', 'nl', 'fr-BE', 'fr', 'en-US', 'en', 'go', 'go-BE', 'do', 'do-BE', ], defaultLocale: 'en-US', domains: [ { http: true, domain: 'e...
destination: '/somewhere-else', permanent: false, locale: false, }, { source: '/redirect-3', destination: '/somewhere-else', permanent: false, }, { source: '/redirect-4', des
}, async redirects() { return [ { source: '/en-US/redirect-1', destination: '/somewhere-else', permanent: false, locale: false, }, { source: '/nl/redirect-2',
{ "filepath": "test/e2e/i18n-support/next.config.js", "language": "javascript", "file_size": 2458, "cut_index": 563, "middle_length": 229 }
rt, `${ctx.basePath || ''}/${locale}/files/texts/file.txt`, undefined, { redirect: 'manual' } ) if (!defaultLocales.includes(locale)) { expect(res.status).toBe(404) expect(await res.text()).toContain('could not be found') } else { // We only 404 for non...
ders.get('location')).toBe('https://jobs.example.com/') const res2 = await fetchViaHTTP( ctx.appPort, `${ctx.basePath || ''}/redirect-5`, undefined, { redirect: 'manual', } ) expect(res2.status).toBe(307)
`${ctx.basePath || ''}/do/redirect-5`, undefined, { headers: { 'accept-language': 'do', }, redirect: 'manual', } ) expect(res.status).toBe(307) expect(res.hea
{ "filepath": "test/e2e/i18n-support/shared.ts", "language": "typescript", "file_size": 125250, "cut_index": 3790, "middle_length": 229 }
ink from 'next/link' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() return ( <> <p id="another">another page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-default-locale">{...
sPath}</p> <Link href="/" id="to-index"> to / </Link> <br /> </> ) } export const getServerSideProps = ({ locale, locales, defaultLocale }) => { return { props: { locale, locales, defaultLocale,
pathname}</p> <p id="router-as-path">{router.a
{ "filepath": "test/e2e/i18n-support/pages/another.js", "language": "javascript", "file_size": 837, "cut_index": 520, "middle_length": 52 }
from 'next/link' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() return ( <> <p id="frank">frank page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-default-locale">{router.d...
<Link href="/gsp/fallback/first" id="to-fallback-first"> to /gsp/fallback/first </Link> <br /> <Link href="/gsp/fallback/hello" id="to-fallback-hello"> to /gsp/fallback/hello </Link> <br /> <Link href
}</p> <p id="router-as-path">{router.asPath}</p> <Link href="/another" id="to-another"> to /another </Link> <br /> <Link href="/gsp" id="to-gsp"> to /gsp </Link> <br />
{ "filepath": "test/e2e/i18n-support/pages/frank.js", "language": "javascript", "file_size": 1480, "cut_index": 524, "middle_length": 229 }
rom 'next/router' import { useEffect } from 'react' import { useState } from 'react' export default function Page(props) { const router = useRouter() const parsedAs = new URL(router.asPath, 'http://n') const [asPath, setAsPath] = useState(parsedAs.pathname) useEffect(() => { if (router.isReady && router.a...
main-locales">{JSON.stringify(router.domainLocales)}</p> <p id="router-query">{JSON.stringify(router.query)}</p> <p id="router-pathname">{router.pathname}</p> <p id="router-as-path">{asPath}</p> <Link href="/another" id="to-another"
">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-default-locale">{router.defaultLocale}</p> <p id="router-locales">{JSON.stringify(router.locales)}</p> <p id="router-do
{ "filepath": "test/e2e/i18n-support/pages/index.js", "language": "javascript", "file_size": 2219, "cut_index": 563, "middle_length": 229 }
nk' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() const { nextLocale } = router.query return ( <> <p id="links">links page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-...
ocale} id="to-gsp"> to /gsp </Link> <br /> <Link href="/gsp/fallback/first" locale={nextLocale} id="to-fallback-first" > to /gsp/fallback/first </Link> <br /> <Link h
athname">{router.pathname}</p> <p id="router-as-path">{router.asPath}</p> <Link href="/another" locale={nextLocale} id="to-another"> to /another </Link> <br /> <Link href="/gsp" locale={nextL
{ "filepath": "test/e2e/i18n-support/pages/links.js", "language": "javascript", "file_size": 1719, "cut_index": 537, "middle_length": 229 }
nk' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() const { nextLocale } = router.query return ( <> <p id="links">links page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-...
</Link> <br /> <Link href={`/${nextLocale}/gsp/fallback/first`} locale={false} id="to-fallback-first" > to /gsp/fallback/first </Link> <br /> <Link href={`/${nextLocale}/gsp/fallb
uter.asPath}</p> <Link href={`/${nextLocale}/another`} locale={false} id="to-another"> to /another </Link> <br /> <Link href={`/${nextLocale}/gsp`} locale={false} id="to-gsp"> to /gsp
{ "filepath": "test/e2e/i18n-support/pages/locale-false.js", "language": "javascript", "file_size": 1997, "cut_index": 537, "middle_length": 229 }
export default function Page(props) { const router = useRouter() return ( <> <p id="links">links page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-default-locale">{router.defaultLocale}</p> <p id="router-locales">{JSON.strin...
s"> to /gsp </Link> <br /> <Link href="/gsp" locale="nl-NL" id="to-gsp-nl-nl"> to /gsp </Link> <br /> <Link href="/gsp" locale="fr" id="to-gsp-fr"> to /gsp </Link> <br /> <Lin
<Link href="/gsp" locale="en-US" id="to-gsp-en-u
{ "filepath": "test/e2e/i18n-support/pages/mixed.js", "language": "javascript", "file_size": 972, "cut_index": 582, "middle_length": 52 }
://localhost:__EXTERNAL_PORT__' module.exports = { i18n: { // localeDetection: false, locales: ['nl-NL', 'nl-BE', 'nl', 'fr-BE', 'fr', 'en'], defaultLocale: 'en', }, async rewrites() { return [ { source: '/:path*', destination: '/:path*', }, { source: '/...
t', destination: `${destination}/about`, locale: false, }, { source: '/fr/about', destination: `${destination}/fr/about`, locale: false, }, { source: '/en/catch-all/:path*', d
urce: '/fr', destination: `/fr/links`, locale: false, }, { source: '/en/about', destination: `${destination}/about`, locale: false, }, { source: '/nl-NL/abou
{ "filepath": "test/e2e/custom-routes-i18n/next.config.js", "language": "javascript", "file_size": 1770, "cut_index": 537, "middle_length": 229 }
{ next, isNextDeploy, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, }) if (skipped) return if (isNextDeploy) return it('should alias components', async () => { const $ = await next.render$('/basic-alias') expect($('body').text()).toMatch(/World/) }) it('should resolve...
ait next.render$('/single-alias') expect($('body').text()).toMatch(/Hello/) }) if (isNextDev) { it('should have correct module not found error', async () => { const originalContent = await next.readFile('pages/basic-alias.js') try
item as fallback', async () => { const $ = await next.render$('/resolve-fallback') expect($('body').text()).toMatch(/Hello from only b/) }) it('should resolve a single matching alias', async () => { const $ = aw
{ "filepath": "test/e2e/jsconfig-paths/jsconfig-paths.test.ts", "language": "typescript", "file_size": 6525, "cut_index": 716, "middle_length": 229 }
import { nextTestSetup } from 'e2e-utils' describe('next-image-src-with-query-without-local-patterns', () => { const { next, isNextDev, skipped } = nextTestSetup({ files: __dirname, skipStart: true, skipDeployment: true, }) if (skipped) { return } it('should throw error for relative image w...
build() expect(cliOutput).toContain( 'Image with src "/test.png?v=1" is using a query string which is not configured in images.localPatterns.\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns' ) }
st.png?v=1" is using a query string which is not configured in images.localPatterns.\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns' ) } else { const { cliOutput } = await next.
{ "filepath": "test/e2e/next-image-src-with-query-without-local-patterns/next-image-src-with-query-without-local-patterns.test.ts", "language": "typescript", "file_size": 1003, "cut_index": 512, "middle_length": 229 }
ip-trailing-slash-redirect', () => { const { next } = nextTestSetup({ files: new FileRef(join(__dirname, 'app')), dependencies: {}, }) // the tests below are run in both pages and app dir to ensure the behavior is the same // the other cases aren't added to this block since they are either testing page...
it res.text()).toContain('another page') }) it('should not apply trailing slash redirect (without slash)', async () => { const res = await fetchViaHTTP( next.url, `${basePath}another`, undefined, { r
async () => { const res = await fetchViaHTTP( next.url, `${basePath}another/`, undefined, { redirect: 'manual', } ) expect(res.status).toBe(200) expect(awa
{ "filepath": "test/e2e/skip-trailing-slash-redirect/index.test.ts", "language": "typescript", "file_size": 12379, "cut_index": 921, "middle_length": 229 }
cHeader = 'X-From-Src-Middleware' const rootHeader = 'X-From-Root-Middleware' describe('middleware-src-node', () => { const { next, isTurbopack, skipped } = nextTestSetup({ files: __dirname, skipStart: true, skipDeployment: true, }) if (skipped) return if (isNextDev) { beforeAll(async () => { ...
export', async () => { await next.patchFile( 'next.config.js', "module.exports = { output: 'export' }" ) await next.build() expect(next.cliOutput).toContain( 'Statically exporting a Next.js app
next.fetch('/post-1') expect(response.headers.has(srcHeader)).toBe(false) expect(response.headers.has(`${srcHeader}-TS`)).toBe(true) }) } if (!isNextDev) { it('should warn about middleware on
{ "filepath": "test/e2e/middleware-src-node/middleware-src-node.test.ts", "language": "typescript", "file_size": 3549, "cut_index": 614, "middle_length": 229 }
mport { nextTestSetup } from 'e2e-utils' import { retry } from 'next-test-utils' const expectedErr = /Webpack config is undefined. You may have forgot to return properly from within the "webpack" method of your next.config.js/ // Webpack-specific test, not needed for Turbopack ;(process.env.IS_TURBOPACK_TEST ? desc...
build() expect(cliOutput).toMatch(expectedErr) }) }) ;(isNextDev ? it : it.skip)( 'should show error in development mode', async () => { await next.start() await retry(async () => { expect(next.cl
skipDeployment: true, }) if (skipped) return ;(isNextStart ? describe : describe.skip)('production mode', () => { it.skip('should show in production mode', async () => { const { cliOutput } = await next.
{ "filepath": "test/e2e/undefined-webpack-config/undefined-webpack-config.test.ts", "language": "typescript", "file_size": 1059, "cut_index": 513, "middle_length": 229 }
G_MESSAGE = `ERROR: This build is using Turbopack, with a \`webpack\` config and no \`turbopack\` config.` const itif = (condition: boolean) => (condition ? it : it.skip) const page = { 'app/page.js': ` export default function Page() { return <p>hello world</p> } `, } ;(process.env.IS_TURBOPACK_TEST ? describe :...
...page, 'next.config.js': ` module.exports = { webpack: (config) => { return config }, } `, }, }) itif(isNextDev)('warns', async () => {
{ next, isNextDev, isNextStart } = nextTestSetup({ skipStart: Boolean(process.env.NEXT_TEST_MODE === 'start'), turbo: false, env: { TURBOPACK: 'auto', }, files: {
{ "filepath": "test/e2e/config-turbopack/index.test.ts", "language": "typescript", "file_size": 3826, "cut_index": 614, "middle_length": 229 }
eact' import Router, { withRouter } from 'next/router' import Link from 'next/link' const pages = { '/a': 'Foo', '/b': 'Bar', } class HeaderNav extends React.Component { constructor({ router }) { super() this.state = { activeURL: router.asPath, activeURLTopLevelRouterDeprecatedBehavior: rou...
ngeComplete = null Router.events.off( 'routeChangeComplete', this.handleRouteChangeTopLevelRouter ) this.props.router.events.off('routeChangeComplete', this.handleRouteChange) } handleRouteChange = (url) => { this.setState(
Router.events.on( 'routeChangeComplete', this.handleRouteChangeTopLevelRouter ) this.props.router.events.on('routeChangeComplete', this.handleRouteChange) } componentWillUnmount() { Router.onRouteCha
{ "filepath": "test/e2e/with-router/components/header-nav.js", "language": "javascript", "file_size": 2007, "cut_index": 537, "middle_length": 229 }
ForNoRedbox, } from 'next-test-utils' describe('module layer', () => { const { next, isNextStart, isNextDev, isNextDeploy } = nextTestSetup({ files: __dirname, }) function runTests() { const routes = [ // app client components pages '/app/client', '/app/client-edge', // app sever...
const { status } = await next.fetch(route) expect([route, status]).toEqual([route, 200]) }) } it('should render installed react-server condition for middleware', async () => { const json = await next.fetch('/middleware').th
dge', '/api/server-only', '/api/server-only-edge', '/api/mixed', ] for (const route of routes) { it(`should render routes marked with restriction marks without errors ${route}`, async () => {
{ "filepath": "test/e2e/module-layer/module-layer.test.ts", "language": "typescript", "file_size": 4940, "cut_index": 614, "middle_length": 229 }
tion Home() { return ( <div className="flex min-h-screen items-center justify-center bg-zinc-50 font-sans dark:bg-black font-[family-name:var(--font-geist-sans)]"> <main className="flex min-h-screen w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start"> ...
the page.tsx file. </h1> <p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400"> Looking for a starting point or more instructions? Head over to{' '} <a href="https://vercel.com
ssName="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left"> <h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50"> To get started, edit
{ "filepath": "test/e2e/middleware-static-files/app/app/page.tsx", "language": "tsx", "file_size": 2925, "cut_index": 563, "middle_length": 229 }
import Link from 'next/link' import { createContext } from 'react' import { flushSync } from 'react-dom' import { createRoot } from 'react-dom/client' import App, { AppContext } from 'next/app' import { renderToString } from 'react-dom/server' export const DummyContext = createContext(null) as React.Context<string | ...
.createElement('div') document.querySelector('body')?.appendChild(el) flushSync(() => { createRoot(el).render(toRender) }) html = el.innerHTML el.remove() } else { html = renderToString(toRender) } r
Props) { pageProps = await Component.getInitialProps(ctx) } let html: string const toRender = <AppTree pageProps={pageProps} another="prop" /> if (typeof window !== 'undefined') { const el = document
{ "filepath": "test/e2e/app-tree/pages/_app.tsx", "language": "tsx", "file_size": 1606, "cut_index": 537, "middle_length": 229 }
eact from 'react' import { flushSync } from 'react-dom' import { createRoot } from 'react-dom/client' import { renderToString } from 'react-dom/server' import { NextPage } from 'next' const Page: NextPage<{ html: string }> = ({ html }) => html ? ( <> <p>saved:</p> <div dangerouslySetInnerHTML={{ __ht...
lement('div') document.querySelector('body')?.appendChild(el) flushSync(() => { createRoot(el).render(toRender) }) html = el.innerHTML el.remove() } else { html = renderToString(toRender) } return { html } } export def
w !== 'undefined') { const el = document.createE
{ "filepath": "test/e2e/app-tree/pages/hello.tsx", "language": "tsx", "file_size": 838, "cut_index": 520, "middle_length": 52 }
ort { join } from 'path' import cheerio from 'cheerio' import { fetchViaHTTP } from 'next-test-utils' import { FileRef, nextTestSetup } from 'e2e-utils' describe('Middleware base tests', () => { const { next } = nextTestSetup({ files: { pages: new FileRef(join(__dirname, '../app/pages')), 'middleware...
await browser.close() } const res = await fetchViaHTTP(next.url, '/root/redirect-with-basepath') const html = await res.text() const $ = cheerio.load(html) expect($('.title').text()).toBe('About Page') }) it('router.query must exi
', async () => { const browser = await next.browser('/redirect-with-basepath') try { expect(await browser.eval(`window.location.pathname`)).toBe( '/root/redirect-with-basepath' ) } finally {
{ "filepath": "test/e2e/middleware-base-path/test/index.test.ts", "language": "typescript", "file_size": 1732, "cut_index": 537, "middle_length": 229 }
module.exports = { webpack: (config, { isServer }) => { if (!isServer) { const optimization = config.optimization || {} const splitChunks = optimization.splitChunks || {} const cacheGroups = splitChunks.cacheGroups || {} config.optimization = { ...optimization, splitChunks...
/, name: 'requiredByPage', enforce: true, priority: 10, chunks: 'all', filename: 'static/chunks/[name].[chunkhash].js', }, }, }, } } return c
enforce: true, priority: 10, chunks: 'all', filename: 'static/chunks/[name].[chunkhash].js', }, requiredByPage: { test: /requiredByPage.js
{ "filepath": "test/e2e/app-document-import-order/next.config.js", "language": "javascript", "file_size": 1010, "cut_index": 512, "middle_length": 229 }
('next-link', () => { const { skipped, next, isNextDev } = nextTestSetup({ files: __dirname, skipDeployment: true, }) if (skipped) return it('errors on invalid href', async () => { const browser = await next.browser('/invalid-href') if (isNextDev) { await expect(browser).toDisplayRedbox...
</Link> | ^", "stack": [ "Hello app/invalid-href/page.js (6:10)", ], } `) } // Client errors show "This page couldn\u2019t load" expect(await browser.elementByCss('body').text()).toC
our browser's console to view the Component stack trace.", "environmentLabel": null, "label": "Runtime Error", "source": "app/invalid-href/page.js (6:10) @ Hello > 6 | return <Link>Hello, Dave!
{ "filepath": "test/e2e/next-link-errors/next-link-errors.test.ts", "language": "typescript", "file_size": 2229, "cut_index": 563, "middle_length": 229 }
' import { nextTestSetup, isNextDev } from 'e2e-utils' describe('Custom routes i18n', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipStart: true, skipDeployment: true, }) if (skipped) return let server: http.Server let externalPort: number beforeAll(async () => { ...
ace(/__EXTERNAL_PORT__/g, String(externalPort)) ) if (!isNextDev) { await next.build() } await next.start() }) afterAll(() => { server.close() }) it('should respond to default locale redirects correctly', async () => {
})}</p>` ) }) await new Promise<void>((res, rej) => { server.listen(externalPort, (err?: Error) => (err ? rej(err) : res())) }) await next.patchFile('next.config.js', (content) => content.repl
{ "filepath": "test/e2e/custom-routes-i18n/custom-routes-i18n.test.ts", "language": "typescript", "file_size": 4530, "cut_index": 614, "middle_length": 229 }
th' const describeCase = ( caseName: string, callback: (context: ReturnType<typeof nextTestSetup>) => void ) => { describe(caseName, () => { const context = nextTestSetup({ files: path.join(__dirname, caseName), skipDeployment: true, }) if (context.skipped) return callback(context) ...
entation hook', async () => { await next.render('/') await check(() => next.cliOutput, /instrumentation hook on the edge/) }) }) describeCase('with-edge-api', ({ next }) => { it('with-edge-api should run the instrumentation hook',
nder('/') await check( () => next.cliOutput, /register in instrumentation\.js is running/ ) }) }) describeCase('with-middleware', ({ next }) => { it('with-middleware should run the instrum
{ "filepath": "test/e2e/instrumentation-hook/instrumentation-hook.test.ts", "language": "typescript", "file_size": 3648, "cut_index": 614, "middle_length": 229 }
rl = new URL(req.url) const origPathname = parsedOrigUrl.pathname const lowerPathname = origPathname.toLowerCase() // ensure locale casing can be redirected if ( (lowerPathname.startsWith('/en') || lowerPathname.startsWith('/ja-jp')) && origPathname !== lowerPathname && !lowerPathname.includes('_ne...
ned-rewrite')) { if (pathname.startsWith('/en')) { pathname = pathname.replace(/^\/en/, '') || '/' } if (pathname === '/docs') { pathname = '/' } console.log( `rewriting to https://middleware-external-rewrite-target.
h('/_next/data') && pathname.includes('locale-test')) { return NextResponse.json({ locale: req.nextUrl.locale, pathname: req.nextUrl.pathname, }) } if (pathname.includes('docs') || pathname.includes('chai
{ "filepath": "test/e2e/skip-trailing-slash-redirect/app/middleware.js", "language": "javascript", "file_size": 3166, "cut_index": 614, "middle_length": 229 }
waitForNoRedbox, renderViaHTTP } from 'next-test-utils' import cheerio from 'cheerio' describe('Type module interop', () => { const { next } = nextTestSetup({ files: { 'pages/index.js': ` import Link from 'next/link' import Head from 'next/head' import Script from 'next/script' ...
<Script strategy="afterInteractive" dangerouslySetInnerHTML={{ __html: 'console.log("hello world")', }} /> <p>hello world</p> <Dynamic />
<Head> <title>This page has a title 🤔</title> <meta charSet="utf-8" /> <meta name="viewport" content="initial-scale=1.0, width=device-width" /> </Head>
{ "filepath": "test/e2e/type-module-interop/index.test.ts", "language": "typescript", "file_size": 3027, "cut_index": 563, "middle_length": 229 }
import { FileRef, isNextStart, nextTestSetup } from 'e2e-utils' import { listClientChunks } from 'next-test-utils' describe('Middleware Runtime', () => { const { next } = nextTestSetup({ files: new FileRef(join(__dirname, 'app')), }) let testPaths: Array<{ testPath: string }> = [ { testPath: '/file.svg' ...
{ testPath: '/glob/hello' }, { testPath: '/pages-another/hello' }, { testPath: '/pages-another%2fhello' }, { testPath: '/pages-dynamic%2f/first' }, { testPath: '/pages-dynamic/first' }, { testPath: '/pages-glob%2fhello' }, { testP
' }, { testPath: '/another%2fhello' }, { testPath: '/glob%2ffile.svg' }, { testPath: '/glob/file.svg' }, { testPath: '/dynamic%2f/first' }, { testPath: '/dynamic/first' }, { testPath: '/glob%2fhello' },
{ "filepath": "test/e2e/middleware-static-files/index.test.ts", "language": "typescript", "file_size": 2243, "cut_index": 563, "middle_length": 229 }
om 'next/link' import type { GetStaticProps } from 'next' type Props = { random: number draftMode: string } export const getStaticProps: GetStaticProps<Props> = ({ draftMode }) => { return { props: { random: Math.random(), draftMode: Boolean(draftMode).toString(), }, revalidate: 100000, ...
=> setCount(count + 1)}> Increment </button> <p> Count: <span id="count">{count}</span> </p> <p> Random: <em id="rand">{props.random}</em> </p> <Link href="/another">Visit another page</Link>
</em> </p> <button id="inc" onClick={()
{ "filepath": "test/e2e/draft-mode/pages/index.tsx", "language": "tsx", "file_size": 877, "cut_index": 559, "middle_length": 52 }
tTestSetup, isNextDev } from 'e2e-utils' ;(isNextDev ? describe.skip : describe)('i18n-beforefiles-rewrite', () => { const { next } = nextTestSetup({ files: __dirname, }) const locales = ['en', 'fr'] const autoStaticRoutes = [ { pathname: '', content: 'index' }, { pathname: '/home/a', content: 'Ho...
const url = `/${locale}${pathname}` const res = await next.fetch(url) const html = await res.text() expect({ url, status: res.status }).toEqual({ url, status: 200 }) expect(html).toContain(content) } } }) it
ame: '/team/slug', content: '/[teamId]/[slug]' }, ] it('should serve locale-prefixed auto-static pages', async () => { for (const { pathname, content } of autoStaticRoutes) { for (const locale of locales) {
{ "filepath": "test/e2e/i18n-beforefiles-rewrite/i18n-beforefiles-rewrite.test.ts", "language": "typescript", "file_size": 1444, "cut_index": 524, "middle_length": 229 }
from 'e2e-utils' import { check } from 'next-test-utils' describe('instrumentation-hook-rsc', () => { describe('instrumentation', () => { const { next, isNextDev, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, }) if (skipped) { return } it('should run the i...
ext.render('/edge') await check(() => next.cliOutput, /instrumentation hook on the edge/) }) if (isNextDev) { // TODO: Implement handling for changing the instrument file. it.skip('should reload the server when the instrumentation
async () => { const page = await next.render('/instrumentation') expect(page).toContain('Hello') }) it('should run the edge instrumentation compiled version with the edge runtime', async () => { await n
{ "filepath": "test/e2e/instrumentation-hook-src/instrumentation-hook-src.test.ts", "language": "typescript", "file_size": 1929, "cut_index": 537, "middle_length": 229 }
alid hrefs', () => { const { next } = nextTestSetup({ files: __dirname, }) const showsError = async ( pathname: string, regex: RegExp, click = false, isWarn = false ) => { const browser = await next.browser(pathname) try { await browser.waitForElementByCss('#click-me') i...
=> setTimeout(resolve, 500)) } if (isWarn) { await retry(async () => { const warnLogs = await browser.eval('window.warnLogs') expect(warnLogs.join('\n')).toMatch(regex) }) } else { await waitFo
ndow.warnLogs.push(args.join(' ')) origWarn.apply(window.console, args) } })()`) } if (click) { await browser.elementByCss('#click-me').click() await new Promise((resolve)
{ "filepath": "test/e2e/invalid-href/invalid-href.test.ts", "language": "typescript", "file_size": 5989, "cut_index": 716, "middle_length": 229 }
io.load(html) const nextData = $('#__NEXT_DATA__') const preEl = $('#props-pre') const routerData = JSON.parse($('#router').text()) return { nextData: JSON.parse(nextData.html()!), pre: preEl.text(), routerData, } } describe('ServerSide Props Preview Mode', () => { const { next, skipped } = nex...
plication', async () => { const res = await next.fetch('/') expect(res.status).toBe(200) }) } it('should return page on first request', async () => { const html = await next.render('/') const { nextData, pre, routerData } = get
rt) { it('should compile successfully', async () => { expect(next.cliOutput).toMatch(/Compiled successfully/) expect(next.cliOutput).not.toContain('Build error occurred') }) it('should start production ap
{ "filepath": "test/e2e/getserversideprops-preview/getserversideprops-preview.test.ts", "language": "typescript", "file_size": 8145, "cut_index": 716, "middle_length": 229 }
waitForRedbox, getRedboxHeader } from 'next-test-utils' describe('withRouter', () => { const { next, isTurbopack, isNextDev } = nextTestSetup({ files: __dirname, }) ;(isTurbopack && isNextDev ? describe.skip : describe)( 'production mode', () => { it('allows observation of navigation events us...
expect(activePage).toBe('Bar') }) it('allows observation of navigation events using top level Router', async () => { const browser = await next.browser('/a') await browser.waitForElementByCss('#page-a') let activeP
ve').text() expect(activePage).toBe('Foo') await browser.elementByCss('button').click() await browser.waitForElementByCss('#page-b') activePage = await browser.elementByCss('.active').text()
{ "filepath": "test/e2e/with-router/index.test.ts", "language": "typescript", "file_size": 2558, "cut_index": 563, "middle_length": 229 }
sable jest/no-standalone-expect */ import { nextTestSetup } from 'e2e-utils' describe('Root components import order', () => { const { next, isTurbopack } = nextTestSetup({ files: __dirname, }) it('root components should be imported in order _document > _app > page to respect side effects', async () => { ...
be attached to the dom before page chunks', async () => { const $ = await next.render$('/') const requiredByRegex = /^\/_next\/static\/chunks\/(requiredBy\w*).*\.js/ const chunks = Array.from($('head').contents()) .filter(
h((sideEffectCall, index) => { expect($(sideEffectCall).text()).toEqual(expectSideEffectsOrder[index]) }) }) // Test relies on webpack splitChunks overrides. ;(isTurbopack ? it.skip : it)( '_app chunks should
{ "filepath": "test/e2e/app-document-import-order/app-document-import-order.test.ts", "language": "typescript", "file_size": 1463, "cut_index": 524, "middle_length": 229 }
from 'next/link' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() if (router.isFallback) return 'Loading...' return ( <> <p id="gsp">gsp page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> ...
without params if (!params || !params.slug) { throw new Error(`missing params ${JSON.stringify(params)}`) } if (locale === 'en' || locale === 'nl') { return { notFound: true, } } return { props: { params, loca
uter-as-path">{router.asPath}</p> <Link href="/" id="to-index"> to / </Link> <br /> </> ) } export const getStaticProps = ({ params, locale, locales }) => { // ensure getStaticProps isn't called
{ "filepath": "test/e2e/i18n-support/pages/not-found/fallback/[slug].js", "language": "javascript", "file_size": 1266, "cut_index": 524, "middle_length": 229 }
import Link from 'next/link' export default function Main({ message }) { return ( <div> <h1 className="title">Hello {message}</h1> <ul> <li> <Link href="/stream-response">Stream a response</Link> </li> <li> <Link href="/rewrite-me-to-about?messa...
utes/hello-world" id="go-to-hello-world-anchor" > Hello World </Link> </li> </ul> </div> ) } export const getServerSideProps = ({ query }) => ({ props: { message: query.message || 'World' }
href="/rewrite-me-to-vercel">Rewrite me to Vercel</Link> </li> <li> <Link href="/redirect-me-to-about">redirect me to about</Link> </li> <li> <Link href="/dynamic-ro
{ "filepath": "test/e2e/middleware-base-path/app/pages/index.js", "language": "javascript", "file_size": 1002, "cut_index": 512, "middle_length": 229 }
'next/link' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() return ( <> <p id="gssp">gssp page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-default-locale">{router.defaultL...
<Link href="/" id="to-index"> to / </Link> <br /> </> ) } export const getServerSideProps = ({ params, locale, locales, defaultLocale, }) => { return { props: { params, locale, locales, def
<p id="router-as-path">{router.asPath}</p>
{ "filepath": "test/e2e/i18n-support/pages/gssp/[slug].js", "language": "javascript", "file_size": 862, "cut_index": 529, "middle_length": 52 }
t Link from 'next/link' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() return ( <> <p id="gsp">gsp page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-default-locale">{route...
}</p> <Link href="/" id="to-index"> to / </Link> <br /> </> ) } export const getStaticProps = ({ locale, locales, defaultLocale }) => { return { props: { locale, locales, defaultLocale, }, } }
ame}</p> <p id="router-as-path">{router.asPath
{ "filepath": "test/e2e/i18n-support/pages/gsp/index.js", "language": "javascript", "file_size": 825, "cut_index": 517, "middle_length": 52 }
from 'next/link' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() if (router.isFallback) return 'Loading...' return ( <> <p id="gsp">gsp page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> ...
locale, locales, defaultLocale }) => { // ensure getStaticProps isn't called without params if (!params || !params.slug) { throw new Error(`missing params ${JSON.stringify(params)}`) } return { props: { params, locale, lo
<p id="router-pathname">{router.pathname}</p> <p id="router-as-path">{router.asPath}</p> <Link href="/" id="to-index"> to / </Link> <br /> </> ) } export const getStaticProps = ({ params,
{ "filepath": "test/e2e/i18n-support/pages/gsp/no-fallback/[slug].js", "language": "javascript", "file_size": 1310, "cut_index": 524, "middle_length": 229 }
#__NEXT_DATA__').html()), draft: $('#draft').text(), rand: $('#rand').text(), count: $('#count').text(), } } describe('Test Draft Mode', () => { const { next, isNextDev, isNextStart, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, }) if (skipped) return if (isNextDev)...
ect(cookies[0]).toBeTruthy() expect(cookies[0].__prerender_bypass).toBeTruthy() }) it('should start the client-side browser', async () => { const browser = await next.browser('/api/enable') await browser.close() }) it('s
async () => { const res = await next.fetch('/api/enable') expect(res.status).toBe(200) const cookies = res.headers .get('set-cookie') .split(',') .map((c) => cookie.parse(c)) exp
{ "filepath": "test/e2e/draft-mode/draft-mode.test.ts", "language": "typescript", "file_size": 7064, "cut_index": 716, "middle_length": 229 }
estSetup, type Playwright } from 'e2e-utils' import { check, waitFor } from 'next-test-utils' import type { HistoryState } from 'next/dist/shared/lib/router/router' const emitPopsStateEvent = (browser: Playwright, state: HistoryState) => browser.eval( `window.dispatchEvent(new PopStateEvent("popstate", { state:...
ser = await next.browser('/sv/static') const state: HistoryState = { url: '/[dynamic]?', as: '/static', options: { locale: 'sv' }, __N: true, key: '', } expect(await browser.elementByCss('#page-type').text()).toB
es: new FileRef(join(__dirname, 'app/pages')), 'next.config.js': new FileRef(join(__dirname, 'app/next.config.js')), }, dependencies: {}, }) test('Ignore event without query param', async () => { const brow
{ "filepath": "test/e2e/ignore-invalid-popstateevent/with-i18n.test.ts", "language": "typescript", "file_size": 2583, "cut_index": 563, "middle_length": 229 }
nk' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() if (router.isFallback) { return ( <> <p>Loading...</p> <p id="router-query">{JSON.stringify(router.query)}</p> </> ) } return ( <> <p id="gsp">gsp page</p...
ex"> to / </Link> <br /> </> ) } export const getStaticProps = ({ params, locale, locales, defaultLocale }) => { // ensure getStaticProps isn't called without params if (!params || !params.slug) { throw new Error(`missing
SON.stringify(router.locales)}</p> <p id="router-query">{JSON.stringify(router.query)}</p> <p id="router-pathname">{router.pathname}</p> <p id="router-as-path">{router.asPath}</p> <Link href="/" id="to-ind
{ "filepath": "test/e2e/i18n-support/pages/gsp/fallback/[slug].js", "language": "javascript", "file_size": 2017, "cut_index": 537, "middle_length": 229 }
tTestSetup, isNextDev } from 'e2e-utils' describe('Nullish configs in next.config.js', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipStart: true, skipDeployment: true, }) if (skipped) return afterEach(async () => { await next.stop().catch(() => {}) }) it('should ...
xpect(next.cliOutput).toMatch(/ready/i) } else { expect(next.cliOutput).toMatch(/Compiled successfully/i) } }) it('should ignore configs set to `null` in next.config.js', async () => { await next.patchFile( 'next.config.js',
ndefined, webpack: undefined, pageExtensions: undefined, } ` ) await next.start() const html = await next.render('/') expect(html).toContain('Hello World') if (isNextDev) { e
{ "filepath": "test/e2e/nullish-config/nullish-config.test.ts", "language": "typescript", "file_size": 1420, "cut_index": 524, "middle_length": 229 }
{ sass: 'latest', }, skipDeployment: true, }) if (skipped) return it('should render the page', async () => { const $ = await next.render$('/hello') expect($('body').text()).toMatch(/Hello World/) expect($('body').text()).toMatch(/1000000000000/) }) it('should render the cookies pag...
, async () => { const $ = await next.render$('/generics') expect($('#value').text()).toBe('Hello World from Generic') }) it('should render the angle bracket type assertions page', async () => { const $ = await next.render$('/angle-bracket-
res = await next.fetch('/ssr/cookies', { headers: { Cookie: 'key=value;', }, }) const html = await res.text() expect(html).toContain(`{"key":"value"}`) }) it('should render the generics page'
{ "filepath": "test/e2e/typescript/typescript.test.ts", "language": "typescript", "file_size": 5181, "cut_index": 716, "middle_length": 229 }
{ useRouter } from 'next/router' import React, { type JSX } from 'react' import { hello } from '../components/hello' import Image from '../components/image' import Link from '../components/link' import Router from '../components/router' import { World } from '../components/world' import { value as resolveOrderValue } ...
on HelloPage(): JSX.Element { const router = useRouter() console.log(process.browser) console.log(router.pathname) console.log(router.isReady) console.log(router.isPreview) return ( <div> <p>One trillion dollars: {1_000_000_000_000}</
OPIC = 4, } // supports override class Test { show() { console.log('show Test') } } class Test2 extends Test { override show() { console.log('overriding show Test') } } new Test2().show() export default functi
{ "filepath": "test/e2e/typescript/pages/hello.tsx", "language": "tsx", "file_size": 1150, "cut_index": 518, "middle_length": 229 }
from 'e2e-utils' describe('Client-side rewrites resolving', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should break rewrites chain when dynamic route matches', async () => { const browser = await next.browser('/') await browser.elementByCss('#product-link').click() await b...
roducts') }) it('should break rewrites chain when dynamic catch-all route matches', async () => { const browser = await next.browser('/') await browser.elementByCss('#category-link').click() await browser.waitForElementByCss('#category')
c () => { const browser = await next.browser('/') await browser.elementByCss('#products-link').click() await browser.waitForElementByCss('#products') expect(await browser.elementByCss('#products').text()).toBe('p
{ "filepath": "test/e2e/rewrites-client-resolving/rewrites-client-resolving.test.ts", "language": "typescript", "file_size": 1808, "cut_index": 537, "middle_length": 229 }
{ nextTestSetup } from 'e2e-utils' describe('invalid-static-asset-404-pages-asset-prefix', () => { const { next } = nextTestSetup({ files: __dirname, nextConfig: { assetPrefix: '/assets', }, }) it('should return correct output with status 200 on valid asset path', async () => { const buil...
pect(res.status).toBe(404) const text = await res.text() expect(text).toContain('Custom Not Found') }) it('should return 404 with plain text when fetching invalid asset path', async () => { const res = await next.fetch('/assets/_next/stati
const text = await res.text() expect(text).toContain('__BUILD_MANIFEST') }) it('should return custom 404 page when fetching invalid non-asset path', async () => { const res = await next.fetch('/invalid-path') ex
{ "filepath": "test/e2e/invalid-static-asset-404-pages/invalid-static-asset-404-pages-asset-prefix.test.ts", "language": "typescript", "file_size": 1130, "cut_index": 518, "middle_length": 229 }
ort { nextTestSetup } from 'e2e-utils' describe('invalid-static-asset-404-pages-base-path', () => { const { next } = nextTestSetup({ files: __dirname, nextConfig: { basePath: '/base', }, }) it('should return correct output with status 200 on valid asset path', async () => { const buildMani...
ct(res.status).toBe(404) const text = await res.text() expect(text).toContain('Custom Not Found') }) it('should return 404 with plain text when fetching invalid asset path', async () => { const res = await next.fetch('/base/_next/static/in
text = await res.text() expect(text).toContain('__BUILD_MANIFEST') }) it('should return custom 404 page when fetching invalid non-asset path', async () => { const res = await next.fetch('/base/invalid-path') expe
{ "filepath": "test/e2e/invalid-static-asset-404-pages/invalid-static-asset-404-pages-base-path.test.ts", "language": "typescript", "file_size": 1123, "cut_index": 515, "middle_length": 229 }
mport { nextTestSetup } from 'e2e-utils' describe('invalid-static-asset-404-pages', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should return correct output with status 200 on valid asset path', async () => { const buildManifestPath = `/_next/static/${next.buildId}/_buildManifest.j...
t(text).toContain('Custom Not Found') }) it('should return 404 with plain text when fetching invalid asset path', async () => { const res = await next.fetch('/_next/static/invalid-path') expect(res.status).toBe(404) const text = await res.
IFEST') }) it('should return custom 404 page when fetching invalid non-asset path', async () => { const res = await next.fetch('/invalid-path') expect(res.status).toBe(404) const text = await res.text() expec
{ "filepath": "test/e2e/invalid-static-asset-404-pages/invalid-static-asset-404-pages.test.ts", "language": "typescript", "file_size": 1048, "cut_index": 513, "middle_length": 229 }
tTestSetup, isNextDev } from 'e2e-utils' // `exportPathMap` + `useFileSystemPublicRoutes: false` is a dev-only routing // behavior; the custom server runs `next({ dev: true })` so production mode is // not exercised by the original integration test. ;(isNextDev ? describe : describe.skip)('FileSystemPublicRoutes', () ...
tPathMap defined routes in development', async () => { const res = await next.fetch('/exportpathmap-route') expect(res.status).toBe(200) const body = await res.text() expect(body).toMatch(/exportpathmap was here/) }) it('should serve J
it('should not route to the index page', async () => { const res = await next.fetch('/') expect(res.status).toBe(404) const body = await res.text() expect(body).toMatch(/404/) }) it('should route to expor
{ "filepath": "test/e2e/filesystempublicroutes/filesystempublicroutes.test.ts", "language": "typescript", "file_size": 1449, "cut_index": 524, "middle_length": 229 }
http = require('http') const next = require('next') const getPort = require('get-port') const dev = process.env.NODE_ENV !== 'production' const dir = __dirname const app = next({ dev, dir }) const handleNextRequests = app.getRequestHandler() async function main() { await app.prepare() const port = await getPort...
app.setAssetPrefix('') } else { app.setAssetPrefix('') } handleNextRequests(req, res) }) server.listen(port, () => { console.log(`- Local: http://localhost:${port}`) }) } main().catch((err) => { console.error(err) proce
q.url)) {
{ "filepath": "test/e2e/filesystempublicroutes/server.js", "language": "javascript", "file_size": 801, "cut_index": 517, "middle_length": 14 }
from 'child_process' import { nextTestSetup, isNextDev } from 'e2e-utils' import { shouldUseTurbopack } from 'next-test-utils' const relayCompilerPath = join( __dirname, '../../../node_modules/relay-compiler/cli.js' ) describe('Relay Compiler Transform - Multi Project Config', () => { beforeAll(() => { exe...
// The relay SWC transform uses `process.cwd()` as its root, so the // Next.js process must run with its working directory set to the // sub-project. We do that here by wrapping the command in a shell // script defined via `packageJson
__dirname, dependencies: { 'relay-runtime': '13.0.2', '@types/relay-runtime': '14.1.13', react: '19.3.0-canary-fef12a01-20260413', 'react-dom': '19.3.0-canary-fef12a01-20260413', },
{ "filepath": "test/e2e/relay-graphql-swc-multi-project/relay-graphql-swc-multi-project.test.ts", "language": "typescript", "file_size": 2947, "cut_index": 563, "middle_length": 229 }
rated SignedSource<<9f92ea3ccfda1f64fa269e68b912abae>> * @lightSyntaxTransform * @nogrep */ /* tslint:disable */ /* eslint-disable */ // @ts-nocheck import { ConcreteRequest, Query } from 'relay-runtime' export type pagesBQuery$variables = {} export type pagesBQueryVariables = pagesBQuery$variables export type pag...
Definitions: [], kind: 'Fragment', metadata: null, name: 'pagesBQuery', selections: v0 /*: any*/, type: 'Query', abstractKey: null, }, kind: 'Request', operation: { argumentDefinitions: [], kind:
const node: ConcreteRequest = (function () { var v0 = [ { alias: null, args: null, kind: 'ScalarField', name: 'greeting', storageKey: null, }, ] return { fragment: { argument
{ "filepath": "test/e2e/relay-graphql-swc-multi-project/project-b/__generated__/pagesBQuery.graphql.ts", "language": "typescript", "file_size": 1393, "cut_index": 524, "middle_length": 229 }
nvironment, FetchFunction, fetchQuery, graphql, Network, RecordSource, Store, } from 'relay-runtime' import { GetServerSideProps } from 'next' import { pagesBQuery } from '../__generated__/pagesBQuery.graphql' type Props = { greeting: string } export default function Index({ greeting }: Props) { return ...
variables, }), }) return await response.json() } } export const getServerSideProps: GetServerSideProps = async ({ req }) => { const environment = new Environment({ store: new Store(new RecordSource({}), {}), network: Network
/${host}/api/query` : `/api/query` const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: params.text,
{ "filepath": "test/e2e/relay-graphql-swc-multi-project/project-b/pages/index.tsx", "language": "tsx", "file_size": 1405, "cut_index": 524, "middle_length": 229 }