prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
ire('next/dist/compiled/http-proxy')
const PROXY_PORT = process.env.PROXY_PORT
const SERVER_PORT = process.env.SERVER_PORT
httpProxy
.createProxyServer({ target: 'http://localhost:' + SERVER_PORT })
.listen(PROXY_PORT)
const cssResponse = `
/* cyrillic-ext */
@font-face {
font-family: 'Oswald';
font-style: n... | 3iWkUHHAIjg752HT8Gl-1PK62t.woff2) format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* vietnamese */
@font-face {
font-family: 'Oswald';
font-style: normal;
font-weight: 200 700;
font-display: swap;
src: u | -1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Oswald';
font-style: normal;
font-weight: 200 700;
font-display: swap;
src: url(https://fonts.gstatic.com/s/oswald/v49/TK | {
"filepath": "test/e2e/next-font/with-proxy/server.js",
"language": "javascript",
"file_size": 2411,
"cut_index": 563,
"middle_length": 229
} |
o } from 'next/font/google'
import localFont from 'next/font/local'
const firaCode = Fira_Code({ variable: '--fira-code', subsets: ['latin'] })
const roboto = Roboto({
weight: '100',
style: 'italic',
display: 'swap',
preload: true,
variable: '--roboto-100-italic',
subsets: ['latin'],
})
const myFont = loca... | { fontFamily: 'var(--fira-code)' }}
>
Without variables
</div>
{/* Roboto 100 Italic */}
<div
id="variables-roboto-100-italic"
className={roboto.variable}
style={{ fontFamily: 'var(--roboto-100-itali | id="variables-fira-code"
className={firaCode.variable}
style={{ fontFamily: 'var(--fira-code)' }}
>
With variables
</div>
<div
id="without-variables-fira-code"
style={ | {
"filepath": "test/e2e/next-font/app/pages/variables.js",
"language": "javascript",
"file_size": 1602,
"cut_index": 537,
"middle_length": 229
} |
import localFont from 'next/font/local'
import { Open_Sans } from 'next/font/google'
const openSans = Open_Sans({
fallback: ['system-ui', 'Arial'],
variable: '--open-sans',
adjustFontFallback: false,
subsets: ['latin'],
})
const myFont = localFont({
fallback: ['system-ui', 'Arial'],
src: '../fonts/my-font.... | tyle={{ fontFamily: 'var(--open-sans)' }}
className={openSans.variable}
>
{JSON.stringify(openSans)}
</div>
<div id="with-fallback-local" className={myFont.className}>
{JSON.stringify(myFont)}
</div>
</>
| me}>
{JSON.stringify(openSans)}
</div>
<div id="with-fallback-fonts-style" style={openSans.style}>
{JSON.stringify(openSans)}
</div>
<div
id="with-fallback-fonts-variable"
s | {
"filepath": "test/e2e/next-font/app/pages/with-fallback.js",
"language": "javascript",
"file_size": 1003,
"cut_index": 512,
"middle_length": 229
} |
unces, Indie_Flower, Roboto } from 'next/font/google'
const indieFlower = Indie_Flower({
weight: '400',
preload: false,
subsets: ['latin'],
})
const fraunces = Fraunces({ weight: '400', preload: false, subsets: ['latin'] })
const robotoMultiple = Roboto({
weight: ['900', '100'],
style: ['normal', 'italic'],... | </div>
<div id="second-google-font" className={fraunces.className}>
{JSON.stringify(fraunces)}
</div>
<div id="multiple-roboto" className={robotoMultiple.className}>
{JSON.stringify(robotoMultiple)}
</div>
< | s({
weight: ['100', '400', '900'],
subsets: ['latin'],
})
export default function WithFonts() {
return (
<>
<div id="first-google-font" className={indieFlower.className}>
{JSON.stringify(indieFlower)}
| {
"filepath": "test/e2e/next-font/app/pages/with-google-fonts.js",
"language": "javascript",
"file_size": 1321,
"cut_index": 524,
"middle_length": 229
} |
style: 'italic',
weight: '100',
fallback: ['system-ui'],
adjustFontFallback: 'Times New Roman',
declarations: [{ prop: 'ascent-override', value: '90%' }],
})
const myFont2 = localFont({
src: '../fonts/my-other-font.woff2',
preload: false,
variable: '--my-font',
})
const myFont1Override = localFont({
s... | 2',
weight: '400',
style: 'italic',
},
{
path: '../fonts/roboto/roboto-400.woff2',
weight: '400',
},
{
path: '../fonts/my-font.woff2',
style: 'italic',
},
{
path: '../fonts/my-font.woff2',
| '../fonts/roboto/roboto-100-italic.woff2',
weight: '100',
style: 'italic',
},
{
path: '../fonts/my-font.woff2',
weight: '100',
style: 'normal',
},
{
path: '../fonts/my-font.woff | {
"filepath": "test/e2e/next-font/app/pages/with-local-fonts.js",
"language": "javascript",
"file_size": 3552,
"cut_index": 614,
"middle_length": 229
} |
retry } from 'next-test-utils'
const customErrNo404Match =
/You have added a custom \/_error page without a custom \/404 page/
describe('Custom _error', () => {
const { next, isNextDev, isNextStart } = nextTestSetup({
files: __dirname,
dependencies: {
react: '19.3.0-canary-fef12a01-20260413',
... | html).toContain("Expected '\\u003c/', got '\\u003ceof\\u003e'")
expect(next.cliOutput.slice(outputIndex)).not.toMatch(
customErrNo404Match
)
})
} finally {
await next.deleteFile('pages/404.js')
}
| {
const outputIndex = next.cliOutput.length
await next.patchFile('pages/404.js', 'export default <h1>')
try {
await retry(async () => {
const html = await next.render('/404')
expect( | {
"filepath": "test/e2e/custom-error/custom-error.test.ts",
"language": "typescript",
"file_size": 2281,
"cut_index": 563,
"middle_length": 229
} |
are Redirect', () => {
const { next } = nextTestSetup({
files: {
pages: new FileRef(join(__dirname, '../app/pages')),
...(process.env.TEST_NODE_MIDDLEWARE
? {
'proxy.js': new FileRef(join(__dirname, '../app/middleware.js')),
}
: {
'middleware.js': new ... | rElementByCss('#dynamic')
expect(await browser.elementByCss('#dynamic').text()).toBe(
'Welcome to a /dynamic/[slug]: new'
)
})
it('does not include the locale in redirects by default', async () => {
const res = await fetc | n tests() {
it('should redirect correctly with redirect in next.config.js', async () => {
const browser = await next.browser('/')
await browser.eval('window.next.router.push("/to-new")')
await browser.waitFo | {
"filepath": "test/e2e/middleware-redirects/test/index.test.ts",
"language": "typescript",
"file_size": 6499,
"cut_index": 716,
"middle_length": 229
} |
default async function middleware(request) {
const url = request.nextUrl
// this is needed for tests to get the BUILD_ID
if (url.pathname.startsWith('/_next/static/__BUILD_ID')) {
return NextResponse.next()
}
if (url.pathname === '/old-home') {
if (url.searchParams.get('override') === 'external') {
... | turn Response.redirect(url)
}
if (url.pathname === '/redirect-me-alot-2') {
url.pathname = '/redirect-me-alot-3'
return Response.redirect(url)
}
if (url.pathname === '/redirect-me-alot-3') {
url.pathname = '/redirect-me-alot-4'
re | bar') {
url.pathname = '/new-home'
url.searchParams.delete('foo')
return Response.redirect(url)
}
// Chained redirects
if (url.pathname === '/redirect-me-alot') {
url.pathname = '/redirect-me-alot-2'
re | {
"filepath": "test/e2e/middleware-redirects/app/middleware.js",
"language": "javascript",
"file_size": 2179,
"cut_index": 563,
"middle_length": 229
} |
from 'next/link'
export default function Home() {
return (
<div>
<p className="title">Home Page</p>
<Link href="/old-home" id="old-home">
Redirect me to a new version of a page
</Link>
<div />
<Link href="/old-home?override=external" id="old-home-external">
Redirect ... | e-alot">Redirect me alot (chained requests)</Link>
<div />
<Link href="/infinite-loop">Redirect me alot (infinite loop)</Link>
<div />
<Link
href="/to?pathname=/api/ok"
locale="nl"
id="link-to-api-with-locale | Redirect me to Google (with no body response)
</Link>
<div />
<Link href="/redirect-to-google">
Redirect me to Google (with no stream response)
</Link>
<div />
<Link href="/redirect-m | {
"filepath": "test/e2e/middleware-redirects/app/pages/index.js",
"language": "javascript",
"file_size": 1264,
"cut_index": 524,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
describe('transpile-packages-typescript-foreign', () => {
describe('without transpilePackages', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
skipStart: true,
dependencies: {
pkg: `file:./pkg`,
},
... | ).toBeLessThanOrEqual(1)
expect(next.cliOutput.match(/Missing module type/g)?.length ?? 0).toBe(
0
)
} else {
expect(next.cliOutput).toContain(`pkg/index.ts
Module parse failed: Unexpected token`)
}
})
}) | .IS_TURBOPACK_TEST) {
expect(next.cliOutput).toContain(`pkg/index.ts
Unknown module type
This module doesn't have an associated type`)
expect(
next.cliOutput.match(/Unknown module type/g).length
| {
"filepath": "test/e2e/transpile-packages-typescript-foreign/index.test.ts",
"language": "typescript",
"file_size": 1467,
"cut_index": 524,
"middle_length": 229
} |
port { retry } from 'next-test-utils'
describe('nested index.js', () => {
const { next, isTurbopack, skipped } = nextTestSetup({
files: __dirname,
// Vercel's deploy infrastructure normalizes nested `/index/index/index`
// paths differently from Next.js's local server, so the routing
// assertions he... | ', async () => {
const browser = await next.browser('/links')
await browser.elementByCss('#link1').click()
await retry(async () => {
const text = await browser.elementByCss('#page').text()
expect(text).toBe('index')
})
})
i | ')
})
it('should client render page /', async () => {
const browser = await next.browser('/')
const text = await browser.elementByCss('#page').text()
expect(text).toBe('index')
})
it('should follow link to / | {
"filepath": "test/e2e/index-index/index-index.test.ts",
"language": "typescript",
"file_size": 4832,
"cut_index": 614,
"middle_length": 229
} |
ame,
})
describe('_document', () => {
it('should include required elements in rendered html', async () => {
const $ = await next.render$('/')
// It has a custom html class
expect($('html').hasClass('test-html-props')).toBe(true)
// It has a custom body class
expect($('body').hasCl... | senting app shell', async () => {
// Extract css-in-js-class from the rendered HTML, which is returned by Document.getInitialProps
const $index = await next.render$('/')
const $about = await next.render$('/about')
expect($index('#cs | t#__NEXT_DATA__')).toBeTruthy()
// It passes props from Document.getInitialProps to Document
expect($('#custom-property').text()).toBe('Hello Document')
})
it('Document.getInitialProps returns html prop repre | {
"filepath": "test/e2e/app-document/rendering.test.ts",
"language": "typescript",
"file_size": 6230,
"cut_index": 716,
"middle_length": 229
} |
mport App from 'next/app'
import React from 'react'
import { setState } from '../shared-module'
setState(typeof window === 'undefined' ? 'UPDATED' : 'UPDATED CLIENT')
class Layout extends React.Component {
state = {
random: false,
}
componentDidMount() {
this.setState({ random: Math.random() })
}
... | ops = {}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
return { pageProps }
}
render() {
const { Component, pageProps } = this.props
return (
<Layout>
<Component {...pageP | <p id="random-number">{random}</p>
{children}
</div>
)
}
}
export default class MyApp extends App {
static async getInitialProps({ Component, router, ctx }) {
// throw _app GIP err here
let pagePr | {
"filepath": "test/e2e/app-document/pages/_app.js",
"language": "javascript",
"file_size": 1035,
"cut_index": 513,
"middle_length": 229
} |
, Head, Main, NextScript } from 'next/document'
const cspHashOf = (text) => {
const hash = crypto.createHash('sha256')
hash.update(text)
return `'sha256-${hash.digest('base64')}'`
}
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
let options
const enhanceCompone... | x.query.withEnhanceComponent || ctx.query.withEnhanceApp) {
options = {}
if (ctx.query.withEnhanceComponent) {
options.enhanceComponent = enhanceComponent
}
if (ctx.query.withEnhanceApp) {
options.enhanceApp = enhanc | ent) => (props) => (
<div>
<span id="render-page-enhance-app">RENDERED</span>
<Component {...props} />
</div>
)
if (ctx.query.withEnhancer) {
options = enhanceComponent
} else if (ct | {
"filepath": "test/e2e/app-document/pages/_document.js",
"language": "javascript",
"file_size": 2369,
"cut_index": 563,
"middle_length": 229
} |
ic from 'next/dynamic'
import { useState, useEffect } from 'react'
import FourDirect from '../components/four'
const One = dynamic(() => import('../components/one'))
const Two = dynamic(() => import('../components/two'))
const Three = dynamic(() => import('../components/three'))
const Four = dynamic(() => import('../c... | ')
const [beforeHydration, setBeforeHydration] = useState(
'the-second-server-value'
)
useEffect(() => {
setFirstRender(document.getElementById('foo').innerHTML)
setBeforeHydration(BEFORE_HYDRATION)
}, [])
return (
<>
<div | n(' ')
origError(...args)
}
}
const BEFORE_HYDRATION =
typeof document !== 'undefined' && document.getElementById('foo').innerHTML
const Index = () => {
const [firstRender, setFirstRender] = useState('the-server-value | {
"filepath": "test/e2e/next-dynamic-lazy-compilation/pages/index.js",
"language": "javascript",
"file_size": 1277,
"cut_index": 524,
"middle_length": 229
} |
import { renderViaHTTP } from 'next-test-utils'
import cheerio from 'cheerio'
import path from 'path'
async function matchLogs(browser, includes: string) {
let found = false
const browserLogs = await browser.log()
browserLogs.forEach((log) => {
if (log.message.includes(includes)) {
found = true
}... | const $ = cheerio.load(html)
const $a = $('a')
expect($a.text()).toBe('About')
expect($a.attr('href')).toBe('/about')
})
it('should navigate to /about', async () => {
const browser = await next.browser(`/`)
await browser.elementB | Dir, 'pages')),
'next.config.js': new FileRef(path.join(appDir, 'next.config.js')),
},
dependencies: {},
})
it('should render link with <a>', async () => {
const html = await renderViaHTTP(next.url, '/')
| {
"filepath": "test/e2e/new-link-behavior/index.test.ts",
"language": "typescript",
"file_size": 2685,
"cut_index": 563,
"middle_length": 229
} |
mport { FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path'
const appDir = path.join(__dirname, 'material-ui')
describe('New Link Behavior with material-ui', () => {
const { next } = nextTestSetup({
files: {
pages: new FileRef(path.join(appDir, 'pages')),
src: new FileRef(path.join(app... | const browser = await next.browser(`/`)
const element = browser.elementByCss('a[href="/about"]')
const color = await element.getComputedCss('color')
expect(color).toBe('rgb(25, 133, 123)')
const text = await element.text()
expect( | motion/server': 'latest',
'@emotion/styled': 'latest',
'@mui/icons-material': 'latest',
'@mui/material': 'latest',
'prop-types': 'latest',
},
})
it('should render MuiLink with <a>', async () => {
| {
"filepath": "test/e2e/new-link-behavior/material-ui.test.ts",
"language": "typescript",
"file_size": 1041,
"cut_index": 513,
"middle_length": 229
} |
hemeProvider } from '@mui/material/styles'
import CssBaseline from '@mui/material/CssBaseline'
import { CacheProvider } from '@emotion/react'
import theme from '../src/theme'
import createEmotionCache from '../src/createEmotionCache'
// Client-side cache, shared for the whole session of the user in the browser.
const ... | a name="viewport" content="initial-scale=1, width=device-width" />
</Head>
<ThemeProvider theme={theme}>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<Component | ider value={emotionCache}>
<Head>
<met | {
"filepath": "test/e2e/new-link-behavior/material-ui/pages/_app.js",
"language": "javascript",
"file_size": 959,
"cut_index": 582,
"middle_length": 52
} |
from '@stitches/react'
export const {
config,
createTheme,
css,
getCssText,
globalCss,
styled,
theme,
} = createStitches({
theme: {
colors: {
hiContrast: 'hsl(206,10%,5%)',
loContrast: 'white',
gray100: 'hsl(206,22%,99%)',
gray200: 'hsl(206,12%,97%)',
gray300: 'hsl(2... | 4: '20px',
5: '25px',
6: '35px',
},
sizes: {
1: '5px',
2: '10px',
3: '15px',
4: '20px',
5: '25px',
6: '35px',
},
fontSizes: {
1: '12px',
2: '13px',
3: '15px',
4: '17px' | )',
purple300: 'hsl(252,100%,94%)',
purple400: 'hsl(252,75%,84%)',
purple500: 'hsl(252,78%,60%)',
purple600: 'hsl(252,80%,53%)',
},
space: {
1: '5px',
2: '10px',
3: '15px',
| {
"filepath": "test/e2e/new-link-behavior/stitches/stitches.config.js",
"language": "javascript",
"file_size": 1564,
"cut_index": 537,
"middle_length": 229
} |
.config'
import StitchesLogo from '../components/StitchesLogo'
const Box = styled('div', {})
const Text = styled('p', {
fontFamily: '$system',
color: '$hiContrast',
})
const Link = styled('a', {
fontFamily: '$system',
textDecoration: 'none',
color: '$purple600',
})
const Container = styled('div', {
marg... | ) {
return (
<Box css={{ paddingY: '$6' }}>
<Container size={{ '@initial': '1', '@bp1': '2' }}>
<StitchesLogo />
<Text as="h1">Hello, from About.</Text>
<Text>
<Link href="/">Visit Home</Link>.
</Text>
| },
},
},
})
export default function Home( | {
"filepath": "test/e2e/new-link-behavior/stitches/pages/about.jsx",
"language": "jsx",
"file_size": 891,
"cut_index": 547,
"middle_length": 52
} |
go from '../components/StitchesLogo'
const Box = styled('div', {})
const Text = styled('p', {
fontFamily: '$system',
color: '$hiContrast',
})
const Link = styled(NextLink, {
fontFamily: '$system',
textDecoration: 'none',
color: '$purple600',
})
const Container = styled('div', {
marginX: 'auto',
paddin... | ox css={{ paddingY: '$6' }}>
<Container size={{ '@initial': '1', '@bp1': '2' }}>
<StitchesLogo />
<Text as="h1">Hello, from Stitches.</Text>
<Text>
<Link href="/about">Visit About</Link>.
</Text>
</Cont |
export default function Home() {
return (
<B | {
"filepath": "test/e2e/new-link-behavior/stitches/pages/index.jsx",
"language": "jsx",
"file_size": 938,
"cut_index": 606,
"middle_length": 52
} |
pped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) return
afterEach(async () => {
await next.deleteFile('middleware.js').catch(() => {})
await next.stop().catch(() => {})
})
function writeMiddleware(matchers: any) {
return next.patchFile... | (isTurbopack && !isDev) {
expect(stderr).toContain('Turbopack build failed with 10 errors')
let matches = 0
matches += stderr.includes('Missing `source` in `matcher[0]` object')
? 1
: 0
matches += stderr.includes(' | onfig = {
matcher: ${JSON.stringify(matchers)},
}
`
)
}
/** Same branching as integration `runTests(getStderr, isDev)`. */
function assertInvalidMatchersStderr(stderr: string, isDev: boolean) {
if | {
"filepath": "test/e2e/invalid-middleware-matchers/invalid-middleware-matchers.test.ts",
"language": "typescript",
"file_size": 5980,
"cut_index": 716,
"middle_length": 229
} |
in(__dirname, '../app/node_modules/shared-package')
),
},
nextConfig: {
experimental: {
webpackBuildWorker: true,
},
...(i18n
? {
i18n: {
locales: ['en', 'fr', 'nl'],
defaultLocale: 'en',
},
... | source: '/rewrite-2',
destination: '/about/a?from=next-config',
},
{
source: '/sha',
destination: '/shallow',
},
{
source: '/rewrite-3',
| t: false,
},
]
},
async rewrites() {
return [
{
source: '/rewrite-1',
destination: '/ssr-page?from=config',
},
{
| {
"filepath": "test/e2e/middleware-general/test/index.test.ts",
"language": "typescript",
"file_size": 29534,
"cut_index": 1331,
"middle_length": 229
} |
export default function Shallow({ message }) {
const { pathname, query } = useRouter()
return (
<div>
<ul>
<li id="message-contents">{message}</li>
<li>
<Link href="/sha?hello=world" shallow id="shallow-link">
Shallow link to ?hello=world
</Link>
</l... | </h1>
</li>
<li>
<h2 id="query" data-query-hello={query.hello}>
Current query: <code>{JSON.stringify(query)}</code>
</h2>
</li>
</ul>
</div>
)
}
let i = 0
export const getServerSideP | Current path: <code>{pathname}</code>
| {
"filepath": "test/e2e/middleware-general/app/pages/shallow.js",
"language": "javascript",
"file_size": 991,
"cut_index": 582,
"middle_length": 52
} |
ort { useRouter } from 'next/router'
import { useEffect } from 'react'
import { useState } from 'react'
export default function Page(props) {
const router = useRouter()
const [asPath, setAsPath] = useState(
router.isReady ? router.asPath : router.href
)
if (!props.params) {
console.error('props', prop... | export function getStaticProps({ params }) {
if (params.slug.includes('not-found')) {
return {
notFound: true,
}
}
return {
props: {
now: Date.now(),
params,
},
}
}
export function getStaticPaths() {
return {
| <p id="ssg">/blog/[slug]</p>
<p id="query">{JSON.stringify(router.query)}</p>
<p id="pathname">{router.pathname}</p>
<p id="as-path">{asPath}</p>
<p id="props">{JSON.stringify(props)}</p>
</>
)
}
| {
"filepath": "test/e2e/middleware-general/app/pages/ssg-fallback-false/[slug].js",
"language": "javascript",
"file_size": 1097,
"cut_index": 515,
"middle_length": 229
} |
from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('router rerender', () => {
const { next } = nextTestSetup({
files: __dirname,
})
describe('with middleware', () => {
it('should not trigger unnecessary rerenders when middleware is used', async () => {
const browser = await next.br... | > {
// TODO: Figure out the `isReady` issue.
it.skip('should not trigger unnecessary rerenders when rewrites are used', async () => {})
it.skip('should rerender with the correct query parameter if present with rewrites', async () => {})
})
}) | ewrites', () = | {
"filepath": "test/e2e/router-rerender/router-rerender.test.ts",
"language": "typescript",
"file_size": 807,
"cut_index": 536,
"middle_length": 14
} |
, { useCallback, useEffect, useRef, useState } from 'react'
import Link from 'next/link'
const useClickAway = (ref, onClickAway) => {
useEffect(() => {
const handler = (event) => {
const el = ref.current
// when menu is open and clicked inside menu, A is expected to be false
// when menu is op... | stener('click', handler)
}
}, [onClickAway, ref])
}
export default function App() {
const [open, setOpen] = useState(false)
const menuRef = useRef(null)
const onClickAway = useCallback(() => {
console.log('click away, open', open)
if | outID = setTimeout(() => {
timeoutID = null
document.addEventListener('click', handler)
}, 0)
return () => {
if (timeoutID != null) {
clearTimeout(timeoutID)
}
document.removeEventLi | {
"filepath": "test/e2e/link-ref-pages/pages/click-away-race-condition.js",
"language": "javascript",
"file_size": 1348,
"cut_index": 524,
"middle_length": 229
} |
v } from 'e2e-utils'
describe('externals-pages-bundle', () => {
const { next, isTurbopack, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) return
describe('bundle pages externals with config.bundlePagesRouterDependencies', () => {
if (!isNex... | expect(pageBundleBasenames).not.toBeEmpty()
let allBundles = ''
for (const basename of pageBundleBasenames) {
const output = await fs.readFile(join(ssrPath, basename), 'utf8')
allBundles += output
}
| et', async () => {
if (isTurbopack) {
const ssrPath = join(next.testDir, '.next/server/chunks/ssr')
const pageBundleBasenames = (await fs.readdir(ssrPath)).filter((p) =>
p.match(/\.js$/)
)
| {
"filepath": "test/e2e/externals-pages-bundle/externals-pages-bundle.test.ts",
"language": "typescript",
"file_size": 3327,
"cut_index": 614,
"middle_length": 229
} |
eRef, isNextDev, nextTestSetup } from 'e2e-utils'
import path from 'path'
const appDir = path.join(__dirname, 'child-a-tag-error')
describe('New Link Behavior with <a> child', () => {
const { next } = nextTestSetup({
files: {
pages: new FileRef(path.join(appDir, 'pages')),
'next.config.js': new File... | or>'
)
await expect(browser).toDisplayRedbox(`
{
"code": "E209",
"description": "Invalid <Link> with <a> child. Please remove <a> or use <Link legacyBehavior>.
Learn more: https://nextjs.org/docs/messages/invalid | rowser(`/`)
const link = await browser.elementsByCss('a[href="/about"]')
if (isNextDev) {
expect(next.cliOutput).toContain(
'Error: Invalid <Link> with <a> child. Please remove <a> or use <Link legacyBehavi | {
"filepath": "test/e2e/new-link-behavior/child-a-tag-error.test.ts",
"language": "typescript",
"file_size": 1280,
"cut_index": 524,
"middle_length": 229
} |
ath'
const appDir = path.join(__dirname, 'stitches')
describe('New Link Behavior with stitches', () => {
const { next } = nextTestSetup({
files: {
pages: new FileRef(path.join(appDir, 'pages')),
components: new FileRef(path.join(appDir, 'components')),
'next.config.js': new FileRef(path.join(a... | >', async () => {
const browser = await next.browser(`/`)
const element = await browser.elementByCss('a[href="/about"]')
const color = await element.getComputedCss('color')
expect(color).toBe('rgb(78, 39, 231)')
const text = await ele | next: 'latest',
},
})
it('should render <a | {
"filepath": "test/e2e/new-link-behavior/stitches.test.ts",
"language": "typescript",
"file_size": 947,
"cut_index": 582,
"middle_length": 52
} |
StitchesLogo = () => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="35"
height="35"
viewBox="0 0 35 35"
fill="none"
>
<circle
cx="17.5"
cy="17.5"
r="14.5"
stroke="currentColor"
strokeWidth="2"
/>
<path d="M12.8184 31.3218L31.8709 20.3218" stroke="curre... | lor"
strokeLinecap="round"
strokeLinejoin="round"
/>
<path
d="M16.6973 12.2302L25.9736 19.1078"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
/>
<path
d="M9.21582 16.0815L19.045 |
strokeLinejoin="round"
/>
<path
d="M9.21582 16.0815L26.5363 6.08154"
stroke="currentColor"
strokeLinecap="round"
/>
<path
d="M13.2334 14.2297L22.5099 21.1077"
stroke="currentCo | {
"filepath": "test/e2e/new-link-behavior/stitches/components/StitchesLogo.jsx",
"language": "jsx",
"file_size": 1146,
"cut_index": 518,
"middle_length": 229
} |
sNextDev } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('Auto Export', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('Supports commonjs 1', async () => {
const browser = await next.browser('/commonjs1')
const html = await browser.eval('document.body.innerHTML'... | ait retry(async () => {
const html = await browser.eval('document.body.innerHTML')
expect(html).toMatch(/post.*post-1/)
})
const html = await browser.eval('document.body.innerHTML')
expect(html).toMatch(/nextExport/)
})
it('sho | await browser.eval('document.body.innerHTML')
expect(html).toMatch(/test2/)
expect(html).toMatch(/nextExport/)
})
it('Refreshes query on mount', async () => {
const browser = await next.browser('/post-1')
aw | {
"filepath": "test/e2e/auto-export/auto-export.test.ts",
"language": "typescript",
"file_size": 1854,
"cut_index": 537,
"middle_length": 229
} |
regions: 'auto',
}
const PATTERNS = [
[
new URLPattern({ pathname: '/:locale/:id' }),
({ pathname }) => ({
pathname: '/:locale/:id',
params: pathname.groups,
}),
],
[
new URLPattern({ pathname: '/:id' }),
({ pathname }) => ({
pathname: '/:id',
params: pathname.groups,... | rl
if (request.headers.get('x-prerender-revalidate')) {
return NextResponse.next({
headers: { 'x-middleware': 'hi' },
})
}
// this is needed for tests to get the BUILD_ID
if (url.pathname.startsWith('/_next/static/__BUILD_ID')) {
| if (patternResult !== null && 'pathname' in patternResult) {
result = handler(patternResult)
break
}
}
return result
}
export async function middleware(request) {
getSomeData()
const url = request.nextU | {
"filepath": "test/e2e/middleware-general/app/middleware.js",
"language": "javascript",
"file_size": 7220,
"cut_index": 716,
"middle_length": 229
} |
ort { useRouter } from 'next/router'
import { useEffect } from 'react'
import { useState } from 'react'
export default function Page(props) {
const router = useRouter()
const [asPath, setAsPath] = useState(
router.isReady ? router.asPath : router.href
)
if (!props.params) {
console.error('props', prop... | export function getStaticProps({ params }) {
if (params.slug.includes('not-found')) {
return {
notFound: true,
}
}
return {
props: {
now: Date.now(),
params,
},
}
}
export function getStaticPaths() {
return {
| <p id="ssg">/blog/[slug]</p>
<p id="query">{JSON.stringify(router.query)}</p>
<p id="pathname">{router.pathname}</p>
<p id="as-path">{asPath}</p>
<p id="props">{JSON.stringify(props)}</p>
</>
)
}
| {
"filepath": "test/e2e/middleware-general/app/pages/ssg/[slug].js",
"language": "javascript",
"file_size": 1072,
"cut_index": 515,
"middle_length": 229
} |
xtTestSetup } from 'e2e-utils'
describe('Document and App - Client side', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
it('should share module state with pages', async () => {
const browser = await next.browser('/shared')
const text = await brow... | expect(text).toBe('Hello HMR')
// change the content
const editedContent = originalContent.replace('Hello HMR', 'Hi HMR')
await next.patchFile(appPath, editedContent)
await retry(async () =>
expect(await browser | const appPath = 'pages/_app.js'
const originalContent = await next.readFile(appPath)
try {
const browser = await next.browser('/')
const text = await browser.elementByCss('#hello-hmr').text()
| {
"filepath": "test/e2e/app-document/client.test.ts",
"language": "typescript",
"file_size": 2994,
"cut_index": 563,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
import { shouldUseTurbopack } from 'next-test-utils'
// This test relies on an experimental webpack feature (lazyCompilation).
describe('next/dynamic lazy compilation', () => {
if (shouldUseTurbopack()) {
it('skips in Turbopack tests', () => {})
return
}
const { next } = ne... | ation').text()
expect(text).toMatch(
/^Index<!--\/?(\$|\s)-->1(<!--\/?(\$|\s)-->)+2(<!--\/?(\$|\s)-->)+3(<!--\/?(\$|\s)-->)+4(<!--\/?(\$|\s)-->)+4$/
)
expect(await browser.eval('window.caughtErrors')).toBe('')
})
it('should render d | ).toMatch(/the-second-server-value/i)
})
it('should render dynamic server rendered values before hydration', async () => {
const browser = await next.browser('/')
const text = await browser.elementByCss('#before-hydr | {
"filepath": "test/e2e/next-dynamic-lazy-compilation/next-dynamic-lazy-compilation.test.ts",
"language": "typescript",
"file_size": 1405,
"cut_index": 524,
"middle_length": 229
} |
tml, Head, Main, NextScript } from 'next/document'
import createEmotionServer from '@emotion/server/create-instance'
import theme from '../src/theme'
import createEmotionCache from '../src/createEmotionCache'
export default class MyDocument extends Document {
render() {
return (
<Html lang="en">
<H... | /}
{this.props.emotionStyleTags}
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
// `getInitialProps` belongs to `_document` (instead of `_app`),
// it's compatible with static | <link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
{/* Inject MUI styles first to match with the prepend: true configuration. * | {
"filepath": "test/e2e/new-link-behavior/material-ui/pages/_document.js",
"language": "javascript",
"file_size": 2635,
"cut_index": 563,
"middle_length": 229
} |
lue from 'shared-package'
export const config = {
regions: 'auto',
runtime: 'nodejs',
}
// When there is a top level await, requiring middleware.js will return a Promise
await new Promise((resolve) => {
setTimeout(resolve, 100)
})
const PATTERNS = []
const params = (url) => {
const input = url.split('?')[0]... | th.join(process.cwd(), 'package.json')
// @vercel/nft's static analysis only recognizes the callback `fs.readFile`
// (and `readFileSync` etc.), not `fs.promises.readFile`. Using the
// callback form lets NFT resolve the path argument and inclu | handler(patternResult)
break
}
}
return result
}
export async function middleware(request) {
getSomeData()
const url = request.nextUrl
if (url.pathname.startsWith('/test-node-fs')) {
const pkgPath = pa | {
"filepath": "test/e2e/middleware-general/app/middleware-node.js",
"language": "javascript",
"file_size": 8113,
"cut_index": 716,
"middle_length": 229
} |
from 'react'
import Link from 'next/link'
import { useCallback, useRef, useEffect, useState } from 'react'
import { flushSync } from 'react-dom'
export default function Page() {
const [isVisible, setIsVisible] = useState(true)
const statusRef = useRef({ wasInitialized: false, wasCleanedUp: false })
const refW... | se)
})
if (!statusRef.current.wasInitialized) {
console.error('callback ref was not initialized')
}
if (!statusRef.current.wasCleanedUp) {
console.error('callback ref was not cleaned up')
}
| f.current.wasInitialized = true
return () => {
statusRef.current.wasCleanedUp = true
}
}, [])
useEffect(() => {
const timeout = setTimeout(
() => {
flushSync(() => {
setIsVisible(fal | {
"filepath": "test/e2e/link-ref-pages/pages/child-ref-func-cleanup.js",
"language": "javascript",
"file_size": 1279,
"cut_index": 524,
"middle_length": 229
} |
/material/SvgIcon'
import Typography from '@mui/material/Typography'
function LightBulbIcon(props) {
return (
<SvgIcon {...props}>
<path d="M9 21c0 .55.45 1 1 1h4c.55 0 1-.45 1-1v-1H9v1zm3-19C8.14 2 5 5.14 5 9c0 2.38 1.19 4.47 3 5.74V17c0 .55.45 1 1 1h6c.55 0 1-.45 1-1v-2.26c1.81-1.27 3-3.36 3-5.74 0-3.86-... | t.secondary">
<LightBulbIcon sx={{ mr: 1, verticalAlign: 'middle' }} />
Pro tip: See more{' '}
<Link href="https://mui.com/getting-started/templates/">
templates
</Link>{' '}
on the MUI documentation.
</Typography> | n (
<Typography sx={{ mt: 6, mb: 3 }} color="tex | {
"filepath": "test/e2e/new-link-behavior/material-ui/src/ProTip.js",
"language": "javascript",
"file_size": 921,
"cut_index": 606,
"middle_length": 52
} |
{ nextTestSetup } from 'e2e-utils'
describe('styled-jsx dynamic styles SSR', () => {
const { next } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
// Dynamic styled-jsx (with interpolated expressions) produces numeric class
// names at runtime via the DJB2 hash in styled-jsx's computeId... | ('Numeric jsx classes:', [...new Set(numericClasses)])
expect(numericClasses.length).toBeGreaterThan(0)
// All dynamic styles should be present as inline <style> tags
expect(html).toMatch(/color:.*?green/) // main page
expect(html).toMatch | c styled-jsx styles during SSR', async () => {
const html = await next.render('/')
// Dynamic styled-jsx produces numeric class names at runtime
const numericClasses = html.match(/\bjsx-\d+\b/g) || []
console.log | {
"filepath": "test/e2e/styled-jsx-dynamic/index.test.ts",
"language": "typescript",
"file_size": 1163,
"cut_index": 518,
"middle_length": 229
} |
ort { nextTestSetup } from 'e2e-utils'
describe('children-page', () => {
const { next } = nextTestSetup({
files: __dirname,
})
describe('with app dir', () => {
it('should show the content if you have a page named children', async () => {
const browser = await next.browser('/children')
const... | const browser = await next.browser('/other/children')
const text = await browser.waitForElementByCss('#children-page').text()
expect(text).toBe('children - pages')
const currentDisplay = await browser.eval(
`window.getComput | (document.querySelector('body')).display`
)
expect(currentDisplay).toBe('block')
})
})
describe('with pages dir', () => {
it('should show the content if you have a page named children', async () => {
| {
"filepath": "test/e2e/children-page/index.test.ts",
"language": "typescript",
"file_size": 1116,
"cut_index": 515,
"middle_length": 229
} |
rt, nextTestSetup } from 'e2e-utils'
let proxyPort: number
const runTests = (
next: ReturnType<typeof nextTestSetup>['next'],
switchDeployment: (bool) => void
) => {
it('index to gsp', async () => {
switchDeployment(false)
const browser = await next.browser('/', { baseUrl: proxyPort })
await browse... | baseUrl: proxyPort })
await browser.eval('window.beforeNav = 1')
await browser.waitForElementByCss('#gsp')
switchDeployment(true)
await browser.eval(`(function() {
window.next.router.push('/gssp')
})()`)
await browser.wait | `)
await browser.waitForElementByCss('#gsp')
expect(await browser.eval('window.beforeNav')).toBeFalsy()
})
it('gsp to gssp', async () => {
switchDeployment(false)
const browser = await next.browser('/gsp', { | {
"filepath": "test/e2e/pages-ssg-data-deployment-skew/pages-ssg-data-deployment-skew.test.ts",
"language": "typescript",
"file_size": 7832,
"cut_index": 716,
"middle_length": 229
} |
Page(props) {
const router = useRouter()
return (
<>
<p id="index">index page</p>
<p id="pathname">{router.pathname}</p>
<p id="query">{JSON.stringify(router.query)}</p>
{router.query.imageId ? <p id="modal">show modal</p> : null}
<Link href="/?imageId=123" as="/preview/123" id=... | her
</Link>
<br />
<Link href="/rewrite-me" id="to-rewrite-me">
go to /rewrite-me
</Link>
<br />
<Link href="/" as="/rewrite-me" id="to-index-as-rewrite">
go to / as /rewrite-me
</Link>
<br | href="/another" id="to-another">
go to /anot | {
"filepath": "test/e2e/rewrites-manual-href-as/pages/index.js",
"language": "javascript",
"file_size": 931,
"cut_index": 606,
"middle_length": 52
} |
Router } from 'next/router'
import Link from 'next/link'
export const getStaticProps = ({ params }) => {
return {
props: {
params: params || null,
preview: true,
},
}
}
export const getStaticPaths = () => {
return {
paths: [],
fallback: 'blocking',
}
}
export default function Page... | w">
go to /preview/321
</Link>
<br />
<Link href="/another" id="to-another">
go to /another
</Link>
<br />
<Link href="/rewrite-me" id="to-rewrite-me">
go to /rewrite-me
</Link>
<br | </p>
<p id="props">{JSON.stringify(props)}</p>
<Link href="/?imageId=123" as="/preview/123" id="to-modal">
open modal for /preview/123
</Link>
<br />
<Link href="/preview/321" id="to-previe | {
"filepath": "test/e2e/rewrites-manual-href-as/pages/preview/[slug].js",
"language": "javascript",
"file_size": 1444,
"cut_index": 524,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
const CASES = [
[
'turbopackPersistentCaching',
"Use 'experimental.turbopackFileSystemCacheForDev' instead.",
],
[
'turbopackPersistentCachingForDev',
"Use 'experimental.turbopackFileSystemCacheForDev' instead.",
],
[
'... | },
skipDeployment: true,
skipStart: true,
})
if (skipped) {
return
}
if (!isTurbopack) {
it.skip('only for turbopack', () => {})
return
}
if (isNextStart) {
it('er | f CASES) {
describe(option, () => {
const { skipped, next, isTurbopack, isNextStart } = nextTestSetup({
files: {
'next.config.js': `module.exports = {
experimental: {
${option}: true,
},
}`,
| {
"filepath": "test/e2e/persistent-caching-migration/persistent-caching-migration.test.ts",
"language": "typescript",
"file_size": 1435,
"cut_index": 524,
"middle_length": 229
} |
mport { nextTestSetup, isNextDev, isNextStart } from 'e2e-utils'
;((isNextDev && process.env.TURBOPACK_BUILD) ||
(isNextStart && process.env.TURBOPACK_DEV)
? describe.skip
: describe)('getInitialProps', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should have gip in __NEXT_DATA__',... | = await next.render$('/blog/1')
expect($('#as-path').text()).toBe('/blog/1')
})
it('should have correct router.asPath for direct visit dynamic page rewrite direct', async () => {
const $ = await next.render$('/blog/post/1')
expect($('#as-p | () => {
const $ = await next.render$('/normal')
expect('gip' in JSON.parse($('#__NEXT_DATA__').text())).toBe(false)
})
it('should have correct router.asPath for direct visit dynamic page', async () => {
const $ | {
"filepath": "test/e2e/getinitialprops/getinitialprops.test.ts",
"language": "typescript",
"file_size": 1041,
"cut_index": 513,
"middle_length": 229
} |
tripAnsi from 'strip-ansi'
const pagePath = 'pages/index.jsx'
const apiPath = 'pages/api/edge.js'
;(process.env.IS_TURBOPACK_TEST ? describe.skip.each : describe.each)([
{ appDir: join(__dirname, './app/src'), title: 'src/pages and API routes' },
{ appDir: join(__dirname, './app'), title: 'pages and API routes' }... | )
afterEach(async () => {
await next.stop()
await next.patchFile(pagePath, originalPage)
await next.patchFile(apiPath, originalApi)
})
it('runs with no warning API route on the edge runtime', async () => {
| kipStart: true,
})
let originalPage: string
let originalApi: string
beforeAll(async () => {
originalPage = await next.readFile(pagePath)
originalApi = await next.readFile(apiPath)
} | {
"filepath": "test/e2e/edge-configurable-runtime/index.test.ts",
"language": "typescript",
"file_size": 4840,
"cut_index": 614,
"middle_length": 229
} |
retry } from 'next-test-utils'
describe('router.isReady', () => {
const { next } = nextTestSetup({
files: __dirname,
})
const checkIsReadyValues = async (browser: any, expected: boolean[] = []) => {
await retry(async () => {
const values = JSON.stringify(
(await browser.eval('window.isRead... | =world')
await checkIsReadyValues(browser, [true])
})
it('isReady should be true immediately for getServerSideProps page', async () => {
const browser = await next.browser('/gssp')
await checkIsReadyValues(browser, [true])
})
it('isRe | wser = await next.browser('/gip')
await checkIsReadyValues(browser, [true])
})
it('isReady should be true immediately for getInitialProps page with query', async () => {
const browser = await next.browser('/gip?hello | {
"filepath": "test/e2e/router-is-ready/router-is-ready.test.ts",
"language": "typescript",
"file_size": 2542,
"cut_index": 563,
"middle_length": 229
} |
from 'e2e-utils'
describe('API body parser', () => {
describe('without custom server', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
// Uses a custom HTTP/proxy server in front of Next.js; not applicable in deploy mode.
skipDeployment: true,
})
if (skipped) return
... | ) => {
const { next, skipped } = nextTestSetup({
files: __dirname,
startCommand: 'node server.js',
serverReadyPattern: /- Local:/,
env: { CUSTOM_SERVER: 'true' },
dependencies: {
express: '4',
},
// Use | -8',
},
body: JSON.stringify([{ title: 'Nextjs' }]),
})
const data = await res.json()
expect(data).toEqual([{ title: 'Nextjs' }])
})
})
describe('with custom server (pre-parsed body)', ( | {
"filepath": "test/e2e/api-body-parser/api-body-parser.test.ts",
"language": "typescript",
"file_size": 1911,
"cut_index": 537,
"middle_length": 229
} |
} from 'next-test-utils'
describe('manual-client-base-path', () => {
if ((global as any).isNextDeploy) {
it('should skip deploy', () => {})
return
}
let server: http.Server
let appPort: string
const basePath = '/docs-proxy'
const responses = new Set()
const { next } = nextTestSetup({
files... | r IPv6 over IPv4
destination.hostname = '127.0.0.1'
if (req.url.startsWith(basePath)) {
destination.pathname = reqUrl.pathname || '/'
} else {
destination.pathname = `${basePath}${
reqUrl.pathname === '/' ? '' : | => {
const getProxyTarget = (req) => {
const destination = new URL(next.url)
const reqUrl = new URL(req.url, 'http://localhost')
// force IPv4 for testing in node 17+ as the default
// switched to favo | {
"filepath": "test/e2e/manual-client-base-path/index.test.ts",
"language": "typescript",
"file_size": 6789,
"cut_index": 716,
"middle_length": 229
} |
import Link from 'next/link'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
export default function Page(props) {
const router = useRouter()
const [mounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
}, [])
return (
<>
<p id="page">an... | </Link>
<br />
<Link href="/dynamic/first" id="to-dynamic">
to /dynamic/first
</Link>
<br />
</>
)
}
export function getServerSideProps() {
return {
props: {
hello: 'world',
now: Date.now(),
}, | pathname: router.pathname,
asPath: router.asPath,
query: router.query,
}
: {}
)}
</p>
<Link href="/" id="to-index">
to /index
| {
"filepath": "test/e2e/manual-client-base-path/app/pages/another.js",
"language": "javascript",
"file_size": 1004,
"cut_index": 512,
"middle_length": 229
} |
mport { useEffect, useState } from 'react'
export default function Page(props) {
const router = useRouter()
const [mounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
}, [])
return (
<>
<p id="page">index page</p>
<p id="props">{JSON.stringify(props)}</p>
<p ... | }
: {}
)}
</p>
<Link href="/another" id="to-another">
to /another
</Link>
<br />
<Link href="/another/" id="to-another-slash">
to /another
</Link>
<br />
<Link href= | ath,
query: router.query,
| {
"filepath": "test/e2e/manual-client-base-path/app/pages/index.js",
"language": "javascript",
"file_size": 991,
"cut_index": 582,
"middle_length": 52
} |
Link from 'next/link'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
export default function Page(props) {
const router = useRouter()
const [mounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
}, [])
return (
<>
<p id="page">dynamic ... | k>
<br />
<Link href="/dynamic/second" id="to-dynamic">
to /dynamic/second
</Link>
<br />
</>
)
}
export function getStaticPaths() {
return {
paths: ['/dynamic/first'],
fallback: true,
}
}
export functio | pathname: router.pathname,
asPath: router.asPath,
query: router.query,
}
: {}
)}
</p>
<Link href="/" id="to-index">
to /index
</Lin | {
"filepath": "test/e2e/manual-client-base-path/app/pages/dynamic/[slug].js",
"language": "javascript",
"file_size": 1130,
"cut_index": 518,
"middle_length": 229
} |
normalize(str: string) {
return str.replace(/<!-- -->/g, '')
}
describe('esm-externals', () => {
const { next, isTurbopack } = nextTestSetup({
files: __dirname,
})
// Pages
describe.each(['/static', '/ssr', '/ssg'])('pages url %s', (url) => {
// For invalid esm packages that have "import" pointing ... | the client side, webpack always bundles, so it uses the non-esm-flagged module too.
const expectedText =
isTurbopack || url === '/static'
? 'Hello World+World+World+World+World+World'
: 'Hello World+World+World+World+World+Altern | = isTurbopack
? 'Hello World+World+World+World+World+World'
: url === '/static'
? 'Hello World+World+Alternative+World+World+World'
: 'Hello World+World+Alternative+World+World+Alternative'
// On | {
"filepath": "test/e2e/esm-externals/esm-externals.test.ts",
"language": "typescript",
"file_size": 2230,
"cut_index": 563,
"middle_length": 229
} |
from 'e2e-utils'
import { renderViaHTTP } from 'next-test-utils'
// Tests Babel, not needed for Turbopack
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'swc warnings by default',
() => {
const { next } = nextTestSetup({
files: {
'pages/index.js': `
export default function... | )
})
}
)
// Tests Babel, not needed for Turbopack
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'can force swc',
() => {
const { next } = nextTestSetup({
nextConfig: {
experimental: {
forceSwcTrans | ies: {},
})
it('should have warning', async () => {
await renderViaHTTP(next.url, '/')
expect(next.cliOutput).toContain(
'Disabled SWC as replacement for Babel because of custom Babel configuration'
| {
"filepath": "test/e2e/swc-warnings/index.test.ts",
"language": "typescript",
"file_size": 1580,
"cut_index": 537,
"middle_length": 229
} |
port { nextTestSetup } from 'e2e-utils'
describe('api-resolver-query-writeable', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
startCommand: 'node server.js',
serverReadyPattern: /Next mode: (production|development)/,
dependencies: {
'get-port': '... | ders: {
'Content-Type': 'application/json; charset=utf-8',
},
})
if (!res.ok) {
throw new Error('Fetch failed')
}
const data = await res.json()
expect(data).toEqual({ query: { hello: 'yes', changed: 'yes' } })
})
} | res = await next.fetch('/api?hello=yes', {
hea | {
"filepath": "test/e2e/api-resolver-query-writeable/api-resolver-query-writeable.test.ts",
"language": "typescript",
"file_size": 824,
"cut_index": 514,
"middle_length": 52
} |
estSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
describe('i18n-data-fetching-redirect', () => {
// TODO: investigate tests failures on deploy
if ((global as any).isNextDeploy) {
it('should skip temporarily', () => {})
return
}
const { next } = nextTestSetup({
files: {
pag... | edirect'} | ${'sv'}
${'gsp-fallback-redirect'} | ${'en'}
${'gsp-fallback-redirect'} | ${'sv'}
`('$path $locale', async ({ path, locale }) => {
const browser = await next.browser(`/${locale}/${path}/from-ctx`)
await check(
| m context', () => {
test.each`
path | locale
${'gssp-redirect'} | ${'en'}
${'gssp-redirect'} | ${'sv'}
${'gsp-blocking-redirect'} | ${'en'}
${'gsp-blocking-r | {
"filepath": "test/e2e/i18n-data-fetching-redirect/redirect-from-context.test.ts",
"language": "typescript",
"file_size": 2392,
"cut_index": 563,
"middle_length": 229
} |
estSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
describe('i18n-data-fetching-redirect', () => {
// TODO: investigate tests failures on deploy
if ((global as any).isNextDeploy) {
it('should skip temporarily', () => {})
return
}
const { next } = nextTestSetup({
files: {
pag... | '} | ${'en'} | ${'sv'}
${'gsp-blocking-redirect'} | ${'sv'} | ${'en'}
${'gsp-fallback-redirect'} | ${'en'} | ${'sv'}
${'gsp-fallback-redirect'} | ${'sv'} | ${'en'}
`(
'$path $fromLocale -> $toLocale',
async ({ | cale', () => {
test.each`
path | fromLocale | toLocale
${'gssp-redirect'} | ${'en'} | ${'sv'}
${'gssp-redirect'} | ${'sv'} | ${'en'}
${'gsp-blocking-redirect | {
"filepath": "test/e2e/i18n-data-fetching-redirect/redirect.test.ts",
"language": "typescript",
"file_size": 2823,
"cut_index": 563,
"middle_length": 229
} |
from 'next/link'
export default function Component() {
return (
<>
<Link href="/gssp-redirect/en" id="to-gssp-redirect-en">
to /gssp-redirect/en"
</Link>
<Link href="/gssp-redirect/sv" id="to-gssp-redirect-sv">
to /gssp-redirect/sv"
</Link>
<Link href="/gssp-redirect... | id="to-gsp-blocking-redirect-from-ctx"
>
to /gsp-blocking-redirect/from-ctx
</Link>
<Link href="/gsp-fallback-redirect/en" id="to-gsp-fallback-redirect-en">
to /gsp-fallback-redirect/en"
</Link>
<Link href="/ | king-redirect/en"
</Link>
<Link href="/gsp-blocking-redirect/sv" id="to-gsp-blocking-redirect-sv">
to /gsp-blocking-redirect/sv"
</Link>
<Link
href="/gsp-blocking-redirect/from-ctx"
| {
"filepath": "test/e2e/i18n-data-fetching-redirect/app/pages/index.js",
"language": "javascript",
"file_size": 1306,
"cut_index": 524,
"middle_length": 229
} |
eslint-disable jest/no-standalone-expect */
import { join } from 'path'
import { check, 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('Midd... | {
const res = await fetchViaHTTP(next.url, path)
expect(res.status).toBe(200)
expect(res.headers.get('x-from-middleware')).toBeDefined()
}
})
it.each(['/default', '/invalid/base/default'])(
'should not match',
async (pat | /middleware-rewrite-of-nextjs-with-basepath-does-not-work-on-vercel
itif(!isModeDeploy)('should match', async () => {
for (const path of [
'/base/default',
`/base/_next/data/${next.buildId}/default.json`,
]) | {
"filepath": "test/e2e/middleware-dynamic-basepath-matcher/test/index.test.ts",
"language": "typescript",
"file_size": 1594,
"cut_index": 537,
"middle_length": 229
} |
sNextStart } from 'e2e-utils'
describe('404 Page Support with _app', () => {
const { next } = nextTestSetup({
files: __dirname,
})
const gip404Err =
/`pages\/404` can not have getInitialProps\/getServerSideProps/
if (isNextStart) {
it('should build successfully', async () => {
expect(next.c... | })
it('specify to use the 404 page still in the routes-manifest', async () => {
const manifest = await next.readJSON('.next/routes-manifest.json')
expect(manifest.pages404).toBe(true)
})
}
it('should still use 404 page', async ( | utput static 404 if _app has getInitialProps', async () => {
const browser = await next.browser('/404')
const isAutoExported = await browser.eval('__NEXT_DATA__.autoExport')
expect(isAutoExported).toBeFalsy()
| {
"filepath": "test/e2e/404-page-app/404-page-app.test.ts",
"language": "typescript",
"file_size": 1550,
"cut_index": 537,
"middle_length": 229
} |
les: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) return
const gip500Err =
/`pages\/500` can not have getInitialProps\/getServerSideProps/
beforeEach(async () => {
// Reset to original 500.js before each test
await next.patchFile(
'pages/500.js',
`const pag... | itCode).toBe(1)
expect(next.cliOutput).toMatch(gip500Err)
})
it('does not show error with getStaticProps in pages/500 build', async () => {
await next.patchFile(
'pages/500.js',
`
const page = () => 'custom 500 page'
ex | t.patchFile(
'pages/500.js',
`
const page = () => 'custom 500 page'
page.getInitialProps = () => ({ a: 'b' })
export default page
`
)
const { exitCode } = await next.build()
expect(ex | {
"filepath": "test/e2e/500-page/500-page-build.test.ts",
"language": "typescript",
"file_size": 10340,
"cut_index": 921,
"middle_length": 229
} |
ls'
describe('500 Page Support', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
it('should use pages/500', async () => {
const html = await next.render('/500')
expect(html).toContain('custom 500 page')
})
it('should set cor... | anifest = await next.readJSON('.next/server/pages-manifest.json')
const page = manifest['/500']
expect(page.endsWith('.html')).toBe(true)
})
it('should add /500 to pages-manifest correctly', async () => {
const manifest = await n | const res = await next.fetch('/500')
expect(res.status).toBe(500)
expect(await res.text()).toContain('custom 500 page')
})
if (isNextStart) {
it('should output 500.html during build', async () => {
const m | {
"filepath": "test/e2e/500-page/500-page.test.ts",
"language": "typescript",
"file_size": 3350,
"cut_index": 614,
"middle_length": 229
} |
{ nextTestSetup } from 'e2e-utils'
import { findAllTelemetryEvents } from 'next-test-utils'
// Turbopack hasn't fully enabled this option yet
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'next-config-warnings - esm-externals-false',
() => {
const { next, isNextStart } = nextTestSetup({
f... | nfig.js`
)
})
if (isNextStart) {
it('should contain esmExternals feature usage in telemetry', async () => {
const featureUsageEvents = findAllTelemetryEvents(
next.cliOutput,
'NEXT_BUILD_FEATURE_USAGE'
| next.cliOutput).toContain(
`The "experimental.esmExternals" option has been modified. experimental.esmExternals is not recommended to be modified as it may disrupt module resolution. It should be removed from your next.co | {
"filepath": "test/e2e/next-config-warnings/esm-externals-false/esm-externals-false.test.ts",
"language": "typescript",
"file_size": 1161,
"cut_index": 518,
"middle_length": 229
} |
ml, selector) {
const $ = cheerio.load(html)
return $(selector)
}
async function resolveStreamResponse(response, onData) {
let result = ''
onData = onData || (() => {})
await new Promise((resolve) => {
response.body.on('data', (chunk) => {
result += chunk.toString()
onData(chunk.toString(), r... | false
await resolveStreamResponse(response, (_, result) => {
gotData = result.includes('next_streaming_data')
if (!gotFallback) {
gotFallback = result.includes('next_streaming_fallback')
if (gotFallback) | t('should support streaming for fizz response', async () => {
async function testStreamingResponse(pathname) {
await next.fetch(pathname).then(async (response) => {
let gotFallback = false
let gotData = | {
"filepath": "test/e2e/streaming-ssr-edge/streaming-ssr-edge.test.ts",
"language": "typescript",
"file_size": 3456,
"cut_index": 614,
"middle_length": 229
} |
port { nextTestSetup } from 'e2e-utils'
describe('turbopack-loader-config', () => {
const { next, isTurbopack, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
// we can't set `nextConfig` inline because it contains regexes that fail to serialize, it needs
// to be set i... | h their loader-generated versions', async () => {
const response = JSON.parse(await next.render('/api'))
expect(response).toEqual({
foo: 'default return value',
bar: 'has export substring' + (isNextDev ? ' on dev' : ' on prod'),
})
| ce modules wit | {
"filepath": "test/e2e/turbopack-loader-config/index.test.ts",
"language": "typescript",
"file_size": 792,
"cut_index": 514,
"middle_length": 14
} |
ack: {
rules: {
// an empty condition should match
'foo.js': {
condition: {},
// use the shorthand syntax
loaders: ['./webpack-loader-replace-with-stub.cjs'],
},
'bar.js': [
// this condition should not match
{
condition: 'foreign',
... | options: { returnValue: 'missing export' },
},
],
},
// this should match on dev
{
condition: {
any: [
{
all: [
'development',
| his condition should not match
{
condition: {
not: { content: /export/ },
},
loaders: [
{
loader: './webpack-loader-replace-with-stub.cjs',
| {
"filepath": "test/e2e/turbopack-loader-config/next.config.ts",
"language": "typescript",
"file_size": 1809,
"cut_index": 537,
"middle_length": 229
} |
retry } from 'next-test-utils'
describe('Custom routes i18n custom error', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
// Assertions don't apply to deploy mode (output differs vs. local Next.js server).
skipDeployment: true,
})
if (skipped) return
const locales = ['en', 'fr... | stom-path-1',
})
}
})
it('handle custom http status maintaining locale props in custom _error page', async () => {
for (const locale of locales) {
const browser = await next.browser(
`${locale === 'en' ? '' : `/${locale}`}/ | '' : `/${locale}`}/my-custom-path-1`
)
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale,
params: {
slug: 'my-custom-path-1',
},
title: 'my-cu | {
"filepath": "test/e2e/i18n-support-custom-error/i18n-support-custom-error.test.ts",
"language": "typescript",
"file_size": 2897,
"cut_index": 563,
"middle_length": 229
} |
useRouter } from 'next/router'
const SlugPage = (props) => {
const router = useRouter()
return router.isFallback ? null : (
<>
<div>{props.title}</div>
<div id="props">{JSON.stringify(props)}</div>
</>
)
}
export const getStaticProps = async ({ locale, params }) => {
if (params.slug === ... | om-path-1', 'my-custom-path-2']
return {
paths: locales.reduce(
(paths, locale) => [
...paths,
...mySlugs.map((slug) => ({ locale, params: { slug } })),
],
[]
),
fallback: 'blocking',
}
}
export default S | async ({ locales }) => {
const mySlugs = ['my-cust | {
"filepath": "test/e2e/i18n-support-custom-error/pages/[slug].js",
"language": "javascript",
"file_size": 836,
"cut_index": 520,
"middle_length": 52
} |
res1 = await next.fetch('/api/proxy-self')
expect(res1.status).toBe(200)
expect(await res1.text()).toContain('User')
const buildId = isNextDev
? 'development'
: await next.readFile('.next/BUILD_ID')
const res2 = await next.fetch(`/api/proxy-self?buildId=${buildId}`)
expect(res2.status)... | tus-204', { redirect: 'manual' })
expect(res.status).toBe(204)
expect(res.headers.get('content-type')).toBe(null)
expect(res.headers.get('content-length')).toBe(null)
expect(res.headers.get('transfer-encoding')).toBe(null)
const cliOut | th/signin', { redirect: 'manual' })
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ from: 'auth' })
})
it('should handle 204 status correctly', async () => {
const res = await next.fetch('/api/sta | {
"filepath": "test/e2e/api-support/api-support.test.ts",
"language": "typescript",
"file_size": 18681,
"cut_index": 1331,
"middle_length": 229
} |
it for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function initMiddleware(middleware) {
return (req, res) =>
new Promise((resolve, reject) => {
middleware(req, res, (result) => {
if (result instanceof Error) {
return reject(resu... | rs({
// Only allow requests with GET, POST and OPTIONS
methods: ['GET', 'POST', 'OPTIONS'],
})
)
export default async function handler(req, res) {
// Run cors
await cors(req, res)
// Rest of the API logic
res.json({ message: 'Hello Ever | github.com/expressjs/cors#configuration-options
Co | {
"filepath": "test/e2e/api-support/pages/api/cors.js",
"language": "javascript",
"file_size": 879,
"cut_index": 559,
"middle_length": 52
} |
{ nextTestSetup } from 'e2e-utils'
describe('invalid-static-asset-404-app-asset-prefix', () => {
const { next } = nextTestSetup({
files: __dirname,
nextConfig: {
assetPrefix: '/assets',
},
})
it('should return correct output with status 200 on valid asset path', async () => {
const buildM... | 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('/assets/_next/static/ | onst 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')
expe | {
"filepath": "test/e2e/invalid-static-asset-404-app/invalid-static-asset-404-app-asset-prefix.test.ts",
"language": "typescript",
"file_size": 1128,
"cut_index": 518,
"middle_length": 229
} |
ort { nextTestSetup } from 'e2e-utils'
describe('invalid-static-asset-404-app-base-path', () => {
const { next } = nextTestSetup({
files: __dirname,
nextConfig: {
basePath: '/base',
},
})
it('should return correct output with status 200 on valid asset path', async () => {
const buildManife... | (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/inva | xt = 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')
expect | {
"filepath": "test/e2e/invalid-static-asset-404-app/invalid-static-asset-404-app-base-path.test.ts",
"language": "typescript",
"file_size": 1121,
"cut_index": 515,
"middle_length": 229
} |
fetchViaHTTP } from 'next-test-utils'
describe('edge api can use async local storage', () => {
const { next } = nextTestSetup({
files: __dirname,
})
const cases = [
{
title: 'a single instance',
route: '/api/single',
expectResponse: (response: any, id: string) =>
expect(respons... | const ids = Array.from({ length: 100 }, (_, i) => `req-${i}`)
const responses = await Promise.all(
ids.map((id) =>
fetchViaHTTP(next.url, route, {}, { headers: { 'req-id': id } }).then(
(response) =>
res | ct(response).toMatchObject({
status: 200,
json: { id: id, nestedId: `nested-${id}` },
}),
},
]
it.each(cases)(
'can use $title per request',
async ({ route, expectResponse }) => {
| {
"filepath": "test/e2e/edge-async-local-storage/index.test.ts",
"language": "typescript",
"file_size": 2065,
"cut_index": 563,
"middle_length": 229
} |
(e. g. 'eval', 'new Function') not allowed in Edge Runtime`
const DYNAMIC_CODE_ERROR = `Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime`
const WASM_COMPILE_ERROR = `Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime`
const WA... | nextTestSetup({
files: __dirname,
})
it('does not issue dynamic code evaluation warnings', async () => {
const outputIndex = next.cliOutput.length
const html = await next.render('/')
expect(html).toMatch(/>.*?100.*?and.*?100.*?<\//)
| Awaited<
ReturnType<ReturnType<typeof nextTestSetup>['next']['fetch']>
>
describe('Page using eval in development mode', () => {
if (!isNextDev) {
it('only runs in dev mode', () => {})
return
}
const { next } = | {
"filepath": "test/e2e/edge-runtime-dynamic-code/edge-runtime-dynamic-code.test.ts",
"language": "typescript",
"file_size": 5528,
"cut_index": 716,
"middle_length": 229
} |
/ (type (;0;) (func (param i32) (result i32)))
// (func (;0;) (type 0) (param i32) (result i32)
// local.get 0
// local.get 0
// i32.mul)
// (table (;0;) 0 funcref)
// (memory (;0;) 1)
// (export "memory" (memory 0))
// (export "square" (func 0)))
const SQUARE_WASM_BUFFER = new Uint8Array([
0x... | quare.wasm?module'
export async function usingWebAssemblyCompile(x) {
const module = await WebAssembly.compile(SQUARE_WASM_BUFFER)
const instance = await WebAssembly.instantiate(module, {})
return { value: instance.exports.square(x) }
}
export asyn | , 0x13, 0x02, 0x06, 0x6d, 0x65, 0x6d, 0x6f,
0x72, 0x79, 0x02, 0x00, 0x06, 0x73, 0x71, 0x75, 0x61, 0x72, 0x65, 0x00, 0x00,
0x0a, 0x09, 0x01, 0x07, 0x00, 0x20, 0x00, 0x20, 0x00, 0x6c, 0x0b,
])
import squareWasmModule from './s | {
"filepath": "test/e2e/edge-runtime-dynamic-code/lib/wasm.js",
"language": "javascript",
"file_size": 1361,
"cut_index": 524,
"middle_length": 229
} |
usingWebAssemblyInstantiate,
usingWebAssemblyInstantiateWithBuffer,
} from '../../lib/wasm'
export default async function handler(request) {
const useCase = request.nextUrl.searchParams.get('case')
if (useCase === 'using-eval') {
return Response.json(await usingEval())
}
if (useCase === 'not-using-ev... | .json(await usingWebAssemblyInstantiate(9))
}
if (useCase === 'using-webassembly-instantiate-with-buffer') {
return Response.json(await usingWebAssemblyInstantiateWithBuffer(9))
}
return Response.json({ ok: true })
}
export const config = { | sing-webassembly-instantiate') {
return Response | {
"filepath": "test/e2e/edge-runtime-dynamic-code/pages/api/route.js",
"language": "javascript",
"file_size": 932,
"cut_index": 606,
"middle_length": 52
} |
- partytown-missing', () => {
const { next, isNextDev } = nextTestSetup({
files: join(__dirname, 'partytown-missing'),
skipStart: true,
// Vercel deployment fails to build/deploy this fixture in CI; skip in deploy mode.
skipDeployment: true,
})
it('Error message is shown if Partytown is not inst... | he required package\(s\) installed.Please install Partytown by running:.*?(npm|pnpm|yarn) (install|add) (--save-dev|--dev) @builder\.io\/partytownIf you are not trying to use Partytown, please disable the experimental "nextScriptWorkers" flag in next\.conf | to use Partytown with next\/script but do not have t | {
"filepath": "test/e2e/script-loader/partytown-missing.test.ts",
"language": "typescript",
"file_size": 938,
"cut_index": 606,
"middle_length": 52
} |
mport * as React from 'react'
import { Main, NextScript, Head, Html } from 'next/document'
import Script from 'next/script'
export default function Document() {
return (
<Html>
<Head>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Voces"
/>
... | ></Script>
</Head>
<body>
<Main />
<NextScript />
<Script
src="https://www.google-analytics.com/analytics.js?a=scriptBeforeInteractive"
strategy="beforeInteractive"
></Script>
<div i | ctive"
></Script>
<Script
id="inline-before"
strategy="beforeInteractive"
dangerouslySetInnerHTML={{
__html: `console.log('inline beforeInteractive')`,
}}
| {
"filepath": "test/e2e/script-loader/pages/_document.js",
"language": "javascript",
"file_size": 1042,
"cut_index": 513,
"middle_length": 229
} |
/* global _ */
import Script from 'next/script'
import Link from 'next/link'
const url =
'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js'
const Page = () => {
return (
<div class="container">
<div id="onload-div-1">initial</div>
<Link href="/page9">Page 9</Link>
<Scri... | ></Script>
<Script
src={url}
id="script3"
onLoad={() => {
document.getElementById('onload-div-1').textContent += _.repeat(
'c',
3
)
}}
></Script>
</div>
)
}
e | }}
></Script>
<Script
src={url}
id="script2"
onLoad={() => {
document.getElementById('onload-div-1').textContent += _.repeat(
'b',
3
)
}}
| {
"filepath": "test/e2e/script-loader/pages/page4.js",
"language": "javascript",
"file_size": 1016,
"cut_index": 512,
"middle_length": 229
} |
llow manual href/as on index page', async () => {
const browser = await next.browser('/')
expect(await browser.elementByCss('#index').text()).toBe('index page')
expect(await browser.hasElementByCssSelector('#modal')).toBeFalsy()
await browser.eval('window.beforeNav = 1')
await browser.elementByCss... | lementByCss('#preview')
expect(await browser.elementByCss('#preview').text()).toBe('preview page')
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual({
slug: '12 | ser.eval('window.beforeNav')).toBe(1)
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual({
imageId: '123',
})
await browser
.elementByCss('#to-preview')
.click()
.waitForE | {
"filepath": "test/e2e/rewrites-manual-href-as/rewrites-manual-href-as.test.ts",
"language": "typescript",
"file_size": 5170,
"cut_index": 716,
"middle_length": 229
} |
'react'
import FourDirect from '../components/four'
const One = dynamic(() => import('../components/one'))
const Two = dynamic(() => import('../components/two'))
const Three = dynamic(() => import('../components/three'))
const Four = dynamic(() => import('../components/four'))
if (typeof window !== 'undefined') {
... | the-server-value')
useEffect(() => {
setFirstRender(document.getElementById('foo').innerHTML)
}, [])
return (
<>
<div id="foo">
Index
<One />
<Two />
<Three />
<Four />
<FourDirect />
| {
const [firstRender, setFirstRender] = useState(' | {
"filepath": "test/e2e/next-dynamic/pages/index.js",
"language": "javascript",
"file_size": 963,
"cut_index": 582,
"middle_length": 52
} |
avigateProps {
children: React.ReactNode
rootPath: string
}
export default function OnNavigate({ children, rootPath }: OnNavigateProps) {
const [isClicked, setIsClicked] = useState(false)
const [isNavigated, setIsNavigated] = useState(false)
const [isLocked, setIsLocked] = useState(false)
return (
<di... | ton>
<div>
<Link
href={rootPath}
id="link-to-main"
onClick={() => setIsClicked(true)}
onNavigate={(e: any) => {
if (isLocked) {
e.preventDefault()
| : 'false'}</p>
<p id="is-locked">isLocked: {isLocked ? 'true' : 'false'}</p>
</div>
<button id="toggle-lock" onClick={() => setIsLocked(!isLocked)}>
{isLocked ? 'Unlock' : 'Lock'}
</but | {
"filepath": "test/e2e/link-on-navigate-prop/shared/OnNavigate.tsx",
"language": "tsx",
"file_size": 3069,
"cut_index": 614,
"middle_length": 229
} |
ort { FileRef, nextTestSetup } from 'e2e-utils'
import { fetchViaHTTP } from 'next-test-utils'
import path from 'path'
describe('Edge API endpoints can receive body', () => {
const { next } = nextTestSetup({
files: {
'pages/api/edge.js': new FileRef(
path.resolve(__dirname, './app/pages/api/edge.js... | ).toBe('got: hello, world.')
})
it('reads the body from index', async () => {
const res = await fetchViaHTTP(
next.url,
'/api',
{},
{
body: 'hello, world.',
method: 'POST',
}
)
expect(res.stat | c () => {
const res = await fetchViaHTTP(
next.url,
'/api/edge',
{},
{
body: 'hello, world.',
method: 'POST',
}
)
expect(res.status).toBe(200)
expect(await res.text() | {
"filepath": "test/e2e/edge-api-endpoints-can-receive-body/index.test.ts",
"language": "typescript",
"file_size": 1078,
"cut_index": 515,
"middle_length": 229
} |
ow pending state for the last link clicked when clicking multiple links in a row', async () => {
const browser = await next.browser('/')
// Click post 1 link
await browser.elementById('post-1-link').click()
// Quickly click post 2 link
await browser.elementById('post-2-link').click()
// The p... | Css('[data-testid="post-2-page"]')
})
it('should remove pending state after shallow routing', async () => {
const browser = await next.browser('/')
// Click post 1 link
await browser.elementById('post-1-link').click()
// Verify pendi | ait browser.elementsByCss('#post-1-loading')
expect(post1Loading.length).toBe(0)
// Wait for navigation to complete and verify we end up on post 2
await browser.waitForIdleNetwork()
await browser.waitForElementBy | {
"filepath": "test/e2e/use-link-status/index.test.ts",
"language": "typescript",
"file_size": 5418,
"cut_index": 716,
"middle_length": 229
} |
xt/link'
import { navigateByServerAction } from './server-action'
import { useRouter } from 'next/navigation'
export default function NavBar() {
const postIds = Array.from({ length: 5 }, (_, i) => i + 1)
const router = useRouter()
return (
<nav data-testid="navbar">
<ul style={{ display: 'flex', listS... | >
Navigate by server action to home
</button>
</li>
{postIds.map((id) => (
<li key={id}>
<Link
prefetch={false}
href={`/post/${id}`}
id={`post-${id}-lin | Home <LoadingIndicator id="home" />
</Link>
<button
id="server-action-home-btn"
data-testid="server-action-home-btn"
onClick={() => navigateByServerAction(`/`)}
| {
"filepath": "test/e2e/use-link-status/app/nav-bar.tsx",
"language": "tsx",
"file_size": 3323,
"cut_index": 614,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
describe('Route index handling', () => {
const { next } = nextTestSetup({
files: __dirname,
// Pages-router `/index` route resolution differs in Vercel's deploy
// infrastructure; these assertions are local-only.
skipDeployment: true,
})
it('should handle / correctl... | st res = await next.fetch('/index/index')
expect(res.status).toBe(404)
expect(await res.text()).toContain('page could not be found')
})
it('should handle /index/?bar%60%3C%25%22%27%7B%24%2A%25%5C correctly', async () => {
const res = await | ectly', async () => {
const res = await next.fetch('/index')
expect(res.status).toBe(200)
expect(await res.text()).toContain('hello from index')
})
it('should handle /index/index correctly', async () => {
con | {
"filepath": "test/e2e/route-index/route-index.test.ts",
"language": "typescript",
"file_size": 1264,
"cut_index": 524,
"middle_length": 229
} |
= nextTestSetup({
files: __dirname,
// Pages-router `/index` route resolution differs in Vercel's deploy
// infrastructure; these assertions are local-only.
skipDeployment: true,
})
it('should handle / correctly', async () => {
const res = await next.fetch('/')
expect(res.status).toBe(200)... | ait res.text()).toContain('page could not be found')
})
it('should handle /nested-index correctly', async () => {
const res = await next.fetch('/nested-index')
expect(res.status).toBe(404)
expect(await res.text()).toContain('page could not | 4)
expect(await res.text()).toContain('page could not be found')
})
it('should handle /index/index correctly', async () => {
const res = await next.fetch('/index/index')
expect(res.status).toBe(404)
expect(aw | {
"filepath": "test/e2e/route-indexes/route-indexes.test.ts",
"language": "typescript",
"file_size": 3716,
"cut_index": 614,
"middle_length": 229
} |
from 'e2e-utils'
const jsContent = `export const nope = 'nope'
throw new Error('please dont execute me')
`
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'turbopack-import-with-type',
() => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
... | },
jsAsText: {
typeofString: true,
content: jsContent,
},
bytes: {
instanceofUint8Array: true,
length: 18,
content: 'this is some data\n',
},
jsAsBytes: {
| and type: json', async () => {
const response = JSON.parse(await next.render('/api'))
expect(response).toEqual({
text: {
typeofString: true,
length: 12,
content: 'hello world\n',
| {
"filepath": "test/e2e/turbopack-import-with-type/index.test.ts",
"language": "typescript",
"file_size": 1521,
"cut_index": 537,
"middle_length": 229
} |
th'
import { nextTestSetup } from 'e2e-utils'
describe('Optimized loading', () => {
const { next } = nextTestSetup({
files: join(__dirname, '../'),
})
function runTests(url) {
describe('page ' + url, () => {
it(`should render the page ${url}`, async () => {
const html = await next.render(u... | scripts with defer in head', async () => {
const $ = await next.render$(url)
expect($('script[async]').length).toBe(0)
expect($('head script[defer]').length).toBeGreaterThan(0)
})
})
}
runTests('/')
runTests('/page | d]').length).toBe(0)
})
it('should load | {
"filepath": "test/e2e/optimized-loading/test/index.test.ts",
"language": "typescript",
"file_size": 874,
"cut_index": 559,
"middle_length": 52
} |
from 'e2e-utils'
import { listClientChunks, retry } from 'next-test-utils'
import fs from 'fs'
import path from 'path'
describe('swc-auto-polyfill', () => {
const { next, isNextDev, isNextDeploy } = nextTestSetup({
files: __dirname,
dependencies: {
'core-js': '3.38.1',
},
})
it('should render ... | ath.join(next.testDir, next.distDir))
).filter((f) => f.endsWith('.js'))
// Find a chunk that contains BOTH the user code (a-b-c / a_b_c) AND
// core-js polyfill artifacts. This proves SWC's usage-mode polyfill
// injection is work | .text()
expect(text).toBe('a_b_c')
})
})
if (!isNextDev && !isNextDeploy) {
it('should include core-js polyfill in a chunk with user code', async () => {
const jsFiles = (
await listClientChunks(p | {
"filepath": "test/e2e/swc-auto-polyfill/swc-auto-polyfill.test.ts",
"language": "typescript",
"file_size": 1670,
"cut_index": 537,
"middle_length": 229
} |
from 'e2e-utils'
describe('edge-runtime uses edge-light import specifier for packages', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
packageJson: {
scripts: {
build: 'next build',
dev: 'next dev',
start: 'next start',
},
},
installCommand: 'p... | t is only supported in `exports` and `imports` but webpack also adds the top level `edge-light` key incorrectly.
edgeLightPackage: process.env.IS_TURBOPACK_TEST ? 'import' : 'edge-light',
edgeLightPackageExports: 'edge-light',
})
})
it | ou need to test the response object
it('pages/api endpoints import the correct module', async () => {
const res = await next.fetch('/api/edge')
const html = await res.json()
expect(html).toEqual({
// edge-ligh | {
"filepath": "test/e2e/edge-runtime-uses-edge-light-import-specifier-for-packages/edge-runtime-uses-edge-light-import-specifier-for-packages.test.ts",
"language": "typescript",
"file_size": 1912,
"cut_index": 537,
"middle_length": 229
} |
// TODO: We will refactor the next/script to be strict mode resilient
// Don't skip the test case for development mode (strict mode) once refactoring is finished
it('priority afterInteractive', async () => {
const browser = await next.browser('/')
async function test(scriptID: string) {
await retry... | active script in page
await test('scriptAfterInteractive')
// afterInteractive script in _document
await test('documentAfterInteractive')
})
it('priority lazyOnload', async () => {
const browser = await next.browser('/page3')
awai | er.elementsByCss(
`#__NEXT_DATA__ ~ script#${scriptID}`
)
expect(script).toBeDefined()
expect(dataAttr).toBeDefined()
expect(endScripts.length).toBe(1)
})
}
// afterInter | {
"filepath": "test/e2e/script-loader/script-loader.test.ts",
"language": "typescript",
"file_size": 8251,
"cut_index": 716,
"middle_length": 229
} |
from 'e2e-utils'
import { createServer, Server } from 'http'
describe('node-fetch-keep-alive', () => {
let mockServer: Server
const { next, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
// Vercel deployment fails to build/deploy this fixture in CI; skip in deploy mode.
skipDeploym... | const res = await next.fetch('/api/json')
const obj = await res.json()
expect(obj).toEqual({ connection: 'keep-alive' })
})
it('should send keep-alive for getStaticProps', async () => {
const browser = await next.browser('/ssg')
const | n }))
})
await new Promise<void>((resolve) => mockServer.listen(44001, resolve))
await next.start()
})
afterAll(() => {
mockServer?.close()
})
it('should send keep-alive for json API', async () => {
| {
"filepath": "test/e2e/node-fetch-keep-alive/node-fetch-keep-alive.test.ts",
"language": "typescript",
"file_size": 1698,
"cut_index": 537,
"middle_length": 229
} |
/app-router' },
{ name: 'Pages Router', path: '/pages-router' },
]
routers.forEach(({ name, path }) => {
describe(name, () => {
it('should trigger onClick but not onNavigate when using modifier key', async () => {
const browser = await next.browser(path)
// Check initial state
... | down the modifier key
await browser.keydown(modifierKey)
// Click the link while the modifier key is pressed
await browser.elementById('link-to-subpage').click()
// Release the modifier key
await browser.keyup(modi | ted: false'
)
// Click with modifier key based on OS to open in new window
const platform = process.platform
const modifierKey = platform === 'darwin' ? 'Meta' : 'Control'
// First press | {
"filepath": "test/e2e/link-on-navigate-prop/index.test.ts",
"language": "typescript",
"file_size": 6195,
"cut_index": 716,
"middle_length": 229
} |
import { nextTestSetup } from 'e2e-utils'
describe('rewrites persist with browser history actions', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
react: '19.3.0-canary-fef12a01-20260413',
'react-dom': '19.3.0-canary-fef12a01-20260413',
},
// Vercel deployment ... | click()
.waitForElementByCss('#index')
await browser.back().waitForElementByCss('#another')
expect(await browser.waitForElementByCss('#another').text()).toBe(
'another page'
)
expect(await browser.eval('window.beforeNav')).to | = await next.browser('/rewrite-me/path')
expect(await browser.elementByCss('#another').text()).toBe('another page')
await browser.eval('window.beforeNav = 1')
await browser
.elementByCss('#to-index')
. | {
"filepath": "test/e2e/rewrite-with-browser-history/rewrite-with-browser-history.test.ts",
"language": "typescript",
"file_size": 1011,
"cut_index": 512,
"middle_length": 229
} |
import * as path from 'path'
import { nextTestSetup, type NextInstance } from 'e2e-utils'
import { File } from 'next-test-utils'
import * as JSON5 from 'json5'
function runTests(next: NextInstance) {
describe('default behavior', () => {
it('should alias components', async () => {
const $ = await next.rende... | ).toMatch(/Hello from only b/)
})
it('should resolve a single matching alias', async () => {
const $ = await next.render$('/single-alias')
expect($('body').text()).toMatch(/Hello/)
})
it('should not resolve to .d.ts files', as | -order')
expect($('body').text()).toMatch(/Hello from a/)
})
it('should resolve the second item in as a fallback', async () => {
const $ = await next.render$('/resolve-fallback')
expect($('body').text() | {
"filepath": "test/e2e/typescript-paths/test/index.test.ts",
"language": "typescript",
"file_size": 2418,
"cut_index": 563,
"middle_length": 229
} |
o'
import { nextTestSetup, isNextDev } from 'e2e-utils'
import { findPort } from 'next-test-utils'
describe('Fetch polyfill', () => {
let apiServerPort: number
let apiServer: http.Server
const { next, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
dependencies: {
react: '19.3.0... | { usernames: ['a', 'b'] }))
}
if (req.url === '/usernames/a') {
return res.end(JSON.stringify({ from: 'a' }))
}
if (req.url === '/usernames/b') {
return res.end(JSON.stringify({ from: 'b' }))
}
res.end(JS | ent: true,
})
if (skipped) return
beforeAll(async () => {
apiServerPort = await findPort()
apiServer = http.createServer((req, res) => {
if (req.url === '/usernames') {
return res.end(JSON.stringify( | {
"filepath": "test/e2e/fetch-polyfill/fetch-polyfill.test.ts",
"language": "typescript",
"file_size": 2443,
"cut_index": 563,
"middle_length": 229
} |
tResponse } from 'next/server'
import { notUsingEval, usingEval } from './lib/utils'
import {
usingWebAssemblyCompile,
usingWebAssemblyInstantiate,
usingWebAssemblyInstantiateWithBuffer,
} from './lib/wasm'
export async function middleware(request) {
if (request.nextUrl.pathname === '/using-eval') {
return... | le(9)) },
})
}
if (request.nextUrl.pathname === '/using-webassembly-instantiate') {
return new Response(null, {
headers: { data: JSON.stringify(await usingWebAssemblyInstantiate(9)) },
})
}
if (
request.nextUrl.pathname === | ers: { data: JSON.stringify(await notUsingEval()) },
})
}
if (request.nextUrl.pathname === '/using-webassembly-compile') {
return new Response(null, {
headers: { data: JSON.stringify(await usingWebAssemblyCompi | {
"filepath": "test/e2e/edge-runtime-dynamic-code/middleware.js",
"language": "javascript",
"file_size": 1448,
"cut_index": 524,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.