prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
rated SignedSource<<afaeba3a661c4bb0d2a399327c82d32b>> * @lightSyntaxTransform * @nogrep */ /* tslint:disable */ /* eslint-disable */ // @ts-nocheck import { ConcreteRequest, Query } from 'relay-runtime' export type pagesAQuery$variables = {} export type pagesAQueryVariables = pagesAQuery$variables export type pag...
Definitions: [], kind: 'Fragment', metadata: null, name: 'pagesAQuery', selections: v0 /*: any*/, type: 'Query', abstractKey: null, }, kind: 'Request', operation: { argumentDefinitions: [], kind:
const node: ConcreteRequest = (function () { var v0 = [ { alias: null, args: null, kind: 'ScalarField', name: 'greeting', storageKey: null, }, ] return { fragment: { argument
{ "filepath": "test/e2e/relay-graphql-swc-multi-project/project-a/__generated__/pagesAQuery.graphql.ts", "language": "typescript", "file_size": 1393, "cut_index": 524, "middle_length": 229 }
nvironment, FetchFunction, fetchQuery, graphql, Network, RecordSource, Store, } from 'relay-runtime' import { GetServerSideProps } from 'next' import { pagesAQuery } from '../__generated__/pagesAQuery.graphql' type Props = { greeting: string } export default function Index({ greeting }: Props) { return ...
variables, }), }) return await response.json() } } export const getServerSideProps: GetServerSideProps = async ({ req }) => { const environment = new Environment({ store: new Store(new RecordSource({}), {}), network: Network
/${host}/api/query` : `/api/query` const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: params.text,
{ "filepath": "test/e2e/relay-graphql-swc-multi-project/project-a/pages/index.tsx", "language": "tsx", "file_size": 1405, "cut_index": 524, "middle_length": 229 }
import { fetchViaHTTP } from 'next-test-utils' import { FileRef, nextTestSetup } from 'e2e-utils' describe('Middleware Responses', () => { const { next } = nextTestSetup({ files: { pages: new FileRef(join(__dirname, '../app/pages')), 'middleware.js': new FileRef(join(__dirname, '../app/middleware.js'...
', ]) }) it(`${label}should not fail when returning a stream`, async () => { const res = await fetchViaHTTP(next.url, `${locale}/stream-a-response`) expect(res.status).toBe(200) if (!(global as any).isNextDeploy) {
{label}responds with multiple cookies`, async () => { const res = await fetchViaHTTP(next.url, `${locale}/two-cookies`) expect(res.headers.raw()['set-cookie']).toEqual([ 'foo=chocochip', 'bar=chocochip
{ "filepath": "test/e2e/middleware-responses/test/index.test.ts", "language": "typescript", "file_size": 2905, "cut_index": 563, "middle_length": 229 }
se this trick to fool static analysis at build time, so we can build a // middleware that will return a body at run time, and check it is disallowed. class MyResponse extends Response {} export async function middleware(request, ev) { const { readable, writable } = new TransformStream() const url = request.nextUrl...
an append to this value if (url.searchParams.get('append-me') === 'true') { next.headers.append('x-append-me', 'top') } // Ensure deep can append to this value if (url.searchParams.get('cookie-me') === 'true') { next.headers.append('set-co
/_next/static/__BUILD_ID')) { return NextResponse.next() } // Header based on query param if (url.searchParams.get('nested-header') === 'true') { next.headers.set('x-nested-header', 'valid') } // Ensure deep c
{ "filepath": "test/e2e/middleware-responses/app/middleware.js", "language": "javascript", "file_size": 2050, "cut_index": 563, "middle_length": 229 }
nk' export default function Home({ message }) { return ( <div> <p className="title">Hello {message}</p> <Link href="/stream-a-response">Stream a response</Link> <div /> <Link href="/stream-long">Stream a long response</Link> <Link href="/stream-end-stream">Test streaming after respo...
d middleware effect) </Link> <div /> <Link href="/body-end-header">Respond with body, end, set a header</Link> <div /> <Link href="/body-end-body"> Respond with body, end, send another body </Link> <div />
Redirect to Google and attempt to stream after </Link> <div /> <Link href="/header">Respond with a header</Link> <div /> <Link href="/header?nested-header=true"> Respond with 2 headers (neste
{ "filepath": "test/e2e/middleware-responses/app/pages/index.js", "language": "javascript", "file_size": 1512, "cut_index": 537, "middle_length": 229 }
t warningMessage = "Warning: 'dev' is not a boolean which could introduce unexpected behavior. https://nextjs.org/docs/messages/invalid-server-options" describe('Invalid server options', () => { test('next() called with no parameters should throw error', () => { expect(() => // @ts-expect-error nex...
eter should throw error', () => { expect(() => next(null)).toThrow( 'The server has not been instantiated properly. https://nextjs.org/docs/messages/invalid-server-options' ) }) test('next() called with dev as string should send warning'
uld throw error', () => { expect(() => next(undefined)).toThrow( 'The server has not been instantiated properly. https://nextjs.org/docs/messages/invalid-server-options' ) }) test('next() called with null param
{ "filepath": "test/e2e/invalid-server-options/invalid-server-options.test.ts", "language": "typescript", "file_size": 2226, "cut_index": 563, "middle_length": 229 }
getStaticProps() { return { props: { world: 'world', time: new Date().getTime() }, // bad-prop revalidate: 2, } } const Page = ({ world, time }) => { return ( <> <p>hello {world}</p> <span>time: {time}</span> <Link href="/non-json/[p]" as="/non-json/1" id="non-json"> to...
mic </Link> <Link href="/blog/[post]" as="/blog/post-100" id="broken-post"> to broken </Link> <Link href="/blog/[post]" as="/blog/post-999" prefetch={false} id="broken-at-first-post" >
" id="something"> to something </Link> <br /> <Link href="/normal" id="normal"> to normal </Link> <br /> <Link href="/blog/[post]" as="/blog/post-1" id="post-1"> to dyna
{ "filepath": "test/e2e/prerender/pages/index.js", "language": "javascript", "file_size": 2749, "cut_index": 563, "middle_length": 229 }
t Link from 'next/link' import { useRouter } from 'next/router' export async function getStaticPaths() { return { paths: ['/fallback-true/first'], fallback: true, } } export async function getStaticProps({ params }) { return { props: { params, hello: 'world', post: params.slug, ...
<> <p>Post: {post}</p> <span>time: {time}</span> <div id="params">{JSON.stringify(params)}</div> <div id="query">{JSON.stringify(useRouter().query)}</div> <Link href="/" id="home"> to home </Link> </> ) }
) { return <p>hi fallback</p> } return (
{ "filepath": "test/e2e/prerender/pages/fallback-true/[slug].js", "language": "javascript", "file_size": 826, "cut_index": 517, "middle_length": 52 }
React from 'react' import Link from 'next/link' import { useRouter } from 'next/router' import 'firebase/firestore' export async function getStaticPaths() { return { paths: [ '/blog/post-1', { params: { post: 'post-2' } }, '/blog/[post3]', '/blog/post-4', '/blog/post.1', '/bl...
try again..') } } return { props: { params, post: params.post, time: (await import('perf_hooks')).performance.now(), }, revalidate: 10, } } export default ({ post, time, params }) => { return ( <> <p>Po
(resolve) => { setTimeout(() => resolve(), 1000) }) } if (params.post === 'post-100') { throw new Error('such broken..') } if (params.post === 'post-999') { if (++counter < 6) { throw new Error('
{ "filepath": "test/e2e/prerender/pages/blog/[post]/index.js", "language": "javascript", "file_size": 1244, "cut_index": 518, "middle_length": 229 }
arams: { slug } }) { if (slug[0] === 'delayby3s') { await new Promise((resolve) => setTimeout(resolve, 3000)) } return { props: { slug, time: Date.now(), }, revalidate: 1, } } export async function getStaticPaths() { return { paths: [ { params: { slug: ['first'] } }, ...
false, } } export default function Page({ slug, time }) { // Important to not check for `slug` existence (testing that build does not // render fallback version and error) return ( <> <p id="catchall">Hi {slug.join(' ')}</p> <p id=
: ['[third]', '[fourth]'] } }, ], fallback:
{ "filepath": "test/e2e/prerender/pages/catchall-explicit/[...slug].js", "language": "javascript", "file_size": 990, "cut_index": 582, "middle_length": 52 }
mport React from 'react' import Link from 'next/link' import { useRouter } from 'next/router' import fs from 'node:fs/promises' export async function getStaticPaths() { return { paths: [], fallback: true, } } export async function getStaticProps({ params }) { while (true) { try { await fs.stat...
i fallback</p> } return ( <> <p>Post: {post}</p> <span>time: {time}</span> <div id="params">{JSON.stringify(params)}</div> <div id="query">{JSON.stringify(useRouter().query)}</div> <Link href="/" id="home"> to
: params.slug, random: Math.random(), time: (await import('perf_hooks')).performance.now(), }, revalidate: 1, } } export default ({ post, time, params }) => { if (useRouter().isFallback) { return <p>h
{ "filepath": "test/e2e/prerender/pages/fallback-only/[slug].js", "language": "javascript", "file_size": 1032, "cut_index": 513, "middle_length": 229 }
ter } from 'next/router' export async function getStaticPaths() { return { paths: [{ params: { slug: 'a' } }, { params: { slug: 'b' } }], fallback: 'blocking', } } export async function getStaticProps({ params }) { await new Promise((resolve) => setTimeout(resolve, 1000)) return { props: { ...
llback) { return <p>hi fallback</p> } return ( <> <p>Post: {post}</p> <span>time: {time}</span> <div id="params">{JSON.stringify(params)}</div> <div id="query">{JSON.stringify(useRouter().query)}</div> <Link href=
({ post, time, params }) => { if (useRouter().isFa
{ "filepath": "test/e2e/prerender/pages/blocking-fallback-some/[slug].js", "language": "javascript", "file_size": 949, "cut_index": 582, "middle_length": 52 }
t path from 'path' import React from 'react' import Link from 'next/link' import { useRouter } from 'next/router' export async function getStaticPaths() { return { paths: [ { params: { slug: 'test-errors-1' }, }, { params: { slug: 'lots-of-data' }, }, ], fallback: ...
) if (data.trim() === 'yes') { throw new Error('throwing error for /blocking-fallback/' + params.slug) } } } await new Promise((resolve) => setTimeout(resolve, 1000)) console.log(`getStaticProps ${params.slug}`) const res
in(''), }, } } if (params.slug.startsWith('test-errors')) { const errorFile = path.join(process.cwd(), 'error.txt') if (fs.existsSync(errorFile)) { const data = await fs.readFileSync(errorFile, 'utf8'
{ "filepath": "test/e2e/prerender/pages/blocking-fallback/[slug].js", "language": "javascript", "file_size": 1768, "cut_index": 537, "middle_length": 229 }
React from 'react' import Link from 'next/link' import { useRouter } from 'next/router' export async function getStaticPaths() { return { paths: [ { params: { slug: '404-on-manual-revalidate' }, }, ], fallback: 'blocking', } } export async function getStaticProps({ params }) { a...
idate: false, } } export default ({ post, time, params }) => { if (useRouter().isFallback) { return <p>hi fallback</p> } return ( <> <p>Post: {post}</p> <span id="time">time: {time}</span> <div id="params">{JSON.stringif
notFound: true, } } } return { props: { params, hello: 'world', post: params.slug, random: Math.random(), time: (await import('perf_hooks')).performance.now(), }, reval
{ "filepath": "test/e2e/prerender/pages/blocking-fallback-once/[slug].js", "language": "javascript", "file_size": 1160, "cut_index": 518, "middle_length": 229 }
check } from 'next-test-utils' import stripAnsi from 'strip-ansi' describe('fetch failures have good stack traces in edge runtime', () => { const { next, isNextStart, isNextDev, skipped } = nextTestSetup({ files: __dirname, // don't have access to runtime logs on deploy skipDeployment: true, }) if (...
tStart) { // eslint-disable-next-line jest/no-standalone-expect expect(next.cliOutput.slice(outputIndex)).toMatch( /at.+\/pages\/api\/unknown-domain.js/ ) } else if (isNextDev) { // eslint-disable-next-line j
( 'when awaiting `fetch` using an unknown domain, stack traces are preserved', async () => { const outputIndex = next.cliOutput.length const browser = await next.browser('/api/unknown-domain') if (isNex
{ "filepath": "test/e2e/fetch-failures-have-good-stack-traces-in-edge-runtime/fetch-failures-have-good-stack-traces-in-edge-runtime.test.ts", "language": "typescript", "file_size": 2803, "cut_index": 563, "middle_length": 229 }
default.js': ` export default (req, res) => res.json({ body: req.body }) `, 'pages/api/size_limit_5kb.js': ` export const config = { api: { bodyParser: { sizeLimit: '5kb' } } } export default (req, res) => res.json({ body: req.body }) `, 'pages/api/size_limit_5mb.js': ` ...
? Buffer.from(chunk) : chunk) } return Buffer.concat(chunks) } export default async (req, res) => { const buf = await buffer(req) const rawBody = buf.toString('utf8'); res.json({ rawBody,
export const config = { api: { bodyParser: false } } async function buffer(readable) { const chunks = [] for await (const chunk of readable) { chunks.push(typeof chunk === 'string'
{ "filepath": "test/e2e/middleware-fetches-with-body/index.test.ts", "language": "typescript", "file_size": 8196, "cut_index": 716, "middle_length": 229 }
shouldUseTurbopack } from 'next-test-utils' import path from 'node:path' import type { ChildProcess } from 'node:child_process' import { existsSync, readFileSync } from 'node:fs' describe('next experimental-analyze', () => { if (!shouldUseTurbopack()) { // Test suites require at least one test it('skips in n...
!: (url: string) => void let rejectUrl!: (err: Error) => void const urlPromise = new Promise<string>((resolve, reject) => { resolveUrl = resolve rejectUrl = reject }) const timeout = setTimeout(() => { rejectUrl(new Error
st suites require at least one test it('is skipped', () => {}) return } it('runs successfully without errors', async () => { let serveProcess: ChildProcess | undefined let stdoutBuffer = '' let resolveUrl
{ "filepath": "test/e2e/next-analyze/next-analyze.test.ts", "language": "typescript", "file_size": 2945, "cut_index": 563, "middle_length": 229 }
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)( 'Handles Webpack Require Hook', () => { const { next, isNextStart, isNextDev } = nextTestSetup({ files: __dirname, }) if (isNextStart) { it('should not error during build', () => { const errors = next.cliOutput ....
;(isNextDev ? describe : describe.skip)('development mode', () => { it('should apply and not error during development', async () => { await next.render('/') expect(next.cliOutput).toMatch(/Initialized config/) }) }) } )
ut).toMatch(/Initialized config/) }) }
{ "filepath": "test/e2e/webpack-require-hook/webpack-require-hook.test.ts", "language": "typescript", "file_size": 916, "cut_index": 606, "middle_length": 52 }
from 'fs-extra' import path from 'path' describe('minified module ids', () => { ;(!process.env.IS_TURBOPACK_TEST ? describe.skip : describe)( 'production mode', () => { const { next, isNextStart } = nextTestSetup({ files: __dirname, }) if (!isNextStart) { it('skipped for no...
ames) { const output = await fs.readFile(path.join(ssrPath, basename), 'utf8') ssrBundles += output } const staticBundleBasenames = (await listClientChunks(distDir)).filter( (p) => p.endsWith('.js') )
Dir) const ssrPath = path.join(distDir, 'server/chunks/ssr/') const ssrBundleBasenames = (await fs.readdir(ssrPath)).filter((p) => p.match(/\.js$/) ) for (const basename of ssrBundleBasen
{ "filepath": "test/e2e/module-ids/module-ids.test.ts", "language": "typescript", "file_size": 4254, "cut_index": 614, "middle_length": 229 }
'e2e-utils' import { retry } from 'next-test-utils' describe('i18n Support Fallback Rewrite Legacy', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should not rewrite for index page', async () => { for (const [pathname, query] of [ ['/', {}], ['/en', {}], ['/fr', {}...
}) await retry(async () => { expect( JSON.parse(await browser.elementByCss('#router').text()) ).toEqual({ index: true, pathname: '/', asPath: url.format({ pathname: '/', query }),
wser = await next.browser(asPath) expect(JSON.parse(await browser.elementByCss('#router').text())).toEqual({ index: true, pathname: '/', asPath: url.format({ pathname: '/', query }), query,
{ "filepath": "test/e2e/i18n-support-fallback-rewrite-legacy/i18n-support-fallback-rewrite-legacy.test.ts", "language": "typescript", "file_size": 2221, "cut_index": 563, "middle_length": 229 }
from 'e2e-utils' import { retry, waitFor } from 'next-test-utils' describe('revalidate-reason', () => { const { next, isNextDev } = nextTestSetup({ files: __dirname, }) if (isNextDev) { describe('development mode', () => { // in dev mode, the revalidateReason is called on every request, and will a...
eason: "build"', async () => { expect(next.cliOutput).toContain( 'revalidate-reason/pages/index.tsx revalidateReason: build' ) expect(next.cliOutput).toContain( 'revalidate-reason/pages/stale.tsx revalidateReason: build' ) })
t.cliOutput).toContain( 'revalidate-reason/pages/index.tsx revalidateReason: stale' ) }) }) // skip the remaining tests as they do not apply in dev return } it('should support revalidateR
{ "filepath": "test/e2e/revalidate-reason/revalidate-reason.test.ts", "language": "typescript", "file_size": 1652, "cut_index": 537, "middle_length": 229 }
sleep } from './sleep' import { get } from 'http' describe('streaming responses cancel inner stream after disconnect', () => { const { next } = nextTestSetup({ files: __dirname, }) function prime(url: string, noData?: boolean) { return new Promise<void>((resolve, reject) => { url = new URL(url, ne...
ep(5) } res.destroy() resolve() }) req.on('error', reject) req.end() if (noData) { req.on('error', (e) => { // Swallow the "socket hang up" message that happens if you abort // b
e connection stream. // https://github.com/node-fetch/node-fetch/pull/670 const req = get(url, async (res) => { while (true) { const value = res.read(1) if (value) break await sle
{ "filepath": "test/e2e/cancel-request/stream-cancel.test.ts", "language": "typescript", "file_size": 2806, "cut_index": 563, "middle_length": 229 }
eamable } from '../../streamable' import { NextRequest } from 'next/server' export const runtime = 'nodejs' // Next thinks it can statically compile this route, which breaks the test. export const dynamic = 'force-dynamic' let streamable: ReturnType<typeof Streamable> | undefined export async function GET(req: NextR...
eamable(+write)) // The request was aborted before the response was returned. if (req.signal.aborted) { s.abort() return new Response(null, { status: 204 }) } req.signal.onabort = () => { s.abort() } return new
sume the entire request body. // This is so we don't confuse the request close with the connection close. await req.text() const write = req.nextUrl.searchParams.get('write') if (write) { const s = (streamable = Str
{ "filepath": "test/e2e/cancel-request/app/node-route/route.ts", "language": "typescript", "file_size": 1438, "cut_index": 524, "middle_length": 229 }
omingMessage, ServerResponse } from 'http' import { pipeline } from 'stream' import { Readable } from '../../readable' export const config = { runtime: 'nodejs', } let readable: ReturnType<typeof Readable> | undefined export default async function handler( req: IncomingMessage, res: ServerResponse ): Promise<v...
(readable = Readable(+write)) res.on('close', () => { r.abort() }) return new Promise((resolve) => { pipeline(r.stream, res, () => { resolve() res.end() }) }) } // The 2nd request should render the st
() return } // Pages API requests have already consumed the body. // This is so we don't confuse the request close with the connection close. const write = url.searchParams.get('write') if (write) { const r =
{ "filepath": "test/e2e/cancel-request/pages/api/node-api.ts", "language": "typescript", "file_size": 1358, "cut_index": 524, "middle_length": 229 }
-standalone-expect */ import { nextTestSetup, isNextDev, isNextStart } from 'e2e-utils' const shouldSkip = (isNextStart && !!process.env.TURBOPACK_DEV) || (isNextDev && !!process.env.TURBOPACK_BUILD) ;(shouldSkip ? describe.skip : describe)( 'Default 404 Page with custom _error', () => { const { next } = ...
NextDev ? 'oops' : 'Internal Server Error') }) it('should render index page normal', async () => { const html = await next.render('/') expect(html).toContain('hello from index') }) ;(isNextStart ? it : it.skip)( 'should s
status).toBe(404) expect(await res.text()).toContain('This page could not be found') }) it('should render error correctly', async () => { const text = await next.render('/err') expect(text).toContain(is
{ "filepath": "test/e2e/404-page-custom-error/404-page-custom-error.test.ts", "language": "typescript", "file_size": 1524, "cut_index": 537, "middle_length": 229 }
('Error no pageProps', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should load auto-export page correctly', async () => { const browser = await next.browser('/') expect(await browser.elementByCss('#index').text()).toBe('index') expect(await browser.eval('window.uncaughtError...
wser.elementByCss('#gssp').text()).toBe( 'getServerSideProps' ) expect(await browser.eval('window.uncaughtErrors')).toEqual([]) }) it('should load 404 page correctly', async () => { const browser = await next.browser('/non-existent')
('getStaticProps') expect(await browser.eval('window.uncaughtErrors')).toEqual([]) }) it('should load getServerSideProps page correctly', async () => { const browser = await next.browser('/gssp') expect(await bro
{ "filepath": "test/e2e/no-page-props/no-page-props.test.ts", "language": "typescript", "file_size": 2630, "cut_index": 563, "middle_length": 229 }
ges i18n', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should update props on locale change with same hash', async () => { const browser = await next.browser('/about#hash') await browser.elementByCss('#change-locale').click() await retry(async () => { expect(await br...
ect(await browser.eval('window.location.pathname')).toBe('/about') }) await retry(async () => { expect(await browser.eval('window.location.hash')).toBe('#hash') }) expect(await browser.elementByCss('#router-locale').text()).toBe('en'
rowser.elementByCss('#router-locale').text()).toBe('fr') expect(await browser.elementByCss('#props-locale').text()).toBe('fr') await browser.elementByCss('#change-locale').click() await retry(async () => { exp
{ "filepath": "test/e2e/i18n-support-same-page-hash-change/i18n-support-same-page-hash-change.test.ts", "language": "typescript", "file_size": 3118, "cut_index": 614, "middle_length": 229 }
rt Link from 'next/link' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() return ( <> <p id="props-locale">{props.locale}</p> <p id="router-locale">{router.locale}</p> <Link href={{ pathname: router.pathname, query: router.query...
ocale, }, } } export const getStaticPaths = () => { return { paths: [ { params: { slug: ['a'] }, locale: 'en', }, { params: { slug: ['a'] }, locale: 'fr', }, ], fallback: false,
nc ({ locale }) => { return { props: { l
{ "filepath": "test/e2e/i18n-support-same-page-hash-change/pages/posts/[...slug].js", "language": "javascript", "file_size": 829, "cut_index": 516, "middle_length": 52 }
utils' import { retry } from 'next-test-utils' // Webpack-specific test, not needed for Turbopack ;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)( 'Web Workers with webpack 5', () => { const { next } = nextTestSetup({ files: __dirname, dependencies: { faker: '5.5.3', }, ...
#web-status').text()).toMatch( /PASS/i ) }) await browser.waitForElementByCss('#worker-status') await retry(async () => { expect(await browser.elementByCss('#worker-status').text()).toMatch( /PASS/i
() => { expect(await browser.elementByCss('
{ "filepath": "test/e2e/worker-webpack5/worker-webpack5.test.ts", "language": "typescript", "file_size": 884, "cut_index": 547, "middle_length": 52 }
'e2e-utils' import { runTests } from './utils' describe('app dir - with output export - dynamic missing gsp', () => { describe('should error when dynamic route is missing generateStaticParams', () => { runTests({ dynamicPage: 'undefined', generateStaticParamsOpt: 'set noop', expectedErrMsg: is...
TEST ? 'App pages cannot use both "use client" and export function "generateStaticParams()".' : 'Page "/another/[slug]/page" cannot use both "use client" and export function "generateStaticParams()".' runTests({ dynamicPage: 'undefin
ing "generateStaticParams()" so it cannot be used with "output: export" config.', }) }) describe('should error when client component has generateStaticParams', () => { const expectedErrMsg = process.env.IS_TURBOPACK_
{ "filepath": "test/e2e/app-dir-export/test/dynamic-missing-gsp.test.ts", "language": "typescript", "file_size": 1514, "cut_index": 537, "middle_length": 229 }
shTrue = [ '404.html', '404/index.html', '__next.__PAGE__.txt', '__next._full.txt', '__next._head.txt', '__next._index.txt', '__next._tree.txt', // Turbopack and plain next.js have different hash output for the file name // Turbopack will output favicon in the _next/static/media folder ...(process.e...
/_next\/static\/[A-Za-z0-9_-]+\/_clientMiddlewareManifest.js/ ), ] : []), expect.stringMatching(/_next\/static\/[A-Za-z0-9_-]+\/_ssgManifest.js/), '_not-found/__next._full.txt', '_not-found/__next._head.txt', '_not-found/__next._i
/_next\/static\/(immutable\/)?media\/test\.[0-9a-z_-]+\.png/ ), expect.stringMatching(/_next\/static\/[A-Za-z0-9_-]+\/_buildManifest.js/), ...(process.env.IS_TURBOPACK_TEST ? [ expect.stringMatching(
{ "filepath": "test/e2e/app-dir-export/test/utils.ts", "language": "typescript", "file_size": 13050, "cut_index": 921, "middle_length": 229 }
'next/link' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() return ( <> <p id="gssp">gssp page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-default-locale">{router.defaultL...
<Link href="/" id="to-index"> to / </Link> <br /> </> ) } export const getServerSideProps = ({ locale, locales, defaultLocale, query, }) => { return { props: { query, locale, locales, defau
<p id="router-as-path">{router.asPath}</p>
{ "filepath": "test/e2e/i18n-support/pages/gssp/index.js", "language": "javascript", "file_size": 860, "cut_index": 529, "middle_length": 52 }
Link from 'next/link' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() return ( <> <p id="gsp">gsp page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-locales">{JSON.stringif...
.slug) { throw new Error(`missing params ${JSON.stringify(params)}`) } if (locale === 'en' || locale === 'nl') { return { notFound: true, } } return { props: { params, locale, locales, }, } } export
<Link href="/" id="to-index"> to / </Link> <br /> </> ) } export const getStaticProps = ({ params, locale, locales }) => { // ensure getStaticProps isn't called without params if (!params || !params
{ "filepath": "test/e2e/i18n-support/pages/not-found/blocking-fallback/[slug].js", "language": "javascript", "file_size": 1226, "cut_index": 518, "middle_length": 229 }
from 'next/link' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() return ( <> <p id="dynamic">dynamic page</p> <p id="router-locale">{router.locale}</p> <p id="router-default-locale">{router.defaultLocale}</p> <p id="router-locale...
fallback-first"> to /gsp/fallback/first </Link> <br /> <Link href="/gsp/fallback/hello" id="to-fallback-hello"> to /gsp/fallback/hello </Link> <br /> <Link href="/gsp/no-fallback/first" id="to-no-fallback
sPath}</p> <Link href="/another" id="to-another"> to /another </Link> <br /> <Link href="/gsp" id="to-gsp"> to /gsp </Link> <br /> <Link href="/gsp/fallback/first" id="to-
{ "filepath": "test/e2e/i18n-support/pages/dynamic/[slug].js", "language": "javascript", "file_size": 1276, "cut_index": 524, "middle_length": 229 }
st=hello', '/_next/data/BUILD_ID/p1/p2/all-ssr/hello1%2F/he%2Fllo2.json?rest=hello1%2F&rest=he%2Fllo2', '/_next/data/BUILD_ID/p1/p2/all-ssr/hello1/hello2.json?rest=hello1&rest=hello2', '/_next/data/BUILD_ID/p1/p2/nested-all-ssg/hello.json?rest=hello', '/_next/data/BUILD_I...
ent=comment-1', '/_next/data/BUILD_ID/post-1/comments.json?name=post-1', ] : [ '/_next/data/BUILD_ID/p1/p2/all-ssg/hello.json?rest=hello', '/_next/data/BUILD_ID/p1/p2/all-ssg/hello1/hello2.json?rest=hel
en=value&name=post-1', '/_next/data/BUILD_ID/post-1.json?name=post-1', '/_next/data/BUILD_ID/post-1.json?name=post-1&another=value', '/_next/data/BUILD_ID/post-1/comment-1.json?name=post-1&comm
{ "filepath": "test/e2e/dynamic-routing/shared.ts", "language": "typescript", "file_size": 62778, "cut_index": 2151, "middle_length": 229 }
lt function getPaths(pathPrefix) { return [ // this will get turned into %2Fmy-post%2F { params: { slug: '/my-post/' } }, // this will get turned into %252Fmy-post%252F { params: { slug: '%2Fmy-post%2F' } }, // this will be passed through { params: { slug: '+my-post+' } }, // this will get...
slug: ' my-post ' } }, { params: { slug: encodeURIComponent('商業日語') } }, `${pathPrefix}/%2Fsecond-post%2F`, `${pathPrefix}/%2Bsecond-post%2B`, `${pathPrefix}/%26second-post%26`, `${pathPrefix}/mixed-${encodeURIComponent('商業日語')}`, ] }
{ params: {
{ "filepath": "test/e2e/prerender-fallback-encoding/paths.js", "language": "javascript", "file_size": 819, "cut_index": 524, "middle_length": 14 }
tRequest } from 'next/server' import { Streamable } from './streamable' export const config = { matcher: '/middleware', } let streamable: ReturnType<typeof Streamable> | undefined export default async function handler(req: NextRequest): Promise<Response> { if (req.nextUrl.searchParams.has('compile')) { // Th...
if (req.signal.aborted) { s.abort() return new Response(null, { status: 204 }) } req.signal.onabort = () => { s.abort() } return new Response(s.stream) } // The 2nd request should render the stats. We don't use a qu
he connection close. await req.text() const write = req.nextUrl.searchParams.get('write') if (write) { const s = (streamable = Streamable(+write)) // The request was aborted before the response was returned.
{ "filepath": "test/e2e/cancel-request/middleware.ts", "language": "typescript", "file_size": 1351, "cut_index": 524, "middle_length": 229 }
tRequest } from 'next/server' import { Streamable } from '../../streamable' export const config = { runtime: 'edge', } let streamable: ReturnType<typeof Streamable> | undefined export default async function handler(req: NextRequest): Promise<Response> { if (req.nextUrl.searchParams.has('compile')) { // The r...
(req.signal.aborted) { s.abort() return new Response(null, { status: 204 }) } req.signal.onabort = () => { s.abort() } return new Response(s.stream) } // The 2nd request should render the stats. We don't use a query
connection close. await req.text() const write = req.nextUrl.searchParams.get('write') if (write) { const s = (streamable = Streamable(+write)) // The request was aborted before the response was returned. if
{ "filepath": "test/e2e/cancel-request/pages/api/edge-api.ts", "language": "typescript", "file_size": 1348, "cut_index": 524, "middle_length": 229 }
ort { nextTestSetup } from 'e2e-utils' import { retry } from 'next-test-utils' describe('Dynamic Optional Routing Root Fallback', () => { const { next } = nextTestSetup({ files: __dirname }) it('should render optional catch-all top-level route with no segments', async () => { const browser = await next.browse...
entByCss('#success').text()).toMatch(/one/) }) }) it('should render optional catch-all top-level route with two segments', async () => { const browser = await next.browser('/one/two') await browser.waitForElementByCss('#success') await
er optional catch-all top-level route with one segment', async () => { const browser = await next.browser('/one') await browser.waitForElementByCss('#success') await retry(async () => { expect(await browser.elem
{ "filepath": "test/e2e/dynamic-optional-routing-root-fallback/dynamic-optional-routing-root-fallback.test.ts", "language": "typescript", "file_size": 1115, "cut_index": 515, "middle_length": 229 }
ort * as React from 'react' import { Expensive } from '../lib/sharedCode' export default function Home() { const [expensiveWebStatus, setExpensiveWebStatus] = React.useState('WAIT') const [expensiveWorkerStatus, setExpensiveWorkerComplete] = React.useState('WAIT') const worker = React.useRef() React.useEf...
xpensive() setExpensiveWebStatus('PASS') } catch { setExpensiveWebStatus('FAIL') } }, []) return ( <main> <h1>$RefreshRegistry repro</h1> <div id="web-status">Web: {expensiveWebStatus}</div> <div id="worker-st
WorkerComplete('PASS') } }) worker.current.addEventListener('error', (data) => { setExpensiveWorkerComplete('FAIL') }) }, [worker, setExpensiveWorkerComplete]) React.useEffect(() => { try { E
{ "filepath": "test/e2e/worker-webpack5/pages/index.js", "language": "javascript", "file_size": 1062, "cut_index": 515, "middle_length": 229 }
n } from 'path' import { isNextStart, nextTestSetup } from 'e2e-utils' import { retry } from 'next-test-utils' describe('app dir - with output export (next start)', () => { if (isNextStart) { const { next } = nextTestSetup({ files: join(__dirname, '..'), skipStart: true, }) it('should error ...
it('should warn during next start with output standalone', async () => { await next.patchFile( 'next.config.js', (content) => content.replace(`output: 'export'`, `output: 'standalone'`), async () => { cons
} catch (e) {} await retry(() => { expect(next.cliOutput).toContain( `"next start" does not work with "output: export" configuration. Use "npx serve@latest out" instead.` ) }) })
{ "filepath": "test/e2e/app-dir-export/test/start.test.ts", "language": "typescript", "file_size": 1485, "cut_index": 524, "middle_length": 229 }
import { open } from 'sqlite' import sqlite3 from 'sqlite3' import { useRouter } from 'next/router' export const getStaticProps = async ({ params }) => { const dbPath = path.join(process.cwd(), 'data.sqlite') console.log('using db', dbPath) const db = await open({ filename: dbPath, driver: sqlite3.Data...
fallback: true, } } export default function Page(props) { const router = useRouter() if (router.isFallback) { return 'Loading...' } return ( <> <p id="blog">blog page</p> <p id="props">{JSON.stringify(props)}</p> </>
= () => { return { paths: ['/blog/first'],
{ "filepath": "test/e2e/prerender-native-module/pages/blog/[slug].js", "language": "javascript", "file_size": 848, "cut_index": 535, "middle_length": 52 }
(...args) { window.caughtWarns.push(args) origWarn(...args) } } const Page = () => { return ( <div> <h3>My blog</h3> <Link href="/[name]" as="/post-1" id="view-post-1"> View post 1 </Link> <br /> <Link href="/[name]" as="/post-1#my-hash" id="view-post-1-hash-1"> ...
pathname: '/[name]', query: { name: 'post-1' }, }} id="view-post-1-hash-1-interpolated" > View post 1 (hash interpolated) </Link> <br /> <Link href="/post-1" id="view-post-1-no-as"> Vi
<Link href="/post-1?hidden=value" as="/post-1" id="view-post-1-hidden-query" > View post 1 (href query) </Link> <br /> <Link href={{ hash: 'my-hash',
{ "filepath": "test/e2e/dynamic-routing/pages/index.js", "language": "javascript", "file_size": 5851, "cut_index": 716, "middle_length": 229 }
extStart } = nextTestSetup({ files: __dirname, // Assertions don't apply to deploy mode (output differs vs. local Next.js server). skipDeployment: true, }) const urlPaths = [ '%2Fmy-post%2F', '%252Fmy-post%252F', '%2Bmy-post%2B', '%3Fmy-post%3F', '%26my-post%26', encodeURICompon...
F', '+second-post+', '&second-post&', 'mixed-商業日語', ] const modePaths = ['fallback-blocking', 'fallback-false', 'fallback-true'] if (isNextStart) { it('should output paths correctly', async () => { const pagesDir = join(next.t
('商業日語')}`, ] const prerenderedPaths = [ '%2Fmy-post%2F', '%252Fmy-post%252F', '+my-post+', '%3Fmy-post%3F', '&my-post&', '商業日語', encodeURIComponent('商業日語'), ' my-post ', '%2Fsecond-post%2
{ "filepath": "test/e2e/prerender-fallback-encoding/prerender-fallback-encoding.test.ts", "language": "typescript", "file_size": 8548, "cut_index": 716, "middle_length": 229 }
tRequest } from 'next/server' import { Streamable } from '../../streamable' export const runtime = 'edge' let streamable: ReturnType<typeof Streamable> | undefined export async function GET(req: NextRequest): Promise<Response> { if (req.nextUrl.searchParams.has('compile')) { // The request just wants to trigge...
s.abort() return new Response(null, { status: 204 }) } req.signal.onabort = () => { s.abort() } return new Response(s.stream) } // The 2nd request should render the stats. We don't use a query param // because edge re
eq.text() const write = req.nextUrl.searchParams.get('write') if (write) { const s = (streamable = Streamable(+write)) // The request was aborted before the response was returned. if (req.signal.aborted) {
{ "filepath": "test/e2e/cancel-request/app/edge-route/route.ts", "language": "typescript", "file_size": 1321, "cut_index": 524, "middle_length": 229 }
from 'next/link' import { useRouter } from 'next/router' import { useEffect } from 'react' export default function Page(props) { const router = useRouter() useEffect(() => { window.hashChangeStart = 'no' window.hashChangeComplete = 'no' const hashChangeStart = () => { window.hashChangeStart = 'y...
"props-locale">{props.locale}</p> <p id="router-locale">{router.locale}</p> <Link href={{ pathname: router.pathname, query: router.query, hash: '#hash' }} locale={router.locale === 'fr' ? 'en' : 'fr'} id="change-locale"
e', hashChangeComplete) return () => { router.events.off('hashChangeStart', hashChangeStart) router.events.off('hashChangeComplete', hashChangeComplete) } }, [router.events]) return ( <> <p id=
{ "filepath": "test/e2e/i18n-support-same-page-hash-change/pages/about.js", "language": "javascript", "file_size": 1265, "cut_index": 524, "middle_length": 229 }
k from 'next/link' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() return ( <> <p id="gsp">gsp page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-locales">{JSON.stringify(ro...
"to-index"> to / </Link> <br /> </> ) } export const getStaticProps = ({ locale, locales }) => { if (locale === 'en' || locale === 'nl') { return { notFound: true, } } return { props: { locale,
k href="/" id=
{ "filepath": "test/e2e/i18n-support/pages/not-found/index.js", "language": "javascript", "file_size": 816, "cut_index": 522, "middle_length": 14 }
link' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() return ( <> <p id="developments">developments page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-default-locale">{route...
}</p> <Link href="/" id="to-index"> to / </Link> <br /> </> ) } export const getServerSideProps = ({ locale, locales, defaultLocale }) => { return { props: { locale, locales, defaultLocale, },
ame}</p> <p id="router-as-path">{router.asPath
{ "filepath": "test/e2e/i18n-support/pages/developments/index.js", "language": "javascript", "file_size": 847, "cut_index": 535, "middle_length": 52 }
ailingSlashTrue, getFiles } from './utils' import { FileRef, isNextStart, nextTestSetup, PatchedFileRef } from 'e2e-utils' describe('app dir - with output export', () => { if (isNextStart) { describe('with exportPathMap configured', () => { let { next } = nextTestSetup({ files: { app: new...
) it('should throw', async () => { let { exitCode, cliOutput } = await next.build() expect(exitCode).toBe(1) expect(cliOutput).toContain( 'The "exportPathMap" configuration cannot be used with the "app" directory. P
ace( 'trailingSlash: true,', `trailingSlash: true, exportPathMap: async function (map) { return map },` ) ), }, skipStart: true, }
{ "filepath": "test/e2e/app-dir-export/test/config.test.ts", "language": "typescript", "file_size": 2958, "cut_index": 563, "middle_length": 229 }
rom 'next/router' const Page = () => { const router = useRouter() const { query } = router return ( <> <Link href="#only-hash" id="dynamic-route-only-hash"> Dynamic route only hash </Link> <br /> <Link href={{ hash: 'only-hash-obj' }} id="dynamic-route-only-hash-obj"> ...
"dynamic-route-only-query-obj" > Dynamic route only query object </Link> <br /> <Link href={{ query: { name: 'post-5', another: 'value' } }} id="dynamic-route-only-query-obj-extra" > Dynamic rou
href="?name=post-3&another=value" id="dynamic-route-only-query-extra" > Dynamic route only query extra </Link> <br /> <Link href={{ query: { name: 'post-4' } }} id=
{ "filepath": "test/e2e/dynamic-routing/pages/[name]/index.js", "language": "javascript", "file_size": 2040, "cut_index": 563, "middle_length": 229 }
* 4. Wait for the MCP HTTP server to be ready. * 5. Run MCP HTTP and CLI queries and verify the response structure. */ import { nextTestSetup, isNextDeploy } from 'e2e-utils' import { existsSync } from 'fs' import path from 'path' import spawn from 'cross-spawn' import type { ChildProcess } from 'child_process' im...
e * first `data:` line that contains a `result.content[].text` field. */ async function callMcpTool( port: number, toolName: string, args: Record<string, unknown> ): Promise<string> { const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
path.dirname(require.resolve('next/package')), 'dist/bin/next' ) /** * POST a JSON-RPC `tools/call` to the MCP server and return the text content. * The Streamable-HTTP transport responds with Server-Sent Events; we find th
{ "filepath": "test/e2e/turbopack-trace-server-query/turbopack-trace-server.test.ts", "language": "typescript", "file_size": 13766, "cut_index": 921, "middle_length": 229 }
rt path from 'path' import fs from 'fs-extra' function extractJSON(response) { return JSON.parse(response.headers.get('data') ?? '{}') } function baseNextConfig(): Parameters<typeof nextTestSetup>[0] { return { files: { 'src/add.wasm': new FileRef(path.join(__dirname, './add.wasm')), 'src/add.js':...
increment } from './src/add.js' export default async function middleware(request) { const input = Number(request.nextUrl.searchParams.get('input')) || 1; const value = await increment(input); return new Respon
it instance$; return exports.add_one(a); } `, 'pages/index.js': ` export default function () { return <div>Hello, world!</div> } `, 'middleware.js': ` import {
{ "filepath": "test/e2e/edge-can-use-wasm-files/index.test.ts", "language": "typescript", "file_size": 4583, "cut_index": 614, "middle_length": 229 }
{ nextTestSetup, isNextDev, isNextStart } from 'e2e-utils' describe('Errors on conflict between public file and page file', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipStart: true, skipDeployment: true, }) if (skipped) return if (isNextDev) { it('should show confli...
it('should show conflict error during build', async () => { const { cliOutput } = await next.build() const conflicts = ['/another/conflict', '/another', '/hello'] expect(cliOutput).toMatch(/Conflicting public and page files were foun
ict', '/hello'] for (const conflict of conflicts) { const html = await next.render(conflict) expect(html).toMatch(regex) } expect(next.cliOutput).toMatch(regex) }) } if (isNextStart) {
{ "filepath": "test/e2e/conflicting-public-file-page/conflicting-public-file-page.test.ts", "language": "typescript", "file_size": 1131, "cut_index": 518, "middle_length": 229 }
ed) return it('should apply temporary redirect when visited directly for GSSP page', async () => { const res = await next.fetch(`${basePath}/gssp-blog/redirect-1`, { redirect: 'manual', }) expect(res.status).toBe(307) const { pathname } = new URL(res.headers.get('location')!) expect(pathna...
)!) expect(parsedUrl.pathname).toBe(`/404`) const browser = await next.browser(`${basePath}`) await browser.eval(`next.router.push('/gssp-blog/redirect-1-no-basepath-')`) await retry(async () => { const html = await browser.eval('doc
gssp-blog/redirect-1-no-basepath-`, { redirect: 'manual' } ) expect(res.status).toBe(307) const text = await res.text() expect(text).toEqual(`/404`) const parsedUrl = new URL(res.headers.get('location'
{ "filepath": "test/e2e/gssp-redirect-base-path/gssp-redirect-base-path.test.ts", "language": "typescript", "file_size": 14117, "cut_index": 921, "middle_length": 229 }
Router } from 'next/router' export default function Post(props) { const router = useRouter() if (typeof window === 'undefined') { if (router.query.post?.startsWith('redir')) { console.log(router) throw new Error('render should not occur for redirect') } } return ( <> <p id="gssp...
, '/') } let permanent = undefined let statusCode = undefined if (params.post.includes('statusCode-')) { statusCode = parseInt( params.post.split('statusCode-').pop().split('-').shift(), 10 ) } if (par
tination = '/404' if (params.post.includes('dest-external')) { destination = 'https://example.vercel.sh' } else if (params.post.includes('dest-')) { destination = params.post.split('dest-').pop().replace(/_/g
{ "filepath": "test/e2e/gssp-redirect-base-path/pages/gssp-blog/[post].js", "language": "javascript", "file_size": 1378, "cut_index": 524, "middle_length": 229 }
'next/router' export default function Post(props) { const router = useRouter() if (typeof window === 'undefined') { if (router.query.post?.startsWith('redir')) { console.log(router) throw new Error('render should not occur for redirect') } } if (typeof window !== 'undefined' && !window.i...
'https://example.vercel.sh' } else if (params.post.includes('dest-')) { destination = params.post.split('dest-').pop().replace(/_/g, '/') } let permanent = undefined let statusCode = undefined if (params.post.includes('statusCo
JSON.stringify(props)}</p> </> ) } export const getStaticProps = ({ params }) => { if (params.post.startsWith('redir')) { let destination = '/404' if (params.post.includes('dest-external')) { destination =
{ "filepath": "test/e2e/gssp-redirect-base-path/pages/gsp-blog/[post].js", "language": "javascript", "file_size": 1678, "cut_index": 537, "middle_length": 229 }
y).isNextDeploy) { it('should skip deploy', () => {}) return } const { next } = nextTestSetup({ files: __dirname, skipStart: true, }) let backend: http.Server let backendPort: number let intermediary: http.Server let intermediaryPort: number const backendRequests: string[] = [] asyn...
`${smuggledRequest.length.toString(16).toUpperCase()}\r\n`, 'latin1' ) const payload = Buffer.concat([ Buffer.from( `${method} ${rewritePath} HTTP/1.1\r\nHost: 127.0.0.1:${nextPort}\r\nTransfer-Encoding: chunked\r\nConnection
hod?: 'DELETE' | 'OPTIONS' rewritePath?: string }) { const smuggledRequest = Buffer.from( `GET /secret HTTP/1.1\r\nHost: 127.0.0.1:${nextPort}\r\n\r\n`, 'latin1' ) const chunkSize = Buffer.from(
{ "filepath": "test/e2e/rewrite-request-smuggling/rewrite-request-smuggling.test.ts", "language": "typescript", "file_size": 6741, "cut_index": 716, "middle_length": 229 }
import { nextTestSetup } from 'e2e-utils' describe('{{name}}', () => { const { next } = nextTestSetup({ files: __dirname, }) // Recommended for tests that check HTML. Cheerio is a HTML parser that has a jQuery like API. it('should work using cheerio', async () => { const $ = await next.render$('/') ...
r('/') expect(html).toContain('hello world') }) // In case you need to test the response object it('should work with fetch', async () => { const res = await next.fetch('/') const html = await res.text() expect(html).toContain('hello
) expect(await browser.elementByCss('p').text()).toBe('hello world') }) // In case you need the full HTML. Can also use $.html() with cheerio. it('should work with html', async () => { const html = await next.rende
{ "filepath": "test/e2e/test-template/{{ toFileName name }}/{{ toFileName name }}.test.ts", "language": "typescript", "file_size": 1013, "cut_index": 512, "middle_length": 229 }
cHeader = 'X-From-Src-Middleware' const rootHeader = 'X-From-Root-Middleware' describe('middleware-src', () => { const { next, isTurbopack, skipped } = nextTestSetup({ files: __dirname, skipStart: true, skipDeployment: true, }) if (skipped) return if (isNextDev) { beforeAll(async () => { ...
rt', async () => { await next.patchFile( 'next.config.js', "module.exports = { output: 'export' }" ) await next.build() expect(next.cliOutput).toContain( 'Statically exporting a Next.js applicat
.fetch('/post-1') expect(response.headers.has(srcHeader)).toBe(false) expect(response.headers.has(`${srcHeader}-TS`)).toBe(true) }) } if (!isNextDev) { it('should warn about middleware on expo
{ "filepath": "test/e2e/middleware-src/middleware-src.test.ts", "language": "typescript", "file_size": 3609, "cut_index": 614, "middle_length": 229 }
isNextDev, isNextStart } from 'e2e-utils' import { findPort, initNextServerScript, killApp } from 'next-test-utils' describe('Fetch polyfill with ky-universal', () => { ;(isNextDev ? describe : describe.skip)('development mode', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: t...
r: options is not defined/ ) next.env.NEXT_PUBLIC_API_PORT = String(apiServerPort) await next.start() }) afterAll(async () => { await killApp(apiServer) }) it('includes polyfilled fetch when using getStaticProps (
rname, 'api-server.js') apiServerPort = await findPort() apiServer = await initNextServerScript( scriptPath, /ready on/i, { ...process.env, PORT: String(apiServerPort) }, /ReferenceErro
{ "filepath": "test/e2e/fetch-polyfill-ky-universal/fetch-polyfill-ky-universal.test.ts", "language": "typescript", "file_size": 2846, "cut_index": 563, "middle_length": 229 }
' import path from 'path' import { promises as fs } from 'fs' import { readJson } from 'fs-extra' describe('Edge Compiler can import asset assets', () => { const { next, isTurbopack, isNextDeploy } = nextTestSetup({ files: path.join(__dirname, './app'), }) it('allows to fetch a remote URL', async () => { ...
it('allows to fetch text assets', async () => { const html = await renderViaHTTP(next.url, '/api/edge', { handler: 'text-file', }) expect(html).toContain('Hello, from text-file.txt!') }) it('allows to fetch image assets', async () =>
remote URL with a path and basename', async () => { const response = await fetchViaHTTP(next.url, '/api/edge', { handler: 'remote-with-base', }) expect(await response.text()).toContain('Example Domain') })
{ "filepath": "test/e2e/edge-compiler-can-import-blob-assets/index.test.ts", "language": "typescript", "file_size": 3632, "cut_index": 614, "middle_length": 229 }
const config = { runtime: 'edge' } /** * @param {import('next/server').NextRequest} req */ export default async (req) => { const handlerName = req.nextUrl.searchParams.get('handler') const handler = handlers.get(handlerName) || defaultHandler return handler() } /** * @type {Map<string, () => Promise<Respons...
, import.meta.url) return fetch(url) }, ], [ 'remote-full', async () => { const url = new URL('https://example.vercel.sh') return fetch(url) }, ], [ 'remote-with-base', async () => { const url = new U
age-file', async () => { const url = new URL('../../src/vercel.png', import.meta.url) return fetch(url) }, ], [ 'from-node-module', async () => { const url = new URL('my-pkg/hello/world.json'
{ "filepath": "test/e2e/edge-compiler-can-import-blob-assets/app/pages/api/edge.js", "language": "javascript", "file_size": 1166, "cut_index": 518, "middle_length": 229 }
emporary redirect when visited directly for GSSP page', async () => { const res = await next.fetch('/gssp-blog/redirect-1', { redirect: 'manual', }) expect(res.status).toBe(307) const { pathname } = new URL(res.headers.get('location')!) expect(pathname).toBe('/404') }) it('should apply p...
ed directly for GSSP page', async () => { const res = await next.fetch('/gssp-blog/redirect-statusCode-301', { redirect: 'manual', }) expect(res.status).toBe(301) const { pathname } = new URL(res.headers.get('location')!) expect(
).toBe(308) const { pathname } = new URL(res.headers.get('location')!) expect(pathname).toBe('/404') expect(res.headers.get('refresh')).toMatch(/url=\/404/) }) it('should apply statusCode 301 redirect when visit
{ "filepath": "test/e2e/gssp-redirect/gssp-redirect.test.ts", "language": "typescript", "file_size": 14789, "cut_index": 921, "middle_length": 229 }
etch').default // @ts-expect-error global.Request = require('node-fetch').Request // @ts-expect-error global.Headers = require('node-fetch').Headers } const { readFileSync } = require('fs') /** @type {import('next').default} */ // @ts-ignore: missing interopDefault const next = require('next') const { join }...
process.on('unhandledRejection', (err) => { console.error('unhandledRejection:', err) }) async function main() { const envPort = process.env.PORT ? parseInt(process.env.PORT, 10) : 0 const port = envPort > 0 ? envPort : await getPort() const host
E_HTTPS === 'true' const { createServer } = require(useHttps ? 'https' : 'http') const httpOptions = { key: readFileSync(join(__dirname, 'ssh/localhost-key.pem')), cert: readFileSync(join(__dirname, 'ssh/localhost.pem')), }
{ "filepath": "test/e2e/custom-server/server.js", "language": "javascript", "file_size": 3843, "cut_index": 614, "middle_length": 229 }
Router } from 'next/router' export default function Post(props) { const router = useRouter() if (typeof window === 'undefined') { if (router.query.post?.startsWith('redir')) { console.log(router) throw new Error('render should not occur for redirect') } } return ( <> <p id="gssp...
, '/') } let permanent = undefined let statusCode = undefined if (params.post.includes('statusCode-')) { statusCode = parseInt( params.post.split('statusCode-').pop().split('-').shift(), 10 ) } if (par
tination = '/404' if (params.post.includes('dest-external')) { destination = 'https://example.vercel.sh' } else if (params.post.includes('dest-')) { destination = params.post.split('dest-').pop().replace(/_/g
{ "filepath": "test/e2e/gssp-redirect/pages/gssp-blog/[post].js", "language": "javascript", "file_size": 1289, "cut_index": 524, "middle_length": 229 }
'next/router' export default function Post(props) { const router = useRouter() if (typeof window === 'undefined') { if (router.query.post?.startsWith('redir')) { console.log(router) throw new Error('render should not occur for redirect') } } if (typeof window !== 'undefined' && !window.i...
'https://example.vercel.sh' } else if (params.post.includes('dest-')) { destination = params.post.split('dest-').pop().replace(/_/g, '/') } let permanent = undefined let statusCode = undefined if (params.post.includes('statusCo
JSON.stringify(props)}</p> </> ) } export const getStaticProps = ({ params }) => { if (params.post.startsWith('redir')) { let destination = '/404' if (params.post.includes('dest-external')) { destination =
{ "filepath": "test/e2e/gssp-redirect/pages/gsp-blog/[post].js", "language": "javascript", "file_size": 1813, "cut_index": 537, "middle_length": 229 }
'next/router' export default function Post(props) { const router = useRouter() if (typeof window === 'undefined') { if (router.query.post?.startsWith('redir')) { console.log(router) throw new Error('render should not occur for redirect') } } if (typeof window !== 'undefined' && !window.i...
'https://example.vercel.sh' } else if (params.post.includes('dest-')) { destination = params.post.split('dest-').pop().replace(/_/g, '/') } let permanent = undefined let statusCode = undefined if (params.post.includes('statusCo
JSON.stringify(props)}</p> </> ) } export const getStaticProps = ({ params }) => { if (params.post.startsWith('redir')) { let destination = '/404' if (params.post.includes('dest-external')) { destination =
{ "filepath": "test/e2e/gssp-redirect/pages/gsp-blog-blocking/[post].js", "language": "javascript", "file_size": 1819, "cut_index": 537, "middle_length": 229 }
{ const { next, isNextStart } = nextTestSetup({ files: __dirname, }) const locales = ['en-US', 'nl-NL', 'nl-BE', 'nl', 'fr-BE', 'fr', 'en'] it('should load the index route correctly SSR', async () => { const res = await next.fetch('/', { redirect: 'manual' }) expect(res.status).toBe(200) con...
arse($('#router-locales').text())).toEqual(locales) }) it('should load the index route correctly CSR', async () => { const browser = await next.browser('/') expect(await browser.elementByCss('#router-locale').text()).toBe('en-US') expect(
'/[[...slug]]') expect($('#router-as-path').text()).toBe('/') expect(JSON.parse($('#props').text())).toEqual({ params: {}, locale: 'en-US', locales, defaultLocale: 'en-US', }) expect(JSON.p
{ "filepath": "test/e2e/i18n-support-catchall/i18n-support-catchall.test.ts", "language": "typescript", "file_size": 6894, "cut_index": 716, "middle_length": 229 }
nk' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() return ( <> <p id="catch-alll">catch-all page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-default-locale">{router.defau...
to /another </Link> <br /> <Link href="/" locale="nl-NL" id="to-locale-index"> to /nl-nl </Link> <br /> <Link href="/another" locale="nl-NL" id="to-locale-another"> to /nl-nl/another </Link>
> <p id="router-as-path">{router.asPath}</p> <Link href="/" locale="en-US" id="to-def-locale-index"> to / </Link> <br /> <Link href="/another" locale="en-US" id="to-def-locale-another">
{ "filepath": "test/e2e/i18n-support-catchall/pages/[[...slug]].js", "language": "javascript", "file_size": 1727, "cut_index": 537, "middle_length": 229 }
rChunkUrlPath, } from 'next-test-utils' describe('Client 404', () => { 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 beforeAll(async () => { // pre-bui...
// In webpack dev mode, compiling the home page (via the // `next.render('/')` pre-build in beforeAll) can race with the // `/asd` page's hydration and trigger a Fast Refresh-driven full // reload, which in turn swallows the click on `#
replacestate', () => { it('should navigate the page', async () => { const browser = await next.browser('/asd') const serverCode = await browser .waitForElementByCss('#errorStatusCode') .text()
{ "filepath": "test/e2e/client-404/client-404.test.ts", "language": "typescript", "file_size": 3115, "cut_index": 614, "middle_length": 229 }
lementByCss('#link-other') const titleColor = await browser.eval(() => { const el = document.querySelector('#link-other') return el ? window.getComputedStyle(el).backgroundColor : '' }) expect(titleColor).toBe('rgb(0, 255, 0)') } async function checkPinkButton(br...
owser = await next.browser('/') try { await checkGreenButton(browser) } finally { await browser.close() } }) it('should have correct color on index page (on hover)', async () => { const brows
return el ? window.getComputedStyle(el).backgroundColor : '' }) expect(titleColor).toBe('rgb(255, 105, 180)') } it('should have correct color on index page (on load)', async () => { const br
{ "filepath": "test/e2e/css-features/css-modules-ordering.test.ts", "language": "typescript", "file_size": 22187, "cut_index": 1331, "middle_length": 229 }
ort fs from 'fs/promises' import { nextTestSetup } from 'e2e-utils' describe('externals-transitive', () => { const { next, isTurbopack, isNextDeploy, isNextStart } = nextTestSetup({ files: __dirname, dependencies: require('./package.json').dependencies, }) it('uses the right version of transitive extern...
s) { const content = await next.readFile( path.join(next.distDir, 'server', file) ) isLodashBundled = isLodashBundled || // Code content.includes('__lodash_hash_undefined__') || // p
eploy) { const files = glob.sync('**/*.js', { cwd: path.join(next.testDir, next.distDir, 'server'), }) let isLodashBundled = false let isStorybookGlobalBundled = false for (const file of file
{ "filepath": "test/e2e/externals-transitive/externals-transitive.test.ts", "language": "typescript", "file_size": 2798, "cut_index": 563, "middle_length": 229 }
tTestSetup } from 'e2e-utils' describe('i18n-navigations-middleware', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should respect selected locale when navigating to a dynamic route', async () => { const browser = await next.browser('/') // change to "de" locale await browser...
e: de' ) }) it('should respect selected locale when navigating to a static route', async () => { const browser = await next.browser('/') // change to "de" locale await browser.elementByCss("[href='/de']").click() const staticLink =
t()).toBe( 'Current locale: de' ) // navigate to dynamic route await dynamicLink.click() // the locale should still be "de" expect(await browser.elementById('dynamic-locale').text()).toBe( 'Local
{ "filepath": "test/e2e/i18n-navigations-middleware/i18n-navigations-middleware.test.ts", "language": "typescript", "file_size": 1360, "cut_index": 524, "middle_length": 229 }
test-utils' describe('Hydration', () => { const { next } = nextTestSetup({ files: __dirname, }) it('hydrates correctly for normal page', async () => { const browser = await next.browser('/') expect(await browser.eval('window.didHydrate')).toBe(true) }) it('hydrates correctly for //', async () =...
er.eval('window.beforeNav = true') await browser.eval('window.next.router.push("/details")') await retry(async () => { const html = await browser.eval('document.documentElement.innerHTML') expect(html).toMatch(/details/) }) expe
t browser = await next.browser('//') await brows
{ "filepath": "test/e2e/hydration/hydration.test.ts", "language": "typescript", "file_size": 952, "cut_index": 582, "middle_length": 52 }
ocales } from '../i18n-support/shared' import { findPort, fetchViaHTTP } from 'next-test-utils' import { nextTestSetup, isNextDev, type NextInstance } from 'e2e-utils' type BrowserOptions = Parameters<NextInstance['browser']>[1] describe('i18n Support basePath', () => { const { next, skipped } = nextTestSetup({ ...
er = http.createServer((req, res) => { res.statusCode = 200 res.end(JSON.stringify({ url: req.url, external: true })) }) await new Promise<void>((resolve, reject) => { externalServer.listen(externalPort, (err?: Error) => e
thname: string, options?: BrowserOptions) => next.browser(pathname, options), } let externalServer: http.Server let externalPort: number beforeAll(async () => { externalPort = await findPort() externalServ
{ "filepath": "test/e2e/i18n-support-base-path/i18n-support-base-path.test.ts", "language": "typescript", "file_size": 4705, "cut_index": 614, "middle_length": 229 }
// localeDetection: false, locales: [ 'nl-NL', 'nl-BE', 'nl', 'fr-BE', 'fr', 'en-US', 'en', 'go', 'go-BE', 'do', 'do-BE', ], defaultLocale: 'en-US', domains: [ { http: true, domain: 'example.do', defaultLo...
se', permanent: false, locale: false, }, { source: '/redirect-3', destination: '/somewhere-else', permanent: false, }, { source: '/redirect-4', destination: '/', perman
return [ { source: '/en-US/redirect-1', destination: '/somewhere-else', permanent: false, locale: false, }, { source: '/nl/redirect-2', destination: '/somewhere-el
{ "filepath": "test/e2e/i18n-support-base-path/next.config.js", "language": "javascript", "file_size": 2429, "cut_index": 563, "middle_length": 229 }
ink from 'next/link' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() return ( <> <p id="another">another page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-default-locale">{...
sPath}</p> <Link href="/" id="to-index"> to / </Link> <br /> </> ) } export const getServerSideProps = ({ locale, locales, defaultLocale }) => { return { props: { locale, locales, defaultLocale,
pathname}</p> <p id="router-as-path">{router.a
{ "filepath": "test/e2e/i18n-support-base-path/pages/another.js", "language": "javascript", "file_size": 837, "cut_index": 520, "middle_length": 52 }
from 'next/link' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() return ( <> <p id="frank">frank page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-default-locale">{router.d...
<Link href="/gsp/fallback/first" id="to-fallback-first"> to /gsp/fallback/first </Link> <br /> <Link href="/gsp/fallback/hello" id="to-fallback-hello"> to /gsp/fallback/hello </Link> <br /> <Link href
}</p> <p id="router-as-path">{router.asPath}</p> <Link href="/another" id="to-another"> to /another </Link> <br /> <Link href="/gsp" id="to-gsp"> to /gsp </Link> <br />
{ "filepath": "test/e2e/i18n-support-base-path/pages/frank.js", "language": "javascript", "file_size": 1480, "cut_index": 524, "middle_length": 229 }
rom 'next/router' import { useEffect } from 'react' import { useState } from 'react' export default function Page(props) { const router = useRouter() const parsedAs = new URL(router.asPath, 'http://n') const [asPath, setAsPath] = useState(parsedAs.pathname) useEffect(() => { if (router.isReady && router.a...
main-locales">{JSON.stringify(router.domainLocales)}</p> <p id="router-query">{JSON.stringify(router.query)}</p> <p id="router-pathname">{router.pathname}</p> <p id="router-as-path">{asPath}</p> <Link href="/another" id="to-another"
">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-default-locale">{router.defaultLocale}</p> <p id="router-locales">{JSON.stringify(router.locales)}</p> <p id="router-do
{ "filepath": "test/e2e/i18n-support-base-path/pages/index.js", "language": "javascript", "file_size": 2219, "cut_index": 563, "middle_length": 229 }
nk' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() const { nextLocale } = router.query return ( <> <p id="links">links page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-...
ocale} id="to-gsp"> to /gsp </Link> <br /> <Link href="/gsp/fallback/first" locale={nextLocale} id="to-fallback-first" > to /gsp/fallback/first </Link> <br /> <Link h
athname">{router.pathname}</p> <p id="router-as-path">{router.asPath}</p> <Link href="/another" locale={nextLocale} id="to-another"> to /another </Link> <br /> <Link href="/gsp" locale={nextL
{ "filepath": "test/e2e/i18n-support-base-path/pages/links.js", "language": "javascript", "file_size": 1719, "cut_index": 537, "middle_length": 229 }
nk' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() const { nextLocale } = router.query return ( <> <p id="links">links page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-...
</Link> <br /> <Link href={`/${nextLocale}/gsp/fallback/first`} locale={false} id="to-fallback-first" > to /gsp/fallback/first </Link> <br /> <Link href={`/${nextLocale}/gsp/fallb
uter.asPath}</p> <Link href={`/${nextLocale}/another`} locale={false} id="to-another"> to /another </Link> <br /> <Link href={`/${nextLocale}/gsp`} locale={false} id="to-gsp"> to /gsp
{ "filepath": "test/e2e/i18n-support-base-path/pages/locale-false.js", "language": "javascript", "file_size": 1997, "cut_index": 537, "middle_length": 229 }
export default function Page(props) { const router = useRouter() return ( <> <p id="links">links page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-default-locale">{router.defaultLocale}</p> <p id="router-locales">{JSON.strin...
s"> to /gsp </Link> <br /> <Link href="/gsp" locale="nl-NL" id="to-gsp-nl-nl"> to /gsp </Link> <br /> <Link href="/gsp" locale="fr" id="to-gsp-fr"> to /gsp </Link> <br /> <Lin
<Link href="/gsp" locale="en-US" id="to-gsp-en-u
{ "filepath": "test/e2e/i18n-support-base-path/pages/mixed.js", "language": "javascript", "file_size": 972, "cut_index": 582, "middle_length": 52 }
'next/link' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() return ( <> <p id="gssp">gssp page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-default-locale">{router.defaultL...
<Link href="/" id="to-index"> to / </Link> <br /> </> ) } export const getServerSideProps = ({ params, locale, locales, defaultLocale, }) => { return { props: { params, locale, locales, def
<p id="router-as-path">{router.asPath}</p>
{ "filepath": "test/e2e/i18n-support-base-path/pages/gssp/[slug].js", "language": "javascript", "file_size": 862, "cut_index": 529, "middle_length": 52 }
'next/link' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() return ( <> <p id="gssp">gssp page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-default-locale">{router.defaultL...
<Link href="/" id="to-index"> to / </Link> <br /> </> ) } export const getServerSideProps = ({ locale, locales, defaultLocale, query, }) => { return { props: { query, locale, locales, defau
<p id="router-as-path">{router.asPath}</p>
{ "filepath": "test/e2e/i18n-support-base-path/pages/gssp/index.js", "language": "javascript", "file_size": 860, "cut_index": 529, "middle_length": 52 }
t Link from 'next/link' import { useRouter } from 'next/router' export default function Page(props) { const router = useRouter() return ( <> <p id="gsp">gsp page</p> <p id="props">{JSON.stringify(props)}</p> <p id="router-locale">{router.locale}</p> <p id="router-default-locale">{route...
}</p> <Link href="/" id="to-index"> to / </Link> <br /> </> ) } export const getStaticProps = ({ locale, locales, defaultLocale }) => { return { props: { locale, locales, defaultLocale, }, } }
ame}</p> <p id="router-as-path">{router.asPath
{ "filepath": "test/e2e/i18n-support-base-path/pages/gsp/index.js", "language": "javascript", "file_size": 825, "cut_index": 517, "middle_length": 52 }
tSetup } from 'e2e-utils' import { check } from 'next-test-utils' import { join } from 'path' describe('nonce head manager', () => { const { next } = nextTestSetup({ files: { pages: new FileRef(join(__dirname, 'app/pages')), public: new FileRef(join(__dirname, 'app/public')), }, }) async fun...
=> await browser.eval(`JSON.stringify(window.scriptExecutionIds)`), '["src-1.js"]' ) await browser.elementByCss('#change-script').click() await check( async () => await browser.eval(`JSON.stringify(window.scriptExe
]' ) await browser.elementByCss('#force-rerender').click() await check( async () => await browser.eval(`document.getElementById('h1').textContent`), 'Count 1' ) await check( async ()
{ "filepath": "test/e2e/nonce-head-manager/index.test.ts", "language": "typescript", "file_size": 1521, "cut_index": 537, "middle_length": 229 }
from 'e2e-utils' import { expectVaryHeaderToContain } from 'next-test-utils' import path from 'path' describe('Vary Header Tests', () => { const { next } = nextTestSetup({ files: path.join(__dirname, '../app'), skipDeployment: true, }) it('should preserve custom vary header in API routes', async () => {...
expect(res.headers.get('cache-control')).toBe('s-maxage=3600') // Next.js internal headers are appended expectVaryHeaderToContain(varyHeader, [ 'rsc', 'next-router-state-tree', 'next-router-prefetch', ]) }) it('should
aders in app route handlers', async () => { const res = await next.fetch('/normal') const varyHeader = res.headers.get('vary') // Custom header is preserved expectVaryHeaderToContain(varyHeader, ['user-agent'])
{ "filepath": "test/e2e/vary-header/test/index.test.ts", "language": "typescript", "file_size": 1661, "cut_index": 537, "middle_length": 229 }
import React 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 }) ...
IsVisible(false) }) if (!statusRef.current.wasInitialized) { console.error('callback ref was not initialized') } if (!statusRef.current.wasCleanedUp) { console.error('callback ref was not cleaned up')
statusRef.current.wasInitialized = true return () => { statusRef.current.wasCleanedUp = true } }, []) useEffect(() => { const timeout = setTimeout( () => { flushSync(() => { set
{ "filepath": "test/e2e/link-ref-app/app/child-ref-func-cleanup/page.js", "language": "javascript", "file_size": 1292, "cut_index": 524, "middle_length": 229 }
{ FileRef, nextTestSetup } from 'e2e-utils' import { renderViaHTTP, fetchViaHTTP } from 'next-test-utils' import path from 'path' import cheerio from 'cheerio' const appDir = path.join(__dirname, 'app') // TODO: This test needs to check multiple files and syntax features. describe.skip('Browserslist', () => { const...
.toArray() .map(async (el) => { const src = $(el).attr('src') const res = await fetchViaHTTP(next.url, src) const code = await res.text() if (code.includes('async ()=>')) {
}, }) it('should apply browserslist target', async () => { const html = await renderViaHTTP(next.url, '/') const $ = cheerio.load(html) expect( ( await Promise.all( $('script')
{ "filepath": "test/e2e/browserslist/browserslist.test.ts", "language": "typescript", "file_size": 1180, "cut_index": 518, "middle_length": 229 }
m Server $title', ({ title, useHttps }) => { // The HTTPS server presents a self-signed certificate that the test process // does not trust. Pass a custom agent that skips cert verification on every // HTTPS request. Setting `process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'` // does not take effect from inside th...
skipDeployment: true, disableAutoSkewProtection: true, }) if (skipped) return it('should serve internal file from render', async () => { const html = await next.render('/static/hello.txt', undefined, { agent }) expect(htm
next, skipped } = nextTestSetup({ files: __dirname, startCommand: 'node server.js', serverReadyPattern: /- Local:/, env: { USE_HTTPS: useHttps, NODE_ENV: sharedNodeEnv }, dependencies: sharedDeps,
{ "filepath": "test/e2e/custom-server/custom-server.test.ts", "language": "typescript", "file_size": 11380, "cut_index": 921, "middle_length": 229 }
f */ export function invokeNodeAPI(useCase) { let handle if (useCase === 'Buffer') { Buffer.from('') } else if (useCase === 'setImmediate') { handle = setImmediate(() => {}) } else if (useCase === 'clearImmediate') { clearImmediate(handle) } else if (useCase === 'process.cwd') { console.log(pr...
else if (useCase === 'CountQueuingStrategy') { new CountQueuingStrategy() } else if (useCase === 'DecompressionStream') { new DecompressionStream() } else if (useCase === 'DomException') { new DomException() } else if (useCase === 'Messag
ase === 'BroadcastChannel') { new BroadcastChannel() } else if (useCase === 'ByteLengthQueuingStrategy') { new ByteLengthQueuingStrategy() } else if (useCase === 'CompressionStream') { new CompressionStream() }
{ "filepath": "test/e2e/edge-runtime-with-node.js-apis/lib/utils.js", "language": "javascript", "file_size": 1852, "cut_index": 537, "middle_length": 229 }
port { nextTestSetup, isNextDev, isNextStart } from 'e2e-utils' ;((isNextDev && process.env.TURBOPACK_BUILD) || (isNextStart && process.env.TURBOPACK_DEV) ? describe.skip : describe)('Catches Missing getStaticProps', () => { const errorRegex = /getStaticPaths was added without a getStaticProps in/ const { ne...
it next.render('/hello') expect(html).toMatch(errorRegex) }) } if (isNextStart) { it('should catch it in server build mode', async () => { const { cliOutput } = await next.build() expect(cliOutput).toMatch(errorRegex) })
nst html = awa
{ "filepath": "test/e2e/catches-missing-getStaticProps/catches-missing-getStaticProps.test.ts", "language": "typescript", "file_size": 791, "cut_index": 514, "middle_length": 14 }
it.skip) const isModeDeploy = process.env.NEXT_TEST_MODE === 'deploy' describe('Middleware custom matchers', () => { if ((global as any).isNextDeploy && process.env.TEST_NODE_MIDDLEWARE) { return it('should skip deploy for now', () => {}) } const { next } = nextTestSetup({ files: new FileRef(join(__dir...
')).toBeDefined() const res2 = await fetchViaHTTP(next.url, '/missing-match-1', undefined, { headers: { hello: 'world', }, }) expect(res2.headers.get('x-from-middleware')).toBeFalsy() const res3 = await f
} : {}, }) const runTests = () => { it('should match missing header correctly', async () => { const res = await fetchViaHTTP(next.url, '/missing-match-1') expect(res.headers.get('x-from-middleware
{ "filepath": "test/e2e/middleware-custom-matchers/test/index.test.ts", "language": "typescript", "file_size": 5900, "cut_index": 716, "middle_length": 229 }
rom 'next/server' export default function middleware(request) { const res = NextResponse.rewrite(new URL('/', request.url)) res.headers.set('X-From-Middleware', 'true') return res } export const config = { runtime: 'nodejs', matcher: [ { source: '/source-match' }, { source: '/has-match-1', ...
ue)', }, ], }, { source: '/has-match-4', has: [ { type: 'host', value: 'example.com', }, ], }, { source: '/has-match-5', has: [ { type: 'heade
{ type: 'query', key: 'my-query', }, ], }, { source: '/has-match-3', has: [ { type: 'cookie', key: 'loggedIn', value: '(?<loggedIn>tr
{ "filepath": "test/e2e/middleware-custom-matchers/app/middleware-node.js", "language": "javascript", "file_size": 1850, "cut_index": 537, "middle_length": 229 }
import { retry } from 'next-test-utils' import { join } from 'path' const locales = ['', '/en', '/sv', '/nl'] describe('i18n-ignore-redirect-source-locale with basepath', () => { const { next } = nextTestSetup({ files: { pages: new FileRef(join(__dirname, 'app/pages')), }, dependencies: {}, ne...
, permanent: false, locale: false, }, { source: '/:locale/to-slash', destination: '/newpage', permanent: false, locale: false, }, {
source: '/:locale/to-sv', destination: '/sv/newpage', permanent: false, locale: false, }, { source: '/:locale/to-en', destination: '/en/newpage'
{ "filepath": "test/e2e/i18n-ignore-redirect-source-locale/redirects-with-basepath.test.ts", "language": "typescript", "file_size": 2483, "cut_index": 563, "middle_length": 229 }
isNextDev } from 'e2e-utils' describe('Router prefetch', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should resolve prefetch promise', async () => { const browser = await next.browser('/') const text = await browser .elementByCss('#prefetch-button') .click() ....
const browser = await next.browser('/') const links = await browser .elementByCss('#prefetch-button') .click() .elementsByCss('link[rel=prefetch]') expect(links.length).toBe(0) await browser.close() }) } })
() => {
{ "filepath": "test/e2e/router-prefetch/router-prefetch.test.ts", "language": "typescript", "file_size": 806, "cut_index": 536, "middle_length": 14 }
est-utils' import path from 'path' import type { Response } from 'node-fetch' async function serialize(response: Response) { return { text: await response.text(), headers: Object.fromEntries(response.headers), status: response.status, } } describe('Edge can read request body', () => { const { next }...
-handler=json', null, { method: 'POST', body: JSON.stringify({ hello: 'world' }), } ) expect(await serialize(response)).toMatchObject({ text: expect.stringContaining('ok'), status: 200
.url, '/api/nothing') expect(html).toContain('ok') }) describe('middleware', () => { it('reads a JSON body', async () => { const response = await fetchViaHTTP( next.url, '/api/nothing?middleware
{ "filepath": "test/e2e/edge-can-read-request-body/index.test.ts", "language": "typescript", "file_size": 3144, "cut_index": 614, "middle_length": 229 }
import { nextTestSetup, isNextDev, isNextStart } from 'e2e-utils' ;((isNextDev && process.env.TURBOPACK_BUILD) || (isNextStart && process.env.TURBOPACK_DEV) ? describe.skip : describe)('Custom routes', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should rewrite and render page corr...
st data = await next.render('/docs/static/data.json') expect(data).toContain('some data...') }) it('should rewrite to public file correctly', async () => { const data = await next.render('/docs/another.txt') expect(data).toContain('some te
bundlePath = `/docs/_next/static/${next.buildId}/_buildManifest.js` const data = await next.render(bundlePath) expect(data).toContain('/hello') }) it('should rewrite to public/static correctly', async () => { con
{ "filepath": "test/e2e/custom-routes-catchall/custom-routes-catchall.test.ts", "language": "typescript", "file_size": 1010, "cut_index": 512, "middle_length": 229 }
nextConfig = { reactStrictMode: true, rewrites: async () => { return { beforeFiles: [ { source: '/', destination: '/foo', }, { source: '/rewrite-to-another-segment/:id', destination: '/rewrite-to-another-segment/:id/foo', }, /...
ame-segment/2', destination: '/rewrite-to-same-segment/002', }, { source: '/rewrite-to-same-segment/3', destination: '/rewrite-to-same-segment/003', }, ], } }, } module.exports = nextConfig
}, { source: '/rewrite-to-s
{ "filepath": "test/e2e/use-router-with-rewrites/next.config.js", "language": "javascript", "file_size": 868, "cut_index": 559, "middle_length": 52 }
mport { nextTestSetup } from 'e2e-utils' describe('Custom routes i18n with index redirect', () => { 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 it('shoul...
ext).toEqual(dest) if (dest.startsWith('/')) { const parsed = new URL(res.headers.get('location')) expect(parsed.pathname).toBe(dest) expect(parsed.search).toBe('') } else { expect(res.headers.get('lo
fr/destination'], ]) { const res = await next.fetch(path, { redirect: 'manual', }) expect(res.status).toBe(dest ? 307 : 404) if (dest) { const text = await res.text() expect(t
{ "filepath": "test/e2e/custom-routes-i18n-index-redirect/custom-routes-i18n-index-redirect.test.ts", "language": "typescript", "file_size": 1051, "cut_index": 513, "middle_length": 229 }