prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
import { createSandbox } from 'development-sandbox' import path from 'path' jest.setTimeout(240 * 1000) describe('Error overlay - RSC build errors', () => { const { next } = nextTestSetup({ files: new FileRef(path.join(__dirname, 'fixtures', 'app-hmr-changes')), dependencies: { '@next/mdx': 'canary', ...
S_TURBOPACK_TEST ? describe : describe.skip)( 'Skipped in webpack', () => { it('should handle successive HMR changes with errors correctly', async () => { await using sandbox = await createSandbox( next, undefined,
, '@types/react-dom': '^18.0.10', 'image-size': '^1.0.2', autoprefixer: '^10.4.13', }, skipStart: true, }) // TODO: The error overlay is not closed when restoring the working code. ;(process.env.I
{ "filepath": "test/development/acceptance-app/app-hmr-changes.test.ts", "language": "typescript", "file_size": 2166, "cut_index": 563, "middle_length": 229 }
ent } from 'outdent' async function clickSourceFile(browser: Playwright) { await browser.waitForElementByCss( '[data-with-open-in-editor-link-source-file]' ) await browser .elementByCss('[data-with-open-in-editor-link-source-file]') .click() } async function clickImportTraceFiles(browser: Playwright...
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')), skipStart: true, }) it('should be possible to open source file on build error', async () => { let editorRequestsCount = 0 await using sandbox = await createSandbox(
ink-import-trace]' ) for (const collapsedFrameworkButton of collapsedFrameworkGroups) { await collapsedFrameworkButton.click() } } describe('Error overlay - editor links', () => { const { next } = nextTestSetup({
{ "filepath": "test/development/acceptance-app/editor-links.test.ts", "language": "typescript", "file_size": 5156, "cut_index": 716, "middle_length": 229 }
rement = useCallback(() => setCount(c => c + 1), [setCount]) return ( <main> <p>{count}</p> <button onClick={increment}>Increment</button> </main> ) } ` ) await browser.elementByCss('button').click() expect( await s...
> 1 | export default () => <div/ | ^", "stack": [], } `) } else if (isRspack) { await expect({ browser, next }).toDisplayRedbox(` { "description": " ╰─▶ × Error: x
wser).toDisplayRedbox(` { "description": "Expected '>', got '<eof>'", "environmentLabel": null, "label": "Build Error", "source": "./index.js (1:27) Expected '>', got '<eof>'
{ "filepath": "test/development/acceptance-app/error-recovery.test.ts", "language": "typescript", "file_size": 32665, "cut_index": 1331, "middle_length": 229 }
nt-only': 'latest', }, skipStart: true, }) it('should show error when using styled-jsx in server component', async () => { await using sandbox = await createSandbox( next, new Map([ [ 'app/comp1.js', outdent` import { Comp2 } from './comp2' ...
} `, ], [ 'app/page.js', outdent` 'use client' import { Comp1 } from './comp1' export default function Page() { return <Comp1 /> }
return ( <div> <style jsx>{\` p { color: red; } \`}</style> </div> )
{ "filepath": "test/development/acceptance-app/invalid-imports.test.ts", "language": "typescript", "file_size": 12089, "cut_index": 921, "middle_length": 229 }
tdent' import { FileRef, nextTestSetup } from 'e2e-utils' describe('Error overlay - RSC runtime errors', () => { const { next } = nextTestSetup({ files: new FileRef(path.join(__dirname, 'fixtures', 'rsc-runtime-errors')), }) it('should show runtime errors if invalid client API from node_modules is executed'...
se client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/react-client-hook-in-server-component", "environmentLabel": "Server", "label": "Runtime TypeError", "source": "app/server/page.js (3:16)
entApi() return 'page' } ` ) const browser = await next.browser('/server') await expect(browser).toDisplayRedbox(` { "description": "useState only works in Client Components. Add the "u
{ "filepath": "test/development/acceptance-app/rsc-runtime-errors.test.ts", "language": "typescript", "file_size": 2804, "cut_index": 563, "middle_length": 229 }
tup, type Playwright } from 'e2e-utils' import path from 'path' import { outdent } from 'outdent' function getStaleness(browser: Playwright) { return browser .waitForElementByCss('.nextjs-container-build-error-version-status') .text() } describe('Error Overlay version staleness', () => { const { next } = ...
next, new Map([ ['node_modules/next/package.json', JSON.stringify(nextPackageJson)], ]) ) const { session, browser } = sandbox await session.patch( 'app/page.js', outdent` "use client" import C
// Set next to outdated version const nextPackageJson = JSON.parse( await next.readFile('node_modules/next/package.json') ) nextPackageJson.version = '1.0.0' await using sandbox = await createSandbox(
{ "filepath": "test/development/acceptance-app/version-staleness.test.ts", "language": "typescript", "file_size": 4027, "cut_index": 614, "middle_length": 229 }
import sizeOf from 'image-size' import { join } from 'path' import { readFile } from 'fs/promises' import NextImage from 'next/image' export async function Image({ src, alt = null, width = null, height = null }) { if (!src.startsWith('data:') && (width === null || height === null)) { let imageBuffer = null ...
tartsWith('data:') ? ( <img src={src} alt={alt} /> ) : ( <NextImage width={width} height={height} alt={alt} src={src} /> )} {alt && ( <span className="block font-mono text-xs mt-5 text-center">{alt}</span> )
L(join(import.meta.url, '..', '..', '..', '..', 'public', src)) .pathname ) } ;({ width, height } = sizeOf(imageBuffer)) } return ( <span className="my-5 flex flex-col items-center"> {src.s
{ "filepath": "test/development/acceptance-app/fixtures/app-hmr-changes/app/(post)/components/image.tsx", "language": "tsx", "file_size": 1017, "cut_index": 512, "middle_length": 229 }
mport type { ReactNode } from 'react' import { Tweet as ReactTweet, TweetComponents } from 'react-tweet' import Image from 'next/image' import { Caption } from './caption' const components: TweetComponents = { AvatarImg: (props) => <Image {...props} />, MediaImg: (props) => <Image {...props} fill unoptimized />, ...
function Tweet({ id, caption }: TweetArgs) { return ( <div className="my-6"> <div className="flex justify-center"> <ReactTweet id={id} components={components} /> </div> {caption && <Caption>{caption}</Caption>} </div>
export async
{ "filepath": "test/development/acceptance-app/fixtures/app-hmr-changes/app/(post)/components/tweet.tsx", "language": "tsx", "file_size": 787, "cut_index": 513, "middle_length": 14 }
t { createSandbox } from 'development-sandbox' import { FileRef, nextTestSetup } from 'e2e-utils' import { retry } from 'next-test-utils' describe('dynamic metadata error', () => { const { next } = nextTestSetup({ files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')), skipStart: true, })...
{ contentType: 'image/png', size: { width: 48, height: 48 }, id: 101, }, ] } export default function icon() { return new ImageResponse(<div>icon</div>) } ` await using _sandbox = awai
ImageResponse } from 'next/og' export async function generateImageMetadata() { return [ { contentType: 'image/png', size: { width: 48, height: 48 }, // id: 100, },
{ "filepath": "test/development/acceptance-app/dynamic-metadata-error.test.ts", "language": "typescript", "file_size": 2758, "cut_index": 563, "middle_length": 229 }
<Next.js Internal Component> <Next.js Internal Component> <Next.js Internal Component> <Next.js Internal Component> <Mismatch params={Promise} searchParams={Promise}> <d...
n if a SSR-ed Client Component used:", "environmentLabel": null, "label": "Recoverable Error", "source": "app/(default)/text-mismatch/page.tsx (8:7) @ Mismatch > 8 | <main className="child">{isClient ? 'client' : 'server'}<
... ... ...", "description": "Hydration failed because the server rendered text didn't match the client. As a result this tree will be regenerated on the client. This can happe
{ "filepath": "test/development/acceptance-app/hydration-error.test.ts", "language": "typescript", "file_size": 36270, "cut_index": 2151, "middle_length": 229 }
lt function Page() { return ( <> <Context.Provider value="hello"> <h1>Page</h1> </Context.Provider> </> ) } `, ], ]) ) const {...
'success' }, 'success') expect(next.cliOutput).toContain( 'createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-c
Contain( 'createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component' ) return
{ "filepath": "test/development/acceptance-app/server-components.test.ts", "language": "typescript", "file_size": 18732, "cut_index": 1331, "middle_length": 229 }
{ A as a } from '#/app/(post)/components/a' import { P as p } from '#/app/(post)/components/p' import { H1 as h1 } from '#/app/(post)/components/h1' import { H2 as h2 } from '#/app/(post)/components/h2' import { H3 as h3 } from '#/app/(post)/components/h3' import { OL as ol } from '#/app/(post)/components/ol' import {...
nents/callout' import { Ref, FootNotes, FootNote } from '#/app/(post)/components/footnotes' import { Blockquote as blockquote } from '#/app/(post)/components/blockquote' const components = { a, h1, h2, h3, p, ol, ul, li, hr, pre: Snipp
mponents/tweet' import { Image } from '#/app/(post)/components/image' import { Snippet } from '#/app/(post)/components/snippet' import { Caption } from '#/app/(post)/components/caption' import { Callout } from '#/app/(post)/compo
{ "filepath": "test/development/acceptance-app/fixtures/app-hmr-changes/mdx-components.ts", "language": "typescript", "file_size": 1180, "cut_index": 518, "middle_length": 229 }
tSetup } from 'e2e-utils' import path from 'path' import { createSandbox } from 'development-sandbox' import { outdent } from 'outdent' describe('Error overlay - error message urls', () => { const { next } = nextTestSetup({ files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')), skipStart: ...
s( '[data-nextjs-terminal] a, [data-nextjs-codeframe] a' ) const text = await link.text() const href = await link.getAttribute('href') expect(text).toEqual( 'https://nextjs.org/docs/app/building-your-application/data-fetching'
= await next.readFile('app/page.js') await session.patch( 'app/page.js', content + '\nexport function getServerSideProps() {}' ) await session.waitForRedbox() const link = await browser.elementByCs
{ "filepath": "test/development/acceptance-app/error-message-url.test.ts", "language": "typescript", "file_size": 1971, "cut_index": 537, "middle_length": 229 }
from 'node:path' import crypto from 'node:crypto' import { Buffer } from 'node:buffer' import vm from 'node:vm' import assert from 'node:assert' import constants from 'node:constants' import domain from 'node:domain' import http from 'node:http' import https from 'node:https' import os from 'node:os' import punycode fr...
w Writable({ write(_chunk, _encoding, callback) { callback() }, }) writable.on('finish', () => { closedStream = true }) writable.end() assert.ok(true) assert.ok(!!domain) assert.ok(!!http) asser
node:timers' import tty from 'node:tty' import util from 'node:util' import zlib from 'node:zlib' async function getData() { const result = await new Promise((resolve) => { let closedStream = false const writable = ne
{ "filepath": "test/development/basic/node-builtins/app/server-component/node-schema/page.js", "language": "javascript", "file_size": 2243, "cut_index": 563, "middle_length": 229 }
'export function getServerSideProps' ) await session.patch(pageFile, uncomment) await session.waitForRedbox() expect(await session.getRedboxSource()).toInclude( '"getServerSideProps" is not supported in app/' ) }) it('should throw an error when metadata export is used in client co...
t metadata' ) await session.patch(pageFile, uncomment) await session.waitForRedbox() expect(await session.getRedboxSource()).toInclude( 'You are attempting to export "metadata" from a component marked with "use client", which is disal
pageFile = 'app/client-with-errors/metadata-export/page.js' const content = await next.readFile(pageFile) // Add `metadata` error let uncomment = content.replace( '// export const metadata', 'export cons
{ "filepath": "test/development/acceptance-app/rsc-build-errors.test.ts", "language": "typescript", "file_size": 19932, "cut_index": 1331, "middle_length": 229 }
('with empty getInitialProps()', () => { it('should render a redbox', async () => { const pageErrors: unknown[] = [] const browser = await next.browser('/nav', { beforePageLoad: (page) => { page.on('pageerror', (error: unknown) => { pageErrors.push(error) }) ...
ect(pageErrors).toEqual([ expect.objectContaining({ message: '"EmptyInitialPropsPage.getInitialProps()" should resolve to an object. But found "null" instead.', }), ]) }) }) describe('with the current ur
ropsPage.getInitialProps()" should resolve to an object. But found "null" instead.", "environmentLabel": null, "label": "Runtime Error", "source": null, "stack": [], } `) exp
{ "filepath": "test/development/pages-dir/client-navigation/index.test.ts", "language": "typescript", "file_size": 16111, "cut_index": 921, "middle_length": 229 }
{ nextTestSetup } from 'e2e-utils' describe('Client Navigation with <Link/>', () => { const { next } = nextTestSetup({ files: path.join(__dirname, 'fixture'), env: { TEST_STRICT_NEXT_HEAD: String(true), }, }) it('should navigate the page', async () => { const browser = await next.browser(...
wser.waitForElementByCss('.nav-about') await browser.refresh() await waitFor(3000) await browser.back() await waitFor(3000) const text = await browser.elementByCss('#about-link').text() if (browser) await browser.close() expect(
'This is the about page.') await browser.close() }) it('should navigate back after reload', async () => { const browser = await next.browser('/nav') await browser.elementByCss('#about-link').click() await bro
{ "filepath": "test/development/pages-dir/client-navigation/link.test.ts", "language": "typescript", "file_size": 4010, "cut_index": 614, "middle_length": 229 }
import Link from 'next/link' import { useRouter } from 'next/router' let count = 0 const HashChanges = ({ count }) => { const router = useRouter() return ( <div id="hash-changes-page"> <Link href="#via-link" id="via-link"> Via Link </Link> <a href="#via-a" id="via-a"> Via A...
scroll={false} id="scroll-to-name-item-400-no-scroll" > Go to name item 400 (no scroll) </Link> <Link href="#中文" id="scroll-to-cjk-anchor"> Go to CJK anchor </Link> <p>COUNT: {count}</p> {Array.fr
#item-400" id="scroll-to-item-400"> Go to item 400 </Link> <Link href="#name-item-400" id="scroll-to-name-item-400"> Go to name item 400 </Link> <Link href="#name-item-400"
{ "filepath": "test/development/pages-dir/client-navigation/fixture/pages/nav/hash-changes.js", "language": "javascript", "file_size": 1777, "cut_index": 537, "middle_length": 229 }
ounter = 0 const linkStyle = { marginRight: 10, } export default class extends Component { increase() { counter++ this.forceUpdate() } visitQueryStringPage() { const href = { pathname: '/nav/querystring', query: { id: 10 } } const as = { pathname: '/nav/querystring/10', hash: '10' } Route...
Self Reload </Link> <Link href="/nav/shallow-routing" id="shallow-routing-link" style={linkStyle} > Shallow Routing </Link> <Link href="/nav/redirect" id="redirect-link"
k href="/empty-get-initial-props" id="empty-props" style={linkStyle} > Empty Props </Link> <Link href="/nav/self-reload" id="self-reload-link" style={linkStyle}>
{ "filepath": "test/development/pages-dir/client-navigation/fixture/pages/nav/index.js", "language": "javascript", "file_size": 3432, "cut_index": 614, "middle_length": 229 }
Link from 'next/link' import { useRouter } from 'next/router' import React from 'react' const LongPageToSnapScroll = () => { const router = useRouter() return ( <div id="long-page-to-snap-scroll"> <Link href="#item-400" id="scroll-to-item-400"> Go to item 400 </Link> {Array.from({ l...
er.push('/snap-scroll-position') }} > Go to snap scroll imperative </div> <div id="goto-snap-scroll-position-imperative-noscroll" onClick={(e) => { e.preventDefault() router.push('/snap-
roll-position" id="goto-snap-scroll-position"> Go to snap scroll declarative </Link> <div id="goto-snap-scroll-position-imperative" onClick={(e) => { e.preventDefault() rout
{ "filepath": "test/development/pages-dir/client-navigation/fixture/pages/nav/long-page-to-snap-scroll.js", "language": "javascript", "file_size": 1223, "cut_index": 518, "middle_length": 229 }
mport { Component } from 'react' import Link from 'next/link' export default class OnClick extends Component { static getInitialProps({ res, query: { count } }) { return { count: count ? parseInt(count) : 0 } } state = { stateCounter: 0, } render() { const { stateCounter } = this.state cons...
{ e.preventDefault() this.setState({ stateCounter: stateCounter + 1 }) }} > Self Reload </Link> <p id="query-count">QUERY COUNT: {count}</p> <p id="state-count">STATE COUNT: {stat
onClick={() => this.setState({ stateCounter: stateCounter + 1 })} > Self Reload </Link> <Link href="/nav/on-click" id="on-click-link-prevent-default" onClick={(e) =>
{ "filepath": "test/development/pages-dir/client-navigation/fixture/pages/nav/on-click.js", "language": "javascript", "file_size": 1037, "cut_index": 513, "middle_length": 229 }
Link from 'next/link' import { useRouter } from 'next/router' import { useEffect, useState } from 'react' export default function Page() { const router = useRouter() const [routeState, setRouteResult] = useState({ completed: 0, errors: 0, }) useEffect(() => { const increaseErrorCount = () => ...
.off('routeChangeComplete', increaseRouteComplete) } }) return ( <> <div id="routeState">{JSON.stringify(routeState)}</div> <Link href="?prop=foo" id="link" shallow={true}> Click me </Link> <button id="r
router.events.on('routeChangeError', increaseErrorCount) router.events.on('routeChangeComplete', increaseRouteComplete) return () => { router.events.off('routeChangeError', increaseErrorCount) router.events
{ "filepath": "test/development/pages-dir/client-navigation/fixture/pages/nav/query-only-shallow.js", "language": "javascript", "file_size": 1176, "cut_index": 518, "middle_length": 229 }
ter' export default function Page() { const router = useRouter() return ( <> <button id="click-me" onClick={() => router.push({ pathname: '/query', query: { param1: '', param2: undefined, param3: null, ...
undefined, null, 0, false, [], {}, NaN, new Date(1234), /hello/, ], }, }) }
param11: [ '',
{ "filepath": "test/development/pages-dir/client-navigation/fixture/pages/nav/query-params.js", "language": "javascript", "file_size": 911, "cut_index": 547, "middle_length": 52 }
'react' import Link from 'next/link' import Router, { withRouter } from 'next/router' let getInitialPropsRunCount = 1 const linkStyle = { marginRight: 10, } export default withRouter( class extends Component { static getInitialProps({ res }) { if (res) return { getInitialPropsRunCount: 1 } getIn...
NonShallow() { const counter = this.getCurrentCounter() const href = `/nav/shallow-routing?counter=${counter + 1}` Router.push(href, href, {}) } gotoNavShallow() { const href = `/nav` Router.push(href, href, { shallow
unter) : 0 } increase(scroll) { const counter = this.getCurrentCounter() const href = `/nav/shallow-routing?counter=${counter + 1}` Router.push(href, href, { shallow: true, scroll }) } increase
{ "filepath": "test/development/pages-dir/client-navigation/fixture/pages/nav/shallow-routing.js", "language": "javascript", "file_size": 2006, "cut_index": 537, "middle_length": 229 }
expect(stripAnsi(next.cliOutput)).toContain( isTurbopack ? '\n⨯ Error: boom' + // TODO(veil): Sourcemap to original name i.e. "default" '\n at __TURBOPACK__default__export__ (middleware.js:3:15)' + '\n 1 |' : isRspack ? '\n⨯ Error: b...
correctly and recovers', async () => { const browser = await next.browser('/') if (isTurbopack) { await expect(browser).toDisplayRedbox(` { "code": "E394", "description": "boom", "environmentLa
'\n 1 |' ) expect(stripAnsi(next.cliOutput)).toContain( '' + "\n> 3 | throw new Error('boom')" + '\n | ^' ) }) it('renders the error
{ "filepath": "test/development/middleware-errors/index.test.ts", "language": "typescript", "file_size": 20632, "cut_index": 1331, "middle_length": 229 }
tSetup } from 'e2e-utils' import { join } from 'path' import { waitForRedbox, waitForNoRedbox, getRedboxSource, } from 'next-test-utils' // TODO: The error overlay is not closed when restoring the working code. describe.skip('next/font build-errors', () => { const { next } = nextTestSetup({ files: new File...
!</p> } ` ) await waitForRedbox(browser) expect(await getRedboxSource(browser)).toMatchInlineSnapshot(` "app/page.js \`next/font\` error: Missing required \`src\` property" `) await next.patchFile('app/page.js', cont
eadFile('app/page.js') await next.patchFile( 'app/page.js', ` import localFont from 'next/font/local' const font = localFont() export default function Page() { return <p className={font.className}>Hello world
{ "filepath": "test/development/next-font/build-errors.test.ts", "language": "typescript", "file_size": 1936, "cut_index": 537, "middle_length": 229 }
int-env jest */ import { nextTestSetup } from 'e2e-utils' import { check } from 'next-test-utils' describe('Deprecated @next/font warning', () => { const { next, skipped } = nextTestSetup({ files: { 'pages/index.js': '', }, dependencies: { '@next/font': 'canary', }, skipStart: true, ...
deps const packageJson = JSON.parse(await next.readFile('package.json')) delete packageJson.dependencies['@next/font'] await next.patchFile('package.json', JSON.stringify(packageJson)) await next.start() await check(() => next.cliOutpu
liOutput, new RegExp('please use the built-in `next/font` instead') ) await next.stop() await next.clean() }) it('should not warn if @next/font is not in deps', async () => { // Remove @next/font from
{ "filepath": "test/development/next-font/deprecated-package.test.ts", "language": "typescript", "file_size": 1170, "cut_index": 518, "middle_length": 229 }
{ FileRef, nextTestSetup } from 'e2e-utils' import { waitForRedbox, getRedboxSource } from 'next-test-utils' import { join } from 'path' describe('font-loader-in-document-error', () => { const { next } = nextTestSetup({ files: { pages: new FileRef(join(__dirname, 'font-loader-in-document/pages')), }, ...
.NEXT_RSPACK) { expect(await getRedboxSource(browser)).toMatchInlineSnapshot(` "pages/_document.js × \`next/font\` error: │ Cannot be used within pages/_document.js." `) } else { expect(await getRedboxSource(b
rbopack doesn't include pages/ expect(await getRedboxSource(browser)).toMatchInlineSnapshot(` "./_document.js next/font: error: Cannot be used within _document.js" `) } else if (process.env
{ "filepath": "test/development/next-font/font-loader-in-document-error.test.ts", "language": "typescript", "file_size": 1192, "cut_index": 518, "middle_length": 229 }
join } from 'path' import fs from 'fs-extra' describe('jsconfig-path-reloading', () => { const tsConfigFile = 'jsconfig.json' const indexPage = 'pages/index.js' const tsConfigContent = fs.readFileSync( join(__dirname, 'app/jsconfig.json'), 'utf8' ) function runTests({ addAfterStart }: { addAfterSt...
latest', '@types/react': 'latest', '@types/node': 'latest', }, }) if (addAfterStart) { beforeAll(async () => { await next.patchFile(tsConfigFile, tsConfigContent) }) } it('should load with initial
')), lib: new FileRef(join(__dirname, 'app/lib')), ...(addAfterStart ? {} : { [tsConfigFile]: tsConfigContent, }), }, dependencies: { typescript: '
{ "filepath": "test/development/jsconfig-path-reloading/index.test.ts", "language": "typescript", "file_size": 5854, "cut_index": 716, "middle_length": 229 }
c function getStaticProps() { return { props: { posts: ["my isr post"] }, revalidate: 10, } }` const blogGspRevalidateFalse = `export default function Blog({ posts }) { return posts.map(p => (<div key={p}>{p}</div>)) } export async function getStaticProps...
on Blog({ posts }) { return posts.map(p => (<div key={p}>{p}</div>)) } export async function getServerSideProps() { return { props: { posts: ["my ssr post"] }, } }` const postsSlug = (fallback: st
return posts.map(p => (<div key={p}>{p}</div>)) } export async function getStaticProps() { return { props: { posts: ["my gsp post"] }, } }` const blogGssp = `export default functi
{ "filepath": "test/development/config-output-export/config-output-export.test.ts", "language": "typescript", "file_size": 12254, "cut_index": 921, "middle_length": 229 }
ort { join } from 'path' import { FileRef, nextTestSetup } from 'e2e-utils' import { shouldUseTurbopack } from 'next-test-utils' describe('typescript-external-dir', () => { const { next } = nextTestSetup({ files: { project: new FileRef(join(__dirname, 'project')), shared: new FileRef(join(__dirname, ...
dev${ shouldUseTurbopack() ? ' --turbopack' : '' }`, }, }, startCommand: 'pnpm run dev-project', }) it('should render the page with external TS/TSX dependencies', async () => { const $ = await next.render$('/')
file, so Turbopack's `rootPath` includes both // directories and `experimental.externalDir` resolves // `../../shared/*` from `project/pages`. packageJson: { scripts: { 'dev-project': `cd project && next
{ "filepath": "test/development/typescript-external-dir/typescript-external-dir.test.ts", "language": "typescript", "file_size": 1068, "cut_index": 515, "middle_length": 229 }
from 'e2e-utils' import { retry } from 'next-test-utils' describe('stale-dev-types', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should not fail build when .next/dev has stale types from deleted routes', async () => { // Step 1: Wait for dev server to generate .next/dev/types/valid...
eadFile('.next/dev/types/validator.ts') expect(validatorContent).toContain('temp-route/page') // Step 2: Stop dev server await next.stop() // Step 3: Delete the temp-route (simulating user deleting a route) await next.deleteFile('app/
if (!exists) { throw new Error('validator.ts not generated yet') } }, 5000, 500 ) // Verify validator.ts contains reference to temp-route const validatorContent = await next.r
{ "filepath": "test/development/stale-dev-types/stale-dev-types.test.ts", "language": "typescript", "file_size": 1612, "cut_index": 537, "middle_length": 229 }
extTestSetup } from 'e2e-utils' import { retry } from 'next-test-utils' describe('Dynamic route rename casing', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should not throw error when changing casing of dynamic route file', async () => { const html = await next.render('/abc') e...
ames for the same dynamic path` ) }) await next.renameFile('pages/[PiD].js', 'pages/[pid].js') await retry(async () => { expect(next.cliOutput).not.toContain( `You cannot use different slug names for the same dynamic path`
fferent slug n
{ "filepath": "test/development/dynamic-route-rename/dynamic-route-rename.test.ts", "language": "typescript", "file_size": 816, "cut_index": 522, "middle_length": 14 }
e('spaces', () => { it('should have correct query on SSR', async () => { const browser = await next.browser(encodeURI('/single/hello world ')) const text = await browser.elementByCss('#query-content').text() expect(text).toMatchInlineSnapshot(`"{"slug":"hello world "}"`) }) it('should hav...
const text = await browser.elementByCss('#query-content').text() expect(text).toMatchInlineSnapshot(`"{"slug":"hello world "}"`) }) it('should have correct query on simple client-side <Link>', async () => { const browser = await next.
}, { pathname: encodeURI('/single/hello world ') } )` ) await retry(async () => { expect(await browser.hasElementByCssSelector('#query-content')).toBe( true ) })
{ "filepath": "test/development/link-with-encoding/link-with-encoding.test.ts", "language": "typescript", "file_size": 7724, "cut_index": 716, "middle_length": 229 }
import Link from 'next/link' const Home = () => ( <div> <Link href="/single/[slug]" as={encodeURI('/single/hello world ')} id="single-spaces" > Single: Spaces </Link> <br /> <Link href="/single/[slug]" as={encodeURI('/single/hello%world')} id="single-perc...
href="/single/[slug]" as={`/single/hello${encodeURIComponent(':')}world`} id="single-colon" > Single: : </Link> <br /> <Link href="/query?id=http://example.com/" id="url-param"> Url query param </Link> </div> )
le: Forward Slash </Link> <br /> <Link href="/single/[slug]" as={`/single/hello${encodeURIComponent('"')}world`} id="single-double-quote" > Single: " </Link> <br /> <Link
{ "filepath": "test/development/link-with-encoding/pages/index.js", "language": "javascript", "file_size": 1019, "cut_index": 512, "middle_length": 229 }
mport { nextTestSetup } from 'e2e-utils' describe('Configuration with next.config.mjs', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should disable X-Powered-By header support', async () => { const res = await next.fetch('/') expect(res.headers.get('X-Powered-By')).not.toBe('Nex...
.text()).toBe('OK') }) it('should have env variables available on the client', async () => { const browser = await next.browser('/next-config') const envValue = await browser.elementByCss('#env').text() expect(envValue).toBe('hello') })
geInAPackage')
{ "filepath": "test/development/config-mjs/config-mjs.test.ts", "language": "typescript", "file_size": 786, "cut_index": 513, "middle_length": 14 }
tTestSetup } from 'e2e-utils' import { fetchViaHTTP } from 'next-test-utils' ;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)( 'Slow Module Detection', () => { const { next } = nextTestSetup({ files: __dirname, overrideFiles: { 'utils/slow-module.js': ` // This module is...
ync () => { let logs = '' next.on('stdout', (log) => { logs += log }) // Trigger a compilation by making a request await fetchViaHTTP(next.url, '/') // Wait for compilation to complete and check logs awai
tringify( Array(100).fill(`some-long-string-${i}`).join('') )} ` ) .join('\n')} `, }, }) it('should detect slow modules in webpack mode', as
{ "filepath": "test/development/slow-module-detection/index.test.ts", "language": "typescript", "file_size": 1260, "cut_index": 524, "middle_length": 229 }
ort { nextTestSetup } from 'e2e-utils' import { fetchViaHTTP } from 'next-test-utils' describe('Rewritten API Requests should pass OPTIONS requests to the api function', () => { const { next } = nextTestSetup({ files: { 'pages/api/some-endpoint.js': ` export default (req, res) => { res.en...
ependencies: {}, }) it('should pass OPTIONS requests to the api function', async () => { const res = await fetchViaHTTP(next.url, '/some-endpoint', null, { method: 'OPTIONS', headers: { Origin: 'http://localhost:3000', },
ires a /api prefix, let's remove that { source: '/:path*', destination: '/api/:path*', }, ], afterFiles: [], fallback: [], }), }, d
{ "filepath": "test/development/api-cors-with-rewrite/index.test.ts", "language": "typescript", "file_size": 1090, "cut_index": 515, "middle_length": 229 }
rollHandlerNew' : 'InnerScrollAndFocusHandlerOld' function setupLogCapture() { const logs: string[] = [] const originalStdout = process.stdout.write const originalStderr = process.stderr.write const capture = (chunk: any) => { logs.push(stripAnsi(chunk.toString())) return true } process.stdout....
} } describe(`Terminal Logging (${bundlerName})`, () => { describe('Pages Router', () => { let logs: string[] = [] let logCapture: ReturnType<typeof setupLogCapture> let browser = null beforeAll(() => { logCapture = setupLogCaptur
r.call(this, chunk) } const restore = () => { process.stdout.write = originalStdout process.stderr.write = originalStderr } const clearLogs = () => { logs.length = 0 } return { logs, restore, clearLogs
{ "filepath": "test/development/browser-logs/browser-logs.test.ts", "language": "typescript", "file_size": 13446, "cut_index": 921, "middle_length": 229 }
import { nextTestSetup } from 'e2e-utils' describe('experimental-https-server OpenGraph image', () => { const { next, skipped } = nextTestSetup({ files: __dirname, startCommand: 'pnpm next dev --experimental-https', skipStart: !process.env.NEXT_TEST_CI, }) if (skipped) return if (!process.env.NEXT...
onst html = await browser.eval('document.documentElement.innerHTML') expect(html).toContain('Hello from App') expect(html).toMatch(/<meta property="og:image" content="https:\/\//) expect(html).toMatch(/<meta name="twitter:image" content="https:
generate https:// URLs for OpenGraph images when experimental HTTPS is enabled', async () => { expect(next.url).toContain('https://') const browser = await next.browser('/1', { ignoreHTTPSErrors: true, }) c
{ "filepath": "test/development/experimental-https-server/https-server-opengraph-image.test.ts", "language": "typescript", "file_size": 1012, "cut_index": 512, "middle_length": 229 }
tTestSetup } from 'e2e-utils' import https from 'https' import { renderViaHTTP } from 'next-test-utils' describe('experimental-https-server (generated certificate)', () => { const { next, skipped } = nextTestSetup({ files: __dirname, startCommand: 'pnpm next dev --experimental-https', skipStart: !process...
tps://') const html = await renderViaHTTP(next.url, '/1', undefined, { agent }) expect(html).toContain('Hello from App') }) it('should successfully load the app in pages dir', async () => { expect(next.url).toInclude('https://') const
ires administrator privileges', () => {}) return } const agent = new https.Agent({ rejectUnauthorized: false, }) it('should successfully load the app in app dir', async () => { expect(next.url).toInclude('ht
{ "filepath": "test/development/experimental-https-server/https-server.generated-key.test.ts", "language": "typescript", "file_size": 1394, "cut_index": 524, "middle_length": 229 }
port { renderViaHTTP } from 'next-test-utils' describe('experimental-https-server (provided certificate)', () => { const { next } = nextTestSetup({ files: __dirname, startCommand: `pnpm next dev --experimental-https --experimental-https-key ./certificates/localhost-key.pem --experimental-https-cert ./certifi...
next.url, '/1', undefined, { agent }) expect(html).toContain('Hello from App') }) it('should successfully load the app in pages dir', async () => { expect(next.url).toInclude('https://') const html = await renderViaHTTP(next.url, '/2', und
de('https://') const html = await renderViaHTTP(
{ "filepath": "test/development/experimental-https-server/https-server.provided-key.test.ts", "language": "typescript", "file_size": 964, "cut_index": 582, "middle_length": 52 }
from 'e2e-utils' import { retry, shouldUseTurbopack, waitFor } from 'next-test-utils' ;(shouldUseTurbopack() ? describe.skip : describe)('On Demand Entries', () => { const { next } = nextTestSetup({ files: __dirname, startCommand: 'node server.js', serverReadyPattern: /- Local:/, dependencies: { ...
/about'] expect(pageFiles).toBeDefined() const pageFile = pageFiles[pageFiles.length - 1] expect(pageFile).toMatch(/\.js$/) expect(pageFile).toContain('pages/about') const pageContent = await next.render(`/_next/${pageFile}`) expect
'should compile pages for JSON page requests', async () => { await next.render('/about') const manifest = JSON.parse( await next.readFile('.next/dev/build-manifest.json') ) const pageFiles = manifest.pages['
{ "filepath": "test/development/ondemand/ondemand.test.ts", "language": "typescript", "file_size": 1954, "cut_index": 537, "middle_length": 229 }
test-utils' describe('getServerSideProps redirects', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should use a client-side navigation for a rewritten URL', async () => { const browser = await next.browser('/alias-to-main-content') await browser.eval('window.__SAME_PAGE = true')...
known URL', async () => { const browser = await next.browser('/alias-to-main-content') await browser.eval('window.__SAME_PAGE = true') await browser.elementByCss('#link-unknown-url').click() await retry(async () => { const val = awa
it('should fallback to browser navigation for an un
{ "filepath": "test/development/gssp-redirect-with-rewrites/gssp-redirect-with-rewrites.test.ts", "language": "typescript", "file_size": 973, "cut_index": 582, "middle_length": 52 }
ssage }) { return ( <main> <h1>Hello {message}</h1> <ul> <li> <Link href="/redirector?redirect=/alias-to-main-content&message=refreshed" id="link-with-rewritten-url" className={message} > Link with rewritten target url ...
k href="/redirector?redirect=/unknown-route" id="link-unknown-url" > Link to unknown internal navigation </Link> </li> </ul> </main> ) } export const getServerSideProps = ({ query
</Link> </li> <li> <Lin
{ "filepath": "test/development/gssp-redirect-with-rewrites/pages/main-content.js", "language": "javascript", "file_size": 952, "cut_index": 582, "middle_length": 52 }
y from 'next' import ts from 'typescript' export { NEXT_TS_ERRORS } from 'next/dist/server/typescript/constant' export type PluginLanguageService = ts.LanguageService & { getCapturedLogs: () => string } export function getPluginLanguageService(dir: string): PluginLanguageService { const files = ts.sys.readDirecto...
nguageServiceHost = { ...compilerHost, getCompilationSettings: () => compilerOptions, getScriptFileNames: () => files, getScriptSnapshot: (fileName) => { const contents = ts.sys.readFile(fileName) if (contents && typeof contents
> { const message = args .map((arg) => (typeof arg === 'string' ? arg : JSON.stringify(arg))) .join(' ') logs += message + '\n' console.log(...args) }, } const languageServiceHost: ts.La
{ "filepath": "test/development/typescript-plugin/test-utils.ts", "language": "typescript", "file_size": 1959, "cut_index": 537, "middle_length": 229 }
tsFiles) { // This test expects no diagnostics, but if somehow the test // detects one and fails, the diagnostics output on the terminal // is too long and omits the filename, so we filter out only the // necessary properties for debugging. totalDiagnostics[relative(__dirname, tsFile)] = l...
warn-no-type/metadata/has-type/export-inline-from-next/page.tsx": [], "app/warn-no-type/metadata/has-type/export-inline-from-other/layout.tsx": [], "app/warn-no-type/metadata/has-type/export-inline-from-other/page.tsx": [], "app/warn-n
ic.start, length: diagnostic.length, })) } expect(totalDiagnostics).toMatchInlineSnapshot( ` { "app/warn-no-type/metadata/has-type/export-inline-from-next/layout.tsx": [], "app/
{ "filepath": "test/development/typescript-plugin/metadata/warn-no-type.test.ts", "language": "typescript", "file_size": 19046, "cut_index": 1331, "middle_length": 229 }
ive, resolve } from 'node:path' import { getPluginLanguageService } from '../test-utils' type PartialDiagnostic = Pick< ts.Diagnostic, 'code' | 'messageText' | 'start' | 'length' > describe('typescript-plugin - client-boundary', () => { let languageService: PluginLanguageService beforeAll(() => { languag...
the filename, so we filter out only the // necessary properties for debugging. totalDiagnostics[relative(__dirname, tsFile)] = languageService .getSemanticDiagnostics(tsFile) .map((diagnostic) => ({ code: diagnostic.code,
const totalDiagnostics: Record<string, PartialDiagnostic[]> = {} // This test expects no diagnostics, but if somehow the test // detects one and fails, the diagnostics output on the terminal // is too long and omits
{ "filepath": "test/development/typescript-plugin/client-boundary/client-boundary.test.ts", "language": "typescript", "file_size": 4446, "cut_index": 614, "middle_length": 229 }
eca from 'execa' import fs from 'fs' import path from 'path' import stripAnsi from 'strip-ansi' describe('lockfile', () => { const { next, isTurbopack, isRspack } = nextTestSetup({ files: __dirname, }) it('only allows a single instance of `next dev` to run at a time', async () => { const browser = await...
const serverInfo = JSON.parse(fs.readFileSync(lockfilePath, 'utf-8')) expect(serverInfo).toMatchObject({ pid: expect.any(Number), port: expect.any(Number), hostname: expect.any(String), appUrl: expect.any(String), start
r is .next/dev const distDir = path.join(next.testDir, '.next', 'dev') const lockfilePath = path.join(distDir, 'lock') expect(fs.existsSync(lockfilePath)).toBe(true) // Read server info from the lockfile itself
{ "filepath": "test/development/lockfile/lockfile.test.ts", "language": "typescript", "file_size": 2502, "cut_index": 563, "middle_length": 229 }
y } from 'next-test-utils' describe('Client navigation with onClick action', () => { const { next } = nextTestSetup({ files: path.join(__dirname, 'fixture'), env: { TEST_STRICT_NEXT_HEAD: String(true), }, }) it('should reload the page and perform additional action', async () => { const bro...
fterClicked = await browser .elementByCss('#query-count') .text() const countStateAfterClicked = await browser .elementByCss('#state-count') .text() expect(countQueryAfterClicked).toBe('QUERY COUNT: 1') exp
t').text() expect(defaultCountQuery).toBe('QUERY COUNT: 0') expect(defaultCountState).toBe('STATE COUNT: 0') await browser.elementByCss('#on-click-link').click() await retry(async () => { const countQueryA
{ "filepath": "test/development/pages-dir/client-navigation/on-click.test.ts", "language": "typescript", "file_size": 3398, "cut_index": 614, "middle_length": 229 }
rname, 'fixture'), env: { TEST_STRICT_NEXT_HEAD: String(true), }, }) function render( pathname: Parameters<typeof renderViaHTTP>[1], query?: Parameters<typeof renderViaHTTP>[2] ) { return renderViaHTTP(next.appPort, pathname, query) } function fetch( pathname: Parameters<typeof...
.toContain('<meta charSet="utf-8" data-next-head=""/>') expect(html).toContain('My component!') }) it('should should not contain scripts that are not js', async () => { const $ = await get$('/') $('script[src]').each((_index, ele
html = await render(path, query) return cheerio.load(html) } describe('Rendering via HTTP', () => { test('renders a stateless component', async () => { const html = await render('/stateless') expect(html)
{ "filepath": "test/development/pages-dir/client-navigation/rendering.test.ts", "language": "typescript", "file_size": 15065, "cut_index": 921, "middle_length": 229 }
{ nextTestSetup } from 'e2e-utils' describe('Client navigation with shallow routing', () => { const { next } = nextTestSetup({ files: path.join(__dirname, 'fixture'), env: { TEST_STRICT_NEXT_HEAD: String(true), }, }) it('should update the url without running getInitialProps', async () => { ...
t') .text() expect(getInitialPropsRunCount).toBe('getInitialProps run count: 1') await browser.close() }) it('should handle the back button and should not run getInitialProps', async () => { const browser = await next.browser('/nav/
async () => { const counter = await browser.elementByCss('#counter').text() expect(counter).toBe('Counter: 2') }) const getInitialPropsRunCount = await browser .elementByCss('#get-initial-props-run-coun
{ "filepath": "test/development/pages-dir/client-navigation/shallow-routing.test.ts", "language": "typescript", "file_size": 3683, "cut_index": 614, "middle_length": 229 }
nk' import { useRouter } from 'next/router' export async function getServerSideProps({ query: { port } }) { if (!port) { throw new Error('port required') } return { props: { port } } } export default function Page({ port }) { const router = useRouter() const [hover, setHover] = React.useState(false) ...
lace https://vercel.com/ </button> <br /> <Link href={`http://localhost:${port}/nav/about`} id="absolute-local-link" > http://localhost:{port}/nav/about </Link> <br /> <Link href={`h
router.push('https://vercel.com/')} > push https://vercel.com/ </button> <br /> <button id="router-replace" onClick={() => router.replace('https://vercel.com/')} > rep
{ "filepath": "test/development/pages-dir/client-navigation/fixture/pages/absolute-url.js", "language": "javascript", "file_size": 2075, "cut_index": 563, "middle_length": 229 }
import Link from 'next/link' import { withRouter } from 'next/router' export default withRouter(({ router: { asPath, query } }) => { return ( <div id={asPath.replace('/', '').replace('/', '-')}> <div id="router-query">{JSON.stringify(query)}</div> <div> <Link href="/nav/as-path-push...
</Link> </div> {query.something === 'hello' && ( <Link href="/nav/as-path-pushstate?something=hello" as="/something/same-query" id="same-query" > same query </Link>
something/else" id="else"> else </Link> </div> <div> <Link href="/nav/as-path-pushstate" as="/nav/as-path-pushstate" id="hello2" > normal hello
{ "filepath": "test/development/pages-dir/client-navigation/fixture/pages/nav/as-path-pushstate.js", "language": "javascript", "file_size": 1018, "cut_index": 512, "middle_length": 229 }
} from 'react' import Router from 'next/router' let count = 0 export default class SelfReload extends Component { static getInitialProps({ res }) { if (res) return { count: 0 } count += 1 return { count } } handleAClick = () => { Router.push( '/nav/hash-changes-with-state', '/nav/...
historyCount: window.history.state?.options?.historyCount, shallowHistoryCount: (window.history.state?.options?.shallowHistoryCount || 0) + 1, } ) } render() { return ( <div id="hash-changes-page"> <p>COUN
?.shallowHistoryCount, } ) } handleAShallowClick = () => { Router.push( '/nav/hash-changes-with-state#', '/nav/hash-changes-with-state#hello' + Math.random(), { shallow: true,
{ "filepath": "test/development/pages-dir/client-navigation/fixture/pages/nav/hash-changes-with-state.js", "language": "javascript", "file_size": 1738, "cut_index": 537, "middle_length": 229 }
from 'e2e-utils' import { retry } from 'next-test-utils' import { join } from 'path' describe('Has CSS Module in computed styles in Development', () => { const { next } = nextTestSetup({ files: join(__dirname, 'fixtures/dev-module'), }) it('should have CSS for page', async () => { const browser = await ...
emounting <input>', async () => { const browser = await next.browser('/') const desiredText = 'hello world' await browser.elementById('text-input').type(desiredText) expect(await browser.elementById('text-input').getValue()).toBe(desiredTe
t(`"rgb(255, 0, 0)"`) }) }) describe('Can hot reload CSS Module without losing state', () => { const { next } = nextTestSetup({ files: join(__dirname, 'fixtures/hmr-module'), }) it('should update CSS color without r
{ "filepath": "test/development/css-modules/css-modules.test.ts", "language": "typescript", "file_size": 1909, "cut_index": 537, "middle_length": 229 }
'path' describe('Can hot reload CSS without losing state', () => { const { next } = nextTestSetup({ files: join(__dirname, 'fixtures/multi-page'), }) it('should update CSS color without remounting <input>', async () => { const browser = await next.browser('/page1') const desiredText = 'hello world...
ile(cssPath) await next.patchFile( cssPath, originalCss.replace('color: red', 'color: purple') ) try { await retry(async () => { const color = await browser.eval( `window.getComputedStyle(document.querySelec
`window.getComputedStyle(document.querySelector('.red-text')).color` ) expect(currentColor).toMatchInlineSnapshot(`"rgb(255, 0, 0)"`) const cssPath = 'styles/global1.css' const originalCss = await next.readF
{ "filepath": "test/development/css-features/dev-css-handling.test.ts", "language": "typescript", "file_size": 3380, "cut_index": 614, "middle_length": 229 }
utils' import { check } from 'next-test-utils' describe('next-config-ts - dev-hmr', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should output config file change', async () => { await check(async () => next.cliOutput, /ready/i) await check(async () => { await next.patchFil...
rmanent: false, }, ] },` ) }) return next.cliOutput }, /Found a change in next\.config\.ts\. Restarting the server to apply the changes\.\.\./) await check(() => next.fetch('/about').then((re
destination: '/', pe
{ "filepath": "test/development/next-config-ts/hmr/index.test.ts", "language": "typescript", "file_size": 887, "cut_index": 547, "middle_length": 52 }
join } from 'path' import fs from 'fs-extra' describe('tsconfig-path-reloading', () => { const tsConfigFile = 'tsconfig.json' const indexPage = 'pages/index.tsx' const tsConfigContent = fs.readFileSync( join(__dirname, 'app/tsconfig.json'), 'utf8' ) function runTests({ addAfterStart, testB...
: { [tsConfigFile]: tsConfigContent, }), }, dependencies: { typescript: typescriptVersion, '@types/react': 'latest', '@types/node': 'latest', }, }) if (addAfterStart) { bef
components: new FileRef(join(__dirname, 'app/components')), pages: new FileRef(join(__dirname, 'app/pages')), lib: new FileRef(join(__dirname, 'app/lib')), ...(addAfterStart ? {}
{ "filepath": "test/development/tsconfig-path-reloading/index.test.ts", "language": "typescript", "file_size": 6253, "cut_index": 716, "middle_length": 229 }
{ next } = nextTestSetup({ files: __dirname, }) const navigateTo = async (browser: any, selector: string) => await browser .waitForElementByCss('#' + selector + '-link') .click() .waitForElementByCss('#' + selector) const getAnnouncedTitle = async (browser: any) => await browser.w...
= await getAnnouncedTitle(browser) expect(title).toBe('') }) it('has aria-live="assertive" and role="alert"', async () => { const browser = await next.browser('/') const routeAnnouncer = await browser.waitForElementByCss(
r: any) => await browser.elementByCss('h1').text() describe('<RouteAnnouncer />', () => { it('should not have the initial route announced', async () => { const browser = await next.browser('/') const title
{ "filepath": "test/development/client-navigation-a11y/client-navigation-a11y.test.ts", "language": "typescript", "file_size": 3081, "cut_index": 614, "middle_length": 229 }
e development errors', () => { const { next } = nextTestSetup({ files: __dirname, }) let middlewareContent: string beforeAll(async () => { middlewareContent = await next.readFile('middleware.js') }) async function assertMiddlewareFetch(hasMiddleware: boolean, path = '/') { await retry(async ()...
').text() expect(fromMiddleware).toBe(hasMiddleware ? 'true' : 'null') }) } describe('when middleware is removed', () => { let stderrLog = '' let onStderr: ((msg: string) => void) | undefined beforeEach(async () => { stder
} async function assertMiddlewareRender(hasMiddleware: boolean, path = '/') { const browser = await next.browser(path) await retry(async () => { const fromMiddleware = await browser.elementById('from-middleware
{ "filepath": "test/development/middleware-dev-update/middleware-dev-update.test.ts", "language": "typescript", "file_size": 3506, "cut_index": 614, "middle_length": 229 }
from 'e2e-utils' import { check } from 'next-test-utils' describe('custom-app-hmr', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should not do full reload when simply editing _app.js', async () => { const customAppFilePath = 'pages/_app.js' const browser = await next.browser('/')...
ect(pText).toBe('hmr text changed') // Should keep the value on window, which indicates there's no full reload const hmrConstantValue = await browser.eval('window.hmrConstantValue') expect(hmrConstantValue).toBe('should-not-change')
eplace( 'hmr text origin', 'hmr text changed' ) await next.patchFile(customAppFilePath, newCustomAppContent) await check(async () => { const pText = await browser.elementByCss('h1').text() exp
{ "filepath": "test/development/pages-dir/custom-app-hmr/index.test.ts", "language": "typescript", "file_size": 1523, "cut_index": 537, "middle_length": 229 }
estSetup({ files: path.join(__dirname, 'fixture'), env: { TEST_STRICT_NEXT_HEAD: String(true), }, }) describe('inside getInitialProps', () => { it('should show the correct asPath with a Link with as prop', async () => { const browser = await next.browser('/nav') const asPath = awa...
.elementByCss('#as-path-link-no-as') .click() .waitForElementByCss('.as-path-content') .elementByCss('.as-path-content') .text() expect(asPath).toBe('/nav/as-path') await browser.close() }) }) de
th).toBe('/as/path') await browser.close() }) it('should show the correct asPath with a Link without the as prop', async () => { const browser = await next.browser('/nav') const asPath = await browser
{ "filepath": "test/development/pages-dir/client-navigation/as-path.test.ts", "language": "typescript", "file_size": 5769, "cut_index": 716, "middle_length": 229 }
port { waitForNoRedbox, waitFor } from 'next-test-utils' import path from 'path' import { nextTestSetup } from 'e2e-utils' describe('Client navigation with foreign history manipulation', () => { const { next } = nextTestSetup({ files: path.join(__dirname, 'fixture'), env: { TEST_STRICT_NEXT_HEAD: Strin...
waitFor(1000) await waitForNoRedbox(browser) }) it('should ignore history state with an invalid url', async () => { const browser = await next.browser('/nav') // push history object wit invalid url (not relative) await browser.eval(
ser.eval( 'window.history.pushState({ url: "/whatever" }, "", "/whatever")' ) await browser.elementByCss('#about-link').click() await browser.waitForElementByCss('.nav-about') await browser.back() await
{ "filepath": "test/development/pages-dir/client-navigation/foreign-history-manipulation.test.ts", "language": "typescript", "file_size": 1733, "cut_index": 537, "middle_length": 229 }
test-utils' import path from 'path' import { nextTestSetup } from 'e2e-utils' describe('Client navigation querystring', () => { const { next } = nextTestSetup({ files: path.join(__dirname, 'fixture'), env: { TEST_STRICT_NEXT_HEAD: String(true), }, }) describe('with the same page but different ...
=> { const browser = await next.browser('/nav/querystring?id=1') const text = await browser .elementByCss('#main-page') .click() .waitForElementByCss('.nav-id-0') .elementByCss('p') .text() expect
'#next-id-link') .click() .waitForElementByCss('.nav-id-2') .elementByCss('p') .text() expect(text).toBe('2') await browser.close() }) it('should remove querystring', async ()
{ "filepath": "test/development/pages-dir/client-navigation/querystring.test.ts", "language": "typescript", "file_size": 2410, "cut_index": 563, "middle_length": 229 }
stSetup } from 'e2e-utils' describe('Client navigation scroll', () => { const { next } = nextTestSetup({ files: path.join(__dirname, 'fixture'), env: { TEST_STRICT_NEXT_HEAD: String(true), }, }) describe('resets scroll at the correct time', () => { it('should reset scroll before the new pa...
// Go to snap scroll page await browser .elementByCss('#goto-snap-scroll-position') .click() .waitForElementByCss('#scroll-pos-y') const snappedScrollPosition = await browser.eval( 'document.getElementById("s
.waitForElementByCss('#long-page-to-snap-scroll') .elementByCss('#scroll-to-item-400') .click() const scrollPosition = await browser.eval('window.pageYOffset') expect(scrollPosition).toBe(7208)
{ "filepath": "test/development/pages-dir/client-navigation/scroll.test.ts", "language": "typescript", "file_size": 3557, "cut_index": 614, "middle_length": 229 }
[shouldInsertScript, toggleScript] = React.useReducer((b) => !b, false) const scriptAsyncTrue = <script src="/test-async-true.js" async></script> const scriptAsyncFalse = ( <script src="/test-async-false.js" async={false}></script> ) return ( <div> <Head> {/* this will not render */} ...
/} <meta name="empty-content" content={undefined} /> {/* allow duplicates for specific tags */} <meta property="article:tag" content="tag1" key="tag1key" /> <meta property="article:tag" content="tag2" key="tag2key" />
evice-width" /> {/* this will override the default */} <meta name="viewport" content="width=device-width,initial-scale=1" /> <meta content="my meta" /> {/* this will not render the content prop *
{ "filepath": "test/development/pages-dir/client-navigation/fixture/pages/head.js", "language": "javascript", "file_size": 5360, "cut_index": 716, "middle_length": 229 }
next-test-utils' import fs from 'fs-extra' import path from 'path' const READ_ONLY_PERMISSIONS = 0o444 const READ_WRITE_PERMISSIONS = 0o644 let pageHello = 'pages/hello.js' describe('Read-only source HMR', () => { const { next } = nextTestSetup({ files: path.join(__dirname, '..'), skipStart: true, env:...
content: string | undefined) => string | undefined, runWithTempContent: (context: { newFile: boolean }) => Promise<void> ) { const filePath = path.join(next.testDir, filename) const exists = await fs .access(filePath) .then(() =>
AL: '500', }, }) beforeAll(async () => { await fs.chmod(path.join(next.testDir, pageHello), READ_ONLY_PERMISSIONS) await next.start() }) async function patchFileReadOnly( filename: string, content: (
{ "filepath": "test/development/read-only-source-hmr/test/index.test.ts", "language": "typescript", "file_size": 4121, "cut_index": 614, "middle_length": 229 }
port { nextTestSetup } from 'e2e-utils' import { retry } from 'next-test-utils' import { join } from 'path' describe('Has CSS Module in computed styles in Development', () => { const { next } = nextTestSetup({ files: join(__dirname, 'fixtures', 'dev-module'), }) it('should have CSS for page', async () => { ...
ay: 500, }) it('should update CSS color without remounting <input>', async () => { const browser = await next.browser('/') const desiredText = 'hello world' await browser.elementById('text-input').type(desiredText) expect(await browse
olor).toMatchInlineSnapshot(`"rgb(255, 0, 0)"`) }) }) describe('Can hot reload CSS Module without losing state', () => { const { next } = nextTestSetup({ files: join(__dirname, 'fixtures', 'hmr-module'), patchFileDel
{ "filepath": "test/development/css-features/css-modules-support.test.ts", "language": "typescript", "file_size": 1820, "cut_index": 537, "middle_length": 229 }
owser.elementByCss('[data-nextjs-error-code]') const code = await errorCode.getAttribute('data-nextjs-error-code') expect(code).toBe('E40') }) it('sends feedback when clicking helpful button', async () => { const feedbackRequests: string[] = [] const browser = await next.browser('/known-client-erro...
Mark as helpful' }).click() expect( await browser .getByRole('region', { name: 'Error feedback' }) .getByRole('status') .textContent() ).toEqual('Thanks for your feedback!') expect(feedbackRequests).toEqual([
+ url.search) route.fulfill({ status: 204, body: 'No Content' }) }) }, }) await browser.elementByCss('button').click() // clicked "break on client" await browser.getByRole('button', { name: '
{ "filepath": "test/development/error-overlay/index.test.tsx", "language": "tsx", "file_size": 11092, "cut_index": 921, "middle_length": 229 }
retry } from 'next-test-utils' describe('Invalid revalidate values', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should not show error initially', async () => { const html = await next.render('/ssg') expect(html).toContain('a-ok') }) it('should not show error for false rev...
w error for true revalidate value', async () => { const originalContent = await next.readFile('pages/ssg.js') await next.patchFile( 'pages/ssg.js', originalContent.replace('revalidate: 1', 'revalidate: true') ) await retry(asyn
validate: false') ) await retry(async () => { const html = await next.render('/ssg') expect(html).toContain('a-ok') }) await next.patchFile('pages/ssg.js', originalContent) }) it('should not sho
{ "filepath": "test/development/invalid-revalidate-values/invalid-revalidate-values.test.ts", "language": "typescript", "file_size": 2907, "cut_index": 563, "middle_length": 229 }
or } from 'next-test-utils' import path from 'path' import { nextTestSetup } from 'e2e-utils' describe('Client navigation on error pages', () => { const { next } = nextTestSetup({ files: path.join(__dirname, 'fixture'), env: { TEST_STRICT_NEXT_HEAD: String(true), }, }) it('should not reload wh...
const html = await browser.eval('document.documentElement.innerHTML') expect(status).toBe(404) expect(html).toContain('This page could not be found') expect(html).toContain('404') }) describe('with 404 pages', () => { it('should
w.hello = true') // wait on-demand-entries timeout since it can trigger // reloading non-stop for (let i = 0; i < 15; i++) { expect(await browser.eval('window.hello')).toBe(true) await waitFor(1000) }
{ "filepath": "test/development/pages-dir/client-navigation/error-pages.test.ts", "language": "typescript", "file_size": 2915, "cut_index": 563, "middle_length": 229 }
on rendering <Head />', () => { const { next } = nextTestSetup({ files: path.join(__dirname, 'fixture'), }) function render( pathname: Parameters<typeof renderViaHTTP>[1], query?: Parameters<typeof renderViaHTTP>[2] ) { return renderViaHTTP(next.appPort, pathname, query) } it('should handl...
="utf-8" data-next-head=""/>') expect(html).toContain('next-head, but only once.') }) test('header renders default viewport', async () => { const html = await render('/default-head') expect(html).toContain( '<meta name="viewport" con
() expect(value).toBe(false) }) // default-head contains an empty <Head />. test('header renders default charset', async () => { const html = await render('/default-head') expect(html).toContain('<meta charSet
{ "filepath": "test/development/pages-dir/client-navigation/rendering-head.test.ts", "language": "typescript", "file_size": 8871, "cut_index": 716, "middle_length": 229 }
retry } from 'next-test-utils' describe('typescript-native-preview', () => { const { next } = nextTestSetup({ files: { 'app/layout.tsx': ` import { ReactNode } from 'react' export default function Root({ children }: { children: ReactNode }) { return ( <html> ...
, noEmit: true, esModuleInterop: true, module: 'esnext', moduleResolution: 'bundler', resolveJsonModule: true, isolatedModules: true, jsx: 'preserve', incremental: true,
`, 'tsconfig.json': JSON.stringify({ compilerOptions: { target: 'ES2017', lib: ['dom', 'dom.iterable', 'esnext'], allowJs: true, skipLibCheck: true, strict: true
{ "filepath": "test/development/typescript-native-preview/index.test.ts", "language": "typescript", "file_size": 2351, "cut_index": 563, "middle_length": 229 }
git repository is dirty[^\n]*\n?/g, '') .replace(/.*at async handler .*next-route-loader.*/g, '') .replace(/.*at async handleResponse.*/g, '') .replace(/.*at async doRender \(.*/g, '') .split(/\n/) .filter((item) => { const trimmed = item.trim() if (!trimmed) return false ...
rn false // Drop compiling indicator lines (e.g. "○ Compiling /gsp ..."). if (trimmed.startsWith('○ ')) return false return true }) .join('\n') } it('should show server-side error for gsp page correctly', async () =
rts ready (see // `logExperimentalInfo` in `start-server.ts`), so it can race // with the test capturing `cliOutputIdx`. if (trimmed.startsWith('- ')) return false if (/^[✓⚠△] /.test(trimmed)) retu
{ "filepath": "test/development/server-side-dev-errors/server-side-dev-errors.test.ts", "language": "typescript", "file_size": 15238, "cut_index": 921, "middle_length": 229 }
t } = nextTestSetup({ files: path.join(__dirname, 'fixture'), }) it.each([true, false])( 'should handle boolean async prop in next/head client-side: %s', async (bool) => { const browser = await next.browser('/head') const value = await browser.eval( `document.querySelector('script[s...
wser.eval('window.__test_defer_executions'))).toBe(1) await browser.elementByCss('#reverseScriptOrder').click() await waitFor(2000) expect(Number(await browser.eval('window.__test_async_executions'))).toBe(1) expect(Number(await browser.e
> { const browser = await next.browser('/head') await browser.waitForElementByCss('h1') await waitFor(2000) expect(Number(await browser.eval('window.__test_async_executions'))).toBe(1) expect(Number(await bro
{ "filepath": "test/development/pages-dir/client-navigation/head.test.ts", "language": "typescript", "file_size": 5455, "cut_index": 716, "middle_length": 229 }
retry } from 'next-test-utils' describe('_app/_document add HMR', () => { const { next } = nextTestSetup({ files: __dirname, }) // TODO: figure out why test fails. it.skip('should HMR when _app is added', async () => { const browser = await next.browser('/') try { const html = await browser....
) await retry(async () => { const html = await browser.eval('document.documentElement.innerHTML') expect(html).toContain('custom _app') expect(html).toContain('index page') }) } finally { await next.delet
` export default function MyApp({ Component, pageProps }) { return ( <> <p>custom _app</p> <Component {...pageProps} /> </> ) } `
{ "filepath": "test/development/app-document-add-hmr/app-document-add-hmr.test.ts", "language": "typescript", "file_size": 2844, "cut_index": 563, "middle_length": 229 }
tTestSetup({ files: path.join(__dirname, 'fixture'), env: { TEST_STRICT_NEXT_HEAD: String(true), }, }) describe('when hash changes', () => { describe('check hydration mis-match', () => { it('should not have hydration mis-match for hash link', async () => { const browser = await ...
not run getInitialProps', async () => { const browser = await next.browser('/nav/hash-changes') await browser.elementByCss('#via-link').click() await retry(async () => { expect(await browser.elementByCss('p').text()).toB
age) if (log.message.includes('Warning: Prop')) { found = true } }) expect(found).toEqual(false) }) }) describe('when hash change via Link', () => { it('should
{ "filepath": "test/development/pages-dir/client-navigation/url-hash.test.ts", "language": "typescript", "file_size": 8248, "cut_index": 716, "middle_length": 229 }
t-test-utils' import path from 'path' import { nextTestSetup } from 'e2e-utils' describe('Client Navigation', () => { const { next } = nextTestSetup({ files: path.join(__dirname, 'fixture'), env: { TEST_STRICT_NEXT_HEAD: String(true), }, }) describe('with <a/> tag inside the <Link />', () => {...
c () => { const browser = await next.browser('/nav') await browser .elementByCss('#increase') .click() .elementByCss('#target-link') .click() await waitFor(1000) const counterText = await browser.e
.waitForElementByCss('.nav-home') .elementByCss('p') .text() expect(text).toBe('This is the home.') await browser.close() }) it('should not navigate if the <a/> tag has a target', asyn
{ "filepath": "test/development/pages-dir/client-navigation/anchor-in-link.test.ts", "language": "typescript", "file_size": 2104, "cut_index": 563, "middle_length": 229 }
tureBuffer, readFixtureText, } from './utils' describe('metadata-files-static-output-dynamic-route', () => { const { next, skipped } = nextTestSetup({ files: __dirname, }) if (skipped) { return } it('should have correct link tags for dynamic page with static placeholder', async () => { const ...
}, { "href": "/dynamic/-/icon.png", "rel": "icon", "type": "image/png", }, { "href": "/favicon.ico", "rel": "icon", "type": "image/x-icon", }, {
(await getCommonMetadataHeadTags(browser)).toMatchInlineSnapshot(` { "links": [ { "href": "/dynamic/-/apple-icon.png", "rel": "apple-touch-icon", "type": "image/png",
{ "filepath": "test/e2e/app-dir/metadata-static-file/metadata-static-file-dynamic-route.test.ts", "language": "typescript", "file_size": 4368, "cut_index": 614, "middle_length": 229 }
readFixtureText, } from './utils' describe('metadata-files-static-output-group-route', () => { const { next, skipped } = nextTestSetup({ files: __dirname, }) if (skipped) { return } it('should have correct link tags for group page', async () => { const browser = await next.browser('/group') ...
"rel": "icon", "type": "image/png", }, { "href": "/manifest.json", "rel": "manifest", }, ], "metas": [ { "name": "twitter:card", }, {
"image/x-icon", }, { "href": "/group/apple-icon-131tc6.png", "rel": "apple-touch-icon", "type": "image/png", }, { "href": "/group/icon-131tc6.png",
{ "filepath": "test/e2e/app-dir/metadata-static-file/metadata-static-file-group-route.test.ts", "language": "typescript", "file_size": 3412, "cut_index": 614, "middle_length": 229 }
retry } from 'next-test-utils' describe('app-dir action progressive enhancement', () => { const { next } = nextTestSetup({ files: __dirname, dependencies: { nanoid: '4.0.1', 'server-only': 'latest', }, }) it('should support formData and redirect without JS', async () => { let respons...
yId('name').type('test') await browser.elementById('submit').click() await retry(async () => { expect(await browser.url()).toBe( `${next.url}/header?name=test&hidden-info=hi` ) }) expect(responseCode).toBe(303) })
const url = new URL(response.url()) const status = response.status() if (url.pathname.includes('/server')) { responseCode = status } }) }, }) await browser.elementB
{ "filepath": "test/e2e/app-dir/actions/app-action-progressive-enhancement.test.ts", "language": "typescript", "file_size": 2263, "cut_index": 563, "middle_length": 229 }
import { accountForOverhead } from './account-for-overhead' import { join } from 'path' const CONFIG_ERROR = 'Server Actions Size Limit must be a valid number or filesize format larger than 1MB' describe('app-dir action size limit invalid config', () => { const { next, isNextStart, isNextDeploy, skipped } = next...
gs.push(stripAnsi(log.trim())) } next.on('stdout', onLog) next.on('stderr', onLog) }) afterEach(async () => { logs.length = 0 await next.stop() }) if (isNextStart) { it('should error if serverActions.bodySizeLimit config
{}, skipStart: true, dependencies: { nanoid: '4.0.1', 'server-only': 'latest', }, }) if (skipped) return const logs: string[] = [] beforeAll(() => { const onLog = (log: string) => { lo
{ "filepath": "test/e2e/app-dir/actions/app-action-size-limit-invalid.test.ts", "language": "typescript", "file_size": 8540, "cut_index": 716, "middle_length": 229 }
').error(`Invalid action entry ${item}`, err) throw err } } for (const item in referenceManifest.edge) { try { const itemInfo = referenceManifest.edge[item] foundExportNames.push(itemInfo.exportedName) expect(itemInfo.filename).toBeString() ...
('should handle action correctly with middleware rewrite', async () => { const browser = await next.browser('/rewrite-to-static-first') let actionRequestStatus: number | undefined browser.on('response', async (res) => { if ( res.
foundExportNames).toContain('setCookie') expect(foundExportNames).toContain('getCookie') expect(foundExportNames).toContain('getHeader') expect(foundExportNames).toContain('setCookieWithMaxAge') }) } it
{ "filepath": "test/e2e/app-dir/actions/app-action.test.ts", "language": "typescript", "file_size": 65137, "cut_index": 2151, "middle_length": 229 }
s page is forced into dynamic rendering because POST requests to // a static/ISR page will cause an error when deployed. export const dynamic = 'force-dynamic' export default function Home() { return ( <main id="redirect-page"> <h1>POST /api-redirect (`redirect()`)</h1> <form action="/redirects/api-r...
7</h1> <form action="/redirects/api-redirect-307" method="POST"> <input type="submit" value="Submit" id="submit-api-redirect-307" /> </form> <h1>POST /api-reponse-redirect-308</h1> <form action="/redirects/api-redirect-308"
tion="/redirects/api-redirect-permanent" method="POST"> <input type="submit" value="Submit" id="submit-api-redirect-permanent" /> </form> <h1>POST /api-reponse-redirect-30
{ "filepath": "test/e2e/app-dir/actions/app/redirects/page.js", "language": "javascript", "file_size": 1126, "cut_index": 518, "middle_length": 229 }
mport { cookies } from 'next/headers' import { redirect } from 'next/navigation' export default async function Page({ searchParams }) { const foo = (await cookies()).get('foo') const bar = (await cookies()).get('bar') return ( <div> <h1> foo={foo ? foo.value : ''}; bar={bar ? bar.value : ''} ...
? ''}</h2> <form action={async () => { 'use server' redirect('/redirects/action-redirect/redirect-target?baz=1') }} > <button type="submit" id="redirect-with-search-params"> Redirect with Se
s/action-redirect/redirect-target') }} > <button type="submit" id="redirect-with-cookie-mutation"> Set Cookies and Redirect </button> </form> <h2>baz={(await searchParams).baz ?
{ "filepath": "test/e2e/app-dir/actions/app/redirects/action-redirect/page.js", "language": "javascript", "file_size": 1058, "cut_index": 513, "middle_length": 229 }
rt Link from 'next/link' import { cookies } from 'next/headers' import RedirectClientComponent from './client' export default async function Page() { const cookie = (await cookies()).get('random') const data = await fetch( 'https://next-data-api-endpoint.vercel.app/api/random?page', { next: { revali...
ext"> {data} </span>{' '} <span> <Link href="/revalidate-2" id="another"> /revalidate-2 </Link> </span> </p> <p> revalidate (tags: thankyounext, justputit):{' '}
lidate: 3600, tags: ['thankyounext', 'justputit'] }, } ).then((res) => res.text()) return ( <> <h1 id="title">revalidate</h1> <p> {' '} revalidate (tags: thankyounext): <span id="thankyoun
{ "filepath": "test/e2e/app-dir/actions/app/revalidate/page.js", "language": "javascript", "file_size": 3232, "cut_index": 614, "middle_length": 229 }
lient' import { useTransition, useState } from 'react' import { badAction, getServerData } from './actions' export default function Component() { const [isPending, startTransition] = useTransition() const [wasSubmitted, setWasSubmitted] = useState(false) return ( <> {wasSubmitted && <div id="submitted-...
</button> <button id="bad-action" disabled={isPending} onClick={() => { startTransition(() => { badAction() .catch(() => { console.log('error caught in user code')
.catch(() => { console.log('error caught in user code') }) .finally(() => { setWasSubmitted(true) }) }) }} > Submit Action
{ "filepath": "test/e2e/app-dir/actions/app/catching-error/page.tsx", "language": "tsx", "file_size": 1196, "cut_index": 518, "middle_length": 229 }
n Counter({ inc, dec, double, slowInc }) { const [count, setCount] = useState(0) return ( <div> <h1 id="count">{count}</h1> <button id="inc" onClick={async () => { const newCount = await inc(count) setCount(newCount) }} > +1 </button> ...
{async () => { const newCount = await dec(count) setCount(newCount) }} > -1 </button> <button id="double" onClick={async () => { const newCount = await double(count)
ton> <button id="dec" onClick=
{ "filepath": "test/e2e/app-dir/actions/app/server/counter.js", "language": "javascript", "file_size": 972, "cut_index": 582, "middle_length": 52 }
nd } from 'next/navigation' async function action(formData) { 'use server' redirect( '/header?name=' + formData.get('name') + '&hidden-info=' + formData.get('hidden-info') ) } async function nowhere() { 'use server' notFound() } async function here() { 'use server' // nothing } a...
' redirect('/header?result=' + (a + b + c)) } return ( <> <hr /> <form action={action}> <input type="text" name="hidden-info" defaultValue="hi" hidden /> <input type="text" name="name" id="name" required />
async function add(a, formData) { 'use server' // Bind variable, closure variable, and argument. redirect('/header?result=' + (a + b + Number(formData.get('n')))) } async function add3(a, b, c) { 'use server
{ "filepath": "test/e2e/app-dir/actions/app/server/form.js", "language": "javascript", "file_size": 1974, "cut_index": 537, "middle_length": 229 }
mport Counter from './counter' import Form from './form' import ClientForm from './client-form' import dec, { slowInc } from './actions' import { log } from './actions-2' import { inc } from './actions-3' export default function Page() { const two = { value: 2 } // https://github.com/vercel/next.js/issues/58463 ...
return x * two.value } // Wrong answer return 42 }} /> <Form /> <ClientForm /> <form> <button id="log" formAction={log}> log </button> </form> </> )
'你好') {
{ "filepath": "test/e2e/app-dir/actions/app/server/page.js", "language": "javascript", "file_size": 793, "cut_index": 513, "middle_length": 14 }
ort default function UI({ getCookie, getHeader, setCookie, setCookieAndRedirect, getAuthedUppercase, }) { const [result, setResult] = useState('') return ( <div> <h1>{result}</h1> <button id="cookie" onClick={async () => { // set cookie const random = M...
setResult( random + ':' + res.value + ':' + document.cookie.match(/random-server=([^;]+)/)?.[1] ) }} > setCookie </button> <button
</button> <button id="setCookie" onClick={async () => { // set cookie on server side const random = Math.random() const res = await setCookie('random-server', random)
{ "filepath": "test/e2e/app-dir/actions/app/header/ui.js", "language": "javascript", "file_size": 2307, "cut_index": 563, "middle_length": 229 }
e, getHeader, setCookie } from '../../actions' const getReferrer = getHeader.bind(null, 'referer') const setTestCookie = setCookie.bind(null, 'test', '42') const getTestCookie = getCookie.bind(null, 'test') export default function Page() { const [referer, getReferrerAction] = useActionState(getReferrer, null) co...
="get-referer">Get Referer</button> </form> <form action={getTestCookieAction}> <p id="cookie">{cookie?.value}</p> <button id="set-cookie" formAction={setTestCookie}> Set Cookie </button> <button id="ge
eferer">{referer ?? '<null>'}</p> <button id
{ "filepath": "test/e2e/app-dir/actions/app/header/node/form/page.tsx", "language": "tsx", "file_size": 948, "cut_index": 582, "middle_length": 52 }
Page() { const data1 = await fetch( 'https://next-data-api-endpoint.vercel.app/api/random?a', { next: { tags: ['thankyounext'] }, } ).then((res) => res.text()) const data2 = await fetch( 'https://next-data-api-endpoint.vercel.app/api/random?b', { next: { tags: ['justputit'] }, ...
an id="justputit">{data2}</span> </p> <form> <button id="revalidate" formAction={async () => { 'use server' updateTag('thankyounext') updateTag('justputit') }} >
<p> revalidate (tags: justputit): <sp
{ "filepath": "test/e2e/app-dir/actions/app/revalidate-multiple/page.js", "language": "javascript", "file_size": 970, "cut_index": 582, "middle_length": 52 }
client' import { useTransition } from 'react' import { action } from './actions' export default function Page() { const [, startTransition] = useTransition() return ( <main> <p> This button will call a server action and pass something unserializable like a class instance. We expect this...
Submit </button> <button id="submit-transition" onClick={async () => { startTransition(() => action()) }} > Action that triggers an error </button> </main> ) } class Foo { va
}} >
{ "filepath": "test/e2e/app-dir/actions/app/error-handling/page.js", "language": "javascript", "file_size": 798, "cut_index": 517, "middle_length": 14 }
mport { accountForOverhead } from '../../account-for-overhead' async function action(formData) { 'use server' const payload = formData.get('payload').toString() console.log('size =', payload.length) } export default function Page() { return ( <> <form action={action}> <input type="...
</button> </form> <form action={action}> <input type="hidden" name="payload" value={'a'.repeat(accountForOverhead(3))} /> <button type="submit" id="size-3mb"> SUBMIT 3mb
> <form action={action}> <input type="hidden" name="payload" value={'a'.repeat(accountForOverhead(2))} /> <button type="submit" id="size-2mb"> SUBMIT 2mb
{ "filepath": "test/e2e/app-dir/actions/app/form/page.js", "language": "javascript", "file_size": 1037, "cut_index": 513, "middle_length": 229 }
eState } from 'react' import double, { inc, dec, redirectAction, getHeaders, renamed, slowInc, } from './actions' import { test } from './actions-lib' export default function Counter() { const [count, setCount] = useState(0) return ( <div> <h1 id="count">{count}</h1> <button id...
id="dec" onClick={async () => { const newCount = await dec(count) setCount(newCount) }} > -1 </button> <button id="double" onClick={async () => { const newCoun
+1 </button> <button id="slow-inc" onClick={async () => { const newCount = await slowInc(count) setCount(newCount) }} > +1 (Slow) </button> <button
{ "filepath": "test/e2e/app-dir/actions/app/client/page.js", "language": "javascript", "file_size": 1533, "cut_index": 537, "middle_length": 229 }
ort { redirectAction } from '../actions' export default function Page() { return ( <div> <form> <button id="redirect-relative" formAction={() => redirectAction('/redirect-target')} > redirect relative </button> </form> <form> <button...
> </form> <form> <button id="redirect-absolute" formAction={() => redirectAction(location.origin + '/redirect-target') } > redirect internal with domain </button>
> redirect external </button
{ "filepath": "test/e2e/app-dir/actions/app/client/redirects/page.js", "language": "javascript", "file_size": 863, "cut_index": 529, "middle_length": 52 }
eState } from 'react' import double, { inc, dec, redirectAction, getHeaders } from '../actions' export default function Counter() { const [count, setCount] = useState(0) return ( <div> <h1>{count}</h1> <button id="inc" onClick={async () => { const newCount = await inc(cou...
*2 </button> <form> <button id="redirect-relative" formAction={() => redirectAction('/redirect-target')} > redirect to a relative URL </button> </form> <form> <but
setCount(newCount) }} > -1 </button> <button id="double" onClick={async () => { const newCount = await double(count) setCount(newCount) }} >
{ "filepath": "test/e2e/app-dir/actions/app/client/edge/page.js", "language": "javascript", "file_size": 1712, "cut_index": 537, "middle_length": 229 }
mport { updateTag } from 'next/cache' import { cookies } from 'next/headers' import Link from 'next/link' export default async function Page() { const randomCookie = (await cookies()).get('random') const data = await fetch( 'https://next-data-api-endpoint.vercel.app/api/random?page', { next: { revali...
'use server' updateTag('thankyounext') }} > revalidate thankyounext </button> </form> <p> random cookie:{' '} <span id="random-cookie"> {JSON.stringify({ cookie: random
</Link> <p> {' '} revalidate (tags: thankyounext): <span id="thankyounext">{data}</span> </p> <form> <button id="revalidate-tag" formAction={async () => {
{ "filepath": "test/e2e/app-dir/actions/app/revalidate-2/page.js", "language": "javascript", "file_size": 1050, "cut_index": 513, "middle_length": 229 }