from 'next/link'

if (typeof window !== 'undefined') {
  window.caughtErrors = []
  const origError = window.console.error

  window.console.error = function (...args) {
    window.caughtErrors.push(args.join(' '))
    return origError(...args)
  }
}

export default function Invalid() {
  return (
    <>

invalid page

      <Link href="/another" as="//google.com" id="page-with-as-slashes">
        to /another as //google.com
      </Link>

      <Link href="//google.com

oogle.com#hello" id="href-with-slashes-hash">
        to //google.com#hello
      </Link>

      <Link href="/another" as="\/\/google.com" id="page-with-as-backslashes">
        to /another as \\/\\/google.com
      </Link>

" id="href-with-slashes">
        to //google.com
      </Link>

      <Link href="//google.com?hello=1" id="href-with-slashes-query">
        to //google.com?hello=1
      </Link>

      <Link href="//g


ort { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'

const EXPECTED_WARNING =
  'The Edge Runtime is deprecated. You can use the "nodejs" runtime instead.'

describe('edge-runtime-deprecated', () => {
  const { next, isNextDev } = nextTestSetup({
    files: __dirname,
  })

  it('should warn about deprecated edge runtime', async () => {
    if (isNextDev) {
      // In dev mode, the warning fires when the edge route is first compiled.
      await next.fetch('/edge-route')
    }

piled, but
      // another request ensures no duplicate warnings).
      await next.fetch('/edge-route')
    }

    await retry(async () => {
      expect(next.cliOutput).toContain(EXPECTED_WARNING)
    })

    const occurrences = next.cliOutput.split(EXP

   await retry(async () => {
      expect(next.cliOutput).toContain(EXPECTED_WARNING)
    })
  })

  it('should only warn once', async () => {
    if (isNextDev) {
      // Trigger compilation of the edge route again (already com


from 'e2e-utils'
import { fetchViaHTTP } from 'next-test-utils'

describe('i18n API support', () => {
  const { next } = nextTestSetup({
    files: {
      'pages/api/hello.js': `
        export default function handler(req, res) {
          res.end('hello world')
        }
      `,
      'pages/api/blog/[slug].js': `
        export default function handler(req, res) {
          res.end('blog/[slug]')
        }
      `,
    },
    nextConfig: {
      i18n: {
        locales: ['en', 'fr'],
        defaultL

mple.vercel.sh/',
            },
          ],
        }
      },
    },
    dependencies: {},
  })

  it('should respond to normal API request', async () => {
    const res = await fetchViaHTTP(next.url, '/api/hello')
    expect(res.status).toBe(200)
    e

ocale: 'en',
      },
      async rewrites() {
        return {
          beforeFiles: [],
          afterFiles: [],
          fallback: [
            {
              source: '/api/:path*',
              destination: 'https://exa


t', (request) => {
            const url = new URL(request.url())
            requests.push(url.pathname)
          })
        },
      })

      if (!(global as any).isNextDev) {
        browser.elementByCss('#to-article-rewrite').moveTo()

        await retry(async () => {
          expect(requests.some((item) => item.includes('article'))).toBe(true)
        })
      }

      await browser.elementByCss('#to-article-rewrite').click()

      const preQuery = JSON.parse(await browser.elementByCss('pre').text

await next.fetch('/external-rewrite-body', {
        redirect: 'manual',
        method: 'POST',
        body,
      })
      expect(res.status).toBe(200)
      expect(await res.text()).toEqual(body)
    })

    it('should handle middleware rewrite with bo

())
      expect(preQuery).toEqual({ slug: ['foo', 'bar', '123'] })
    })

    it('should handle next.config.js rewrite with body correctly', async () => {
      const body = JSON.stringify({ hello: 'world' })
      const res =


extUrl

  if (url.pathname.includes('article')) {
    return NextResponse.next()
  }

  // this is needed for tests to get the BUILD_ID
  if (url.pathname.startsWith('/_next/static/__BUILD_ID')) {
    return NextResponse.next()
  }

  if (url.pathname.includes('/to/some/404/path')) {
    return NextResponse.next({
      'x-matched-path': '/404',
    })
  }

  if (
    url.pathname.includes(
      '/middleware-external-rewrite-body-headers-return-body'
    )
  ) {
    const tmpHeaders = new Headers(request.h

 },
      }
    )
  }

  if (
    url.pathname.includes(
      '/middleware-external-rewrite-body-headers-return-headers'
    )
  ) {
    const tmpHeaders = new Headers(request.headers)

    tmpHeaders.set('x-hello-from-middleware1', 'hello')

    return N

eaders)

    tmpHeaders.set('x-hello-from-middleware1', 'hello')

    return NextResponse.rewrite(
      'https://next-data-api-endpoint.vercel.app/api/echo-body',
      {
        request: {
          headers: tmpHeaders,


cales: ['ja', 'en', 'fr', 'es'],
    defaultLocale: 'en',
  },
  rewrites() {
    return {
      beforeFiles: [
        {
          source: '/beforefiles-rewrite',
          destination: '/ab-test/a',
        },
      ],
      afterFiles: [
        {
          source: '/article/:slug*',
          destination: '/detail/:slug*',
        },
        {
          source: '/afterfiles-rewrite',
          destination: '/ab-test/b',
        },
        {
          source: '/afterfiles-rewrite-ssg',
          destinat

 {
          source: '/config-rewrite-to-dynamic-static/:rewriteSlug',
          destination: '/ssg',
        },
        {
          source: '/external-rewrite-body',
          destination:
            'https://next-data-api-endpoint.vercel.app/api/echo-bo

ion: '/fallback-true-blog/first',
        },


t default function Home({ locale }) {
  return (

{locale}

          <Link href="/i18n" locale="en" id="link-en">
            Go to en
          </Link>

          <Link href="/en/i18n" locale={false} id="link-en2">
            Go to en2
          </Link>

          <Link href="/i18n" locale="ja" id="link-ja">
            Go to ja
          </Link>

          <Li

         Go to ja2
          </Link>
        </li>
        <li>
          <Link href="/i18n" locale="fr" id="link-fr">
            Go to fr
          </Link>
        </li>
      </ul>
    </div>
  )
}

export const getServerSideProps = ({ query }) => ({

nk href="/ja/i18n" locale={false} id="link-ja2">


rom 'next/router'

export default function Home() {
  const router = useRouter()
  return (

Home Page

      <Link href="/article/foo/bar/123" id="to-article-rewrite">
        to /article/foo/bar/123
      </Link>

      <Link href="/rewrite-to-ab-test">A/B test homepage</Link>

      <Link
        href="/rewrite-me-to-about?override=internal"
        id="rewrite-me-to-about"
      >
        Rewrite me to about
      </Link>

-afterfiles-rewrite"
        id="rewrite-to-afterfiles-rewrite"
      >
        Rewrite me to afterFiles Rewrite
      </Link>

      <Link href="/rewrite-me-to-vercel">Rewrite me to Vercel</Link>

      <Link href="/rewrite-me-ex

      <Link
        href="/rewrite-to-beforefiles-rewrite"
        id="rewrite-to-beforefiles-rewrite"
      >
        Rewrite me to beforeFiles Rewrite
      </Link>

      <Link
        href="/rewrite-to


 { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'

describe('AppTree', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  it('should provide router context in AppTree on SSR', async () => {
    let html = await next.render('/')
    expect(html).toMatch(/page:.*?\//)

    html = await next.render('/another')
    expect(html).toMatch(/page:.*?\/another/)
  })

  it('should provide router context in AppTree on CSR', async () => {
    const browser = await next.br

r.eval(`document.documentElement.innerHTML`)
      expect(html).toMatch(/page:.*?\//)
    })

    await browser.elementByCss('#home').click()
    await retry(async () => {
      html = await browser.eval(`document.documentElement.innerHTML`)
      expect(h

owser('/')
    let html = await browser.eval(`document.documentElement.innerHTML`)
    expect(html).toMatch(/page:.*?\//)

    await browser.elementByCss('#another').click()
    await retry(async () => {
      html = await browse


import Link from 'next/link'
import { useRouter } from 'next/router'

export default function Page(props) {
  if (useRouter().isFallback) {
    return
Loading...

  }

  return (
    <>

{JSON.stringify(props)}

      <Link
        href="/fallback-true-blog/first?hello=world"
        shallow
        id="to-query-shallow"
      >
        to /fallback-true-blog/first?hello=world
      </Link>

      <Link href="/fallback-true-blog/second" shallow id="to-no-query-shallow

llback-true-blog/build-time-2',
      '/fallback-true-blog/build-time-3',
      '/fallback-true-blog/build-time-4',
    ],
    fallback: true,
  }
}

export function getStaticProps({ params }) {
  return {
    props: {
      params,
      time: Date.now(),

">
        to /fallback-true-blog/second
      </Link>
      <br />
    </>
  )
}

export function getStaticPaths() {
  return {
    paths: [
      '/fallback-true-blog/first',
      '/fallback-true-blog/build-time-1',
      '/fa


t origConfigContent: string

  beforeAll(async () => {
    externalPort = await findPort()
    externalServer = http.createServer((req, res) => {
      res.statusCode = 200
      res.end(JSON.stringify({ url: req.url, external: true }))
    })
    await new Promise<void>((resolve, reject) => {
      externalServer.listen(externalPort, (err?: Error) =>
        err ? reject(err) : resolve()
      )
    })

    await next.patchFile('next.config.js', (content) =>
      content.replace(/__EXTERNAL_PORT__/g, Stri

.port
    if (!isNextDev) {
      ctx.buildId = (await next.readFile('.next/BUILD_ID')).trim()
      ctx.buildPagesDir = join(next.testDir, '.next/server/pages')
    } else {
      ctx.buildId = 'development'
    }
  })

  afterAll(() => {
    externalServ

ng(externalPort))
    )
    origConfigContent = await next.readFile('next.config.js')

    if (!isNextDev) {
      await next.build()
    }
    await next.start()

    ctx.appDir = next.testDir
    ctx.appPort = new URL(next.url)


ilingSlash: true,
  i18n: {
    // localeDetection: false,
    locales: [
      'nl-NL',
      'nl-BE',
      'nl',
      'fr-BE',
      'fr',
      'en-US',
      'en',
      'go',
      'go-BE',
      'do',
      'do-BE',
    ],
    defaultLocale: 'en-US',
    domains: [
      {
        http: true,
        domain: 'example.do',
        defaultLocale: 'do',
        locales: ['do-BE'],
      },
      {
        domain: 'example.com',
        defaultLocale: 'go',
        locales: ['go-BE'],
      },
    ],

  destination: '/somewhere-else',
        permanent: false,
        locale: false,
      },
      {
        source: '/redirect-3',
        destination: '/somewhere-else',
        permanent: false,
      },
      {
        source: '/redirect-4',
        des

},
  async redirects() {
    return [
      {
        source: '/en-US/redirect-1',
        destination: '/somewhere-else',
        permanent: false,
        locale: false,
      },
      {
        source: '/nl/redirect-2',


rt,
        `${ctx.basePath || ''}/${locale}/files/texts/file.txt`,
        undefined,
        { redirect: 'manual' }
      )

      if (!defaultLocales.includes(locale)) {
        expect(res.status).toBe(404)
        expect(await res.text()).toContain('could not be found')
      } else {
        // We only 404 for non-default locale
        expect(res.status).toBe(200)
      }
    }
  })

  it('should redirect external domain correctly', async () => {
    const res = await fetchViaHTTP(
      ctx.appPort,

ders.get('location')).toBe('https://jobs.example.com/')

    const res2 = await fetchViaHTTP(
      ctx.appPort,
      `${ctx.basePath || ''}/redirect-5`,
      undefined,
      {
        redirect: 'manual',
      }
    )

    expect(res2.status).toBe(307)

      `${ctx.basePath || ''}/do/redirect-5`,
      undefined,
      {
        headers: {
          'accept-language': 'do',
        },
        redirect: 'manual',
      }
    )

    expect(res.status).toBe(307)
    expect(res.hea


ink from 'next/link'
import { useRouter } from 'next/router'

export default function Page(props) {
  const router = useRouter()

  return (
    <>

another page

{JSON.stringify(props)}

{router.locale}

{router.defaultLocale}

{JSON.stringify(router.locales)}

{JSON.stringify(router.query)}

{router.

sPath}

      <Link href="/" id="to-index">
        to /
      </Link>

    </>
  )
}

export const getServerSideProps = ({ locale, locales, defaultLocale }) => {
  return {
    props: {
      locale,
      locales,
      defaultLocale,


from 'next/link'
import { useRouter } from 'next/router'

export default function Page(props) {
  const router = useRouter()

  return (
    <>

frank page

{JSON.stringify(props)}

{router.locale}

{router.defaultLocale}

{JSON.stringify(router.locales)}

{JSON.stringify(router.query)}

{router.pathname

<Link href="/gsp/fallback/first" id="to-fallback-first">
        to /gsp/fallback/first
      </Link>

      <Link href="/gsp/fallback/hello" id="to-fallback-hello">
        to /gsp/fallback/hello
      </Link>

      <Link href

}

{router.asPath}

      <Link href="/another" id="to-another">
        to /another
      </Link>

      <Link href="/gsp" id="to-gsp">
        to /gsp
      </Link>


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.asPath && asPath !== router.asPath) {
      setAsPath(router.asPath)
    }
  }, [router.asPath, router.isReady, asPath])

  return (
    <>

index page

      <p id="props

main-locales">{JSON.stringify(router.domainLocales)}

{JSON.stringify(router.query)}

{router.pathname}

{asPath}

      <Link href="/another" id="to-another"

">{JSON.stringify(props)}

{router.locale}

{router.defaultLocale}

{JSON.stringify(router.locales)}

      <p id="router-do


nk'
import { useRouter } from 'next/router'

export default function Page(props) {
  const router = useRouter()
  const { nextLocale } = router.query

  return (
    <>

links page

{JSON.stringify(props)}

{router.locale}

{router.defaultLocale}

{JSON.stringify(router.locales)}

{JSON.stringify(router.query)}

      <p id="router-p

ocale} id="to-gsp">
        to /gsp
      </Link>

      <Link
        href="/gsp/fallback/first"
        locale={nextLocale}
        id="to-fallback-first"
      >
        to /gsp/fallback/first
      </Link>

      <Link
        h

athname">{router.pathname}

{router.asPath}

      <Link href="/another" locale={nextLocale} id="to-another">
        to /another
      </Link>

      <Link href="/gsp" locale={nextL


nk'
import { useRouter } from 'next/router'

export default function Page(props) {
  const router = useRouter()
  const { nextLocale } = router.query

  return (
    <>

links page

{JSON.stringify(props)}

{router.locale}

{JSON.stringify(router.locales)}

{JSON.stringify(router.query)}

{router.pathname}

{ro

</Link>

      <Link
        href={`/${nextLocale}/gsp/fallback/first`}
        locale={false}
        id="to-fallback-first"
      >
        to /gsp/fallback/first
      </Link>

      <Link
        href={`/${nextLocale}/gsp/fallb

uter.asPath}

      <Link href={`/${nextLocale}/another`} locale={false} id="to-another">
        to /another
      </Link>

      <Link href={`/${nextLocale}/gsp`} locale={false} id="to-gsp">
        to /gsp


export default function Page(props) {
  const router = useRouter()

  return (
    <>

links page

{JSON.stringify(props)}

{router.locale}

{router.defaultLocale}

{JSON.stringify(router.locales)}

{JSON.stringify(router.query)}

{router.pathname}

{router.asPath}

s">
        to /gsp
      </Link>

      <Link href="/gsp" locale="nl-NL" id="to-gsp-nl-nl">
        to /gsp
      </Link>

      <Link href="/gsp" locale="fr" id="to-gsp-fr">
        to /gsp
      </Link>

      <Lin

<Link href="/gsp" locale="en-US" id="to-gsp-en-u


://localhost:__EXTERNAL_PORT__'

module.exports = {
  i18n: {
    // localeDetection: false,
    locales: ['nl-NL', 'nl-BE', 'nl', 'fr-BE', 'fr', 'en'],
    defaultLocale: 'en',
  },
  async rewrites() {
    return [
      {
        source: '/:path*',
        destination: '/:path*',
      },

      {
        source: '/en',
        destination: '/en/links',
        locale: false,
      },
      {
        source: '/nl-NL',
        destination: '/nl-NL/links',
        locale: false,
      },
      {
        so

t',
        destination: `${destination}/about`,
        locale: false,
      },
      {
        source: '/fr/about',
        destination: `${destination}/fr/about`,
        locale: false,
      },

      {
        source: '/en/catch-all/:path*',
        d

urce: '/fr',
        destination: `/fr/links`,
        locale: false,
      },
      {
        source: '/en/about',
        destination: `${destination}/about`,
        locale: false,
      },
      {
        source: '/nl-NL/abou


{ next, isNextDeploy, skipped } = nextTestSetup({
    files: __dirname,
    skipDeployment: true,
  })
  if (skipped) return
  if (isNextDeploy) return

  it('should alias components', async () => {
    const $ = await next.render$('/basic-alias')
    expect($('body').text()).toMatch(/World/)
  })

  it('should resolve the first item in the array first', async () => {
    const $ = await next.render$('/resolve-order')
    expect($('body').text()).toMatch(/Hello from a/)
  })

  it('should resolve the second

ait next.render$('/single-alias')
    expect($('body').text()).toMatch(/Hello/)
  })

  if (isNextDev) {
    it('should have correct module not found error', async () => {
      const originalContent = await next.readFile('pages/basic-alias.js')

      try

 item as fallback', async () => {
    const $ = await next.render$('/resolve-fallback')
    expect($('body').text()).toMatch(/Hello from only b/)
  })

  it('should resolve a single matching alias', async () => {
    const $ = aw


import { nextTestSetup } from 'e2e-utils'

describe('next-image-src-with-query-without-local-patterns', () => {
  const { next, isNextDev, skipped } = nextTestSetup({
    files: __dirname,
    skipStart: true,
    skipDeployment: true,
  })

  if (skipped) {
    return
  }

  it('should throw error for relative image with query without localPatterns', async () => {
    if (isNextDev) {
      await next.start()
      await next.browser('/')
      expect(next.cliOutput).toContain(
        'Image with src "/te

build()
      expect(cliOutput).toContain(
        'Image with src "/test.png?v=1" is using a query string which is not configured in images.localPatterns.\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns'
      )
    }

st.png?v=1" is using a query string which is not configured in images.localPatterns.\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns'
      )
    } else {
      const { cliOutput } = await next.


ip-trailing-slash-redirect', () => {
  const { next } = nextTestSetup({
    files: new FileRef(join(__dirname, 'app')),
    dependencies: {},
  })

  // the tests below are run in both pages and app dir to ensure the behavior is the same
  // the other cases aren't added to this block since they are either testing pages-specific behavior
  // or aren't specific to either router implementation
  async function runSharedTests(basePath: string) {
    it('should not apply trailing slash redirect (with slash)',

it res.text()).toContain('another page')
    })

    it('should not apply trailing slash redirect (without slash)', async () => {
      const res = await fetchViaHTTP(
        next.url,
        `${basePath}another`,
        undefined,
        {
          r

async () => {
      const res = await fetchViaHTTP(
        next.url,
        `${basePath}another/`,
        undefined,
        {
          redirect: 'manual',
        }
      )
      expect(res.status).toBe(200)
      expect(awa


cHeader = 'X-From-Src-Middleware'
const rootHeader = 'X-From-Root-Middleware'

describe('middleware-src-node', () => {
  const { next, isTurbopack, skipped } = nextTestSetup({
    files: __dirname,
    skipStart: true,
    skipDeployment: true,
  })
  if (skipped) return

  if (isNextDev) {
    beforeAll(async () => {
      await next.start()
    })
  }

  describe('Middleware in src/ folder', () => {
    if (isNextDev) {
      it('loads and runs src middleware', async () => {
        const response = await

 export', async () => {
        await next.patchFile(
          'next.config.js',
          "module.exports = { output: 'export' }"
        )
        await next.build()
        expect(next.cliOutput).toContain(
          'Statically exporting a Next.js app

 next.fetch('/post-1')
        expect(response.headers.has(srcHeader)).toBe(false)
        expect(response.headers.has(`${srcHeader}-TS`)).toBe(true)
      })
    }

    if (!isNextDev) {
      it('should warn about middleware on


mport { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'

const expectedErr =
  /Webpack config is undefined. You may have forgot to return properly from within the "webpack" method of your next.config.js/

// Webpack-specific test, not needed for Turbopack
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
  'undefined webpack config error',
  () => {
    const { next, isNextDev, isNextStart, skipped } = nextTestSetup({
      files: __dirname,
      skipStart: true,

build()
        expect(cliOutput).toMatch(expectedErr)
      })
    })
    ;(isNextDev ? it : it.skip)(
      'should show error in development mode',
      async () => {
        await next.start()
        await retry(async () => {
          expect(next.cl

skipDeployment: true,
    })
    if (skipped) return
    ;(isNextStart ? describe : describe.skip)('production mode', () => {
      it.skip('should show in production mode', async () => {
        const { cliOutput } = await next.


G_MESSAGE = `ERROR: This build is using Turbopack, with a \`webpack\` config and no \`turbopack\` config.`

const itif = (condition: boolean) => (condition ? it : it.skip)

const page = {
  'app/page.js': `
export default function Page() {
  return
hello world

}
`,
}

;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
  'config-turbopack',
  () => {
    describe('when turbopack is auto selected', () => {
      describe('when webpack is configured but Turbopack is not', () => {
        const

         ...page,
            'next.config.js': `
          module.exports = {
            webpack: (config) => {
              return config
            },
          }
        `,
          },
        })

        itif(isNextDev)('warns', async () => {

 { next, isNextDev, isNextStart } = nextTestSetup({
          skipStart: Boolean(process.env.NEXT_TEST_MODE === 'start'),
          turbo: false,
          env: {
            TURBOPACK: 'auto',
          },
          files: {


eact'
import Router, { withRouter } from 'next/router'
import Link from 'next/link'

const pages = {
  '/a': 'Foo',
  '/b': 'Bar',
}

class HeaderNav extends React.Component {
  constructor({ router }) {
    super()

    this.state = {
      activeURL: router.asPath,
      activeURLTopLevelRouterDeprecatedBehavior: router.asPath,
      activeURLTopLevelRouter: router.asPath,
    }
  }

  componentDidMount() {
    Router.onRouteChangeComplete =
      this.handleRouteChangeTopLevelRouterDeprecatedBehavior

ngeComplete = null
    Router.events.off(
      'routeChangeComplete',
      this.handleRouteChangeTopLevelRouter
    )
    this.props.router.events.off('routeChangeComplete', this.handleRouteChange)
  }

  handleRouteChange = (url) => {
    this.setState(

 Router.events.on(
      'routeChangeComplete',
      this.handleRouteChangeTopLevelRouter
    )
    this.props.router.events.on('routeChangeComplete', this.handleRouteChange)
  }

  componentWillUnmount() {
    Router.onRouteCha


ForNoRedbox,
} from 'next-test-utils'

describe('module layer', () => {
  const { next, isNextStart, isNextDev, isNextDeploy } = nextTestSetup({
    files: __dirname,
  })

  function runTests() {
    const routes = [
      // app client components pages
      '/app/client',
      '/app/client-edge',
      // app sever components pages
      '/app/server',
      '/app/server-edge',
      // app routes
      '/app/route',
      '/app/route-edge',
      // pages/api
      '/api/default',
      '/api/default-e

    const { status } = await next.fetch(route)
        expect([route, status]).toEqual([route, 200])
      })
    }

    it('should render installed react-server condition for middleware', async () => {
      const json = await next.fetch('/middleware').th

dge',
      '/api/server-only',
      '/api/server-only-edge',
      '/api/mixed',
    ]

    for (const route of routes) {
      it(`should render routes marked with restriction marks without errors ${route}`, async () => {


tion Home() {
  return (
    <div className="flex min-h-screen items-center justify-center bg-zinc-50 font-sans dark:bg-black font-[family-name:var(--font-geist-sans)]">
      <main className="flex min-h-screen w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
        <Image
          className="dark:invert"
          src="/next.svg"
          alt="Next.js logo"
          width={100}
          height={20}
          priority
        />
        <div cla

 the page.tsx file.
          </h1>
          <p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
            Looking for a starting point or more instructions? Head over to{' '}
            <a
              href="https://vercel.com

ssName="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
          <h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
            To get started, edit


import Link from 'next/link'
import { createContext } from 'react'
import { flushSync } from 'react-dom'
import { createRoot } from 'react-dom/client'
import App, { AppContext } from 'next/app'
import { renderToString } from 'react-dom/server'

export const DummyContext = createContext(null) as React.Context<string | null>

export default class MyApp extends App<{ html: string }> {
  static async getInitialProps({ Component, AppTree, ctx }: AppContext) {
    let pageProps = {}

    if (Component.getInitial

.createElement('div')
      document.querySelector('body')?.appendChild(el)
      flushSync(() => {
        createRoot(el).render(toRender)
      })
      html = el.innerHTML
      el.remove()
    } else {
      html = renderToString(toRender)
    }

    r

Props) {
      pageProps = await Component.getInitialProps(ctx)
    }

    let html: string
    const toRender = <AppTree pageProps={pageProps} another="prop" />

    if (typeof window !== 'undefined') {
      const el = document


eact from 'react'
import { flushSync } from 'react-dom'
import { createRoot } from 'react-dom/client'
import { renderToString } from 'react-dom/server'
import { NextPage } from 'next'

const Page: NextPage<{ html: string }> = ({ html }) =>
  html ? (
    <>

saved:

    </>
  ) : (

Hello world

  )

Page.getInitialProps = async ({ AppTree }) => {
  let html: string

  const toRender = <AppTree pageProps={{}} />

  if (typeof windo

lement('div')
    document.querySelector('body')?.appendChild(el)
    flushSync(() => {
      createRoot(el).render(toRender)
    })
    html = el.innerHTML
    el.remove()
  } else {
    html = renderToString(toRender)
  }

  return { html }
}

export def

w !== 'undefined') {
    const el = document.createE


ort { join } from 'path'
import cheerio from 'cheerio'
import { fetchViaHTTP } from 'next-test-utils'
import { FileRef, nextTestSetup } from 'e2e-utils'

describe('Middleware base tests', () => {
  const { next } = nextTestSetup({
    files: {
      pages: new FileRef(join(__dirname, '../app/pages')),
      'middleware.js': new FileRef(join(__dirname, '../app/middleware.js')),
      'next.config.js': new FileRef(join(__dirname, '../app/next.config.js')),
    },
  })

  it('should execute from absolute paths

await browser.close()
    }

    const res = await fetchViaHTTP(next.url, '/root/redirect-with-basepath')
    const html = await res.text()
    const $ = cheerio.load(html)
    expect($('.title').text()).toBe('About Page')
  })

  it('router.query must exi

', async () => {
    const browser = await next.browser('/redirect-with-basepath')
    try {
      expect(await browser.eval(`window.location.pathname`)).toBe(
        '/root/redirect-with-basepath'
      )
    } finally {


module.exports = {
  webpack: (config, { isServer }) => {
    if (!isServer) {
      const optimization = config.optimization || {}
      const splitChunks = optimization.splitChunks || {}
      const cacheGroups = splitChunks.cacheGroups || {}

      config.optimization = {
        ...optimization,
        splitChunks: {
          ...splitChunks,
          cacheGroups: {
            ...cacheGroups,
            requiredByApp: {
              test: /requiredByApp.js/,
              name: 'requiredByApp',

/,
              name: 'requiredByPage',
              enforce: true,
              priority: 10,
              chunks: 'all',
              filename: 'static/chunks/[name].[chunkhash].js',
            },
          },
        },
      }
    }

    return c

           enforce: true,
              priority: 10,
              chunks: 'all',
              filename: 'static/chunks/[name].[chunkhash].js',
            },
            requiredByPage: {
              test: /requiredByPage.js


('next-link', () => {
  const { skipped, next, isNextDev } = nextTestSetup({
    files: __dirname,
    skipDeployment: true,
  })

  if (skipped) return

  it('errors on invalid href', async () => {
    const browser = await next.browser('/invalid-href')

    if (isNextDev) {
      await expect(browser).toDisplayRedbox(`
       {
         "code": "E319",
         "description": "Failed prop type: The prop \`href\` expects a \`string\` or \`object\` in \`<Link>\`, but got \`undefined\` instead.
       Open y

</Link>
           |          ^",
         "stack": [
           "Hello app/invalid-href/page.js (6:10)",
         ],
       }
      `)
    }
    // Client errors show "This page couldn\u2019t load"
    expect(await browser.elementByCss('body').text()).toC

our browser's console to view the Component stack trace.",
         "environmentLabel": null,
         "label": "Runtime Error",
         "source": "app/invalid-href/page.js (6:10) @ Hello
       > 6 |   return <Link>Hello, Dave!


'
import { nextTestSetup, isNextDev } from 'e2e-utils'

describe('Custom routes i18n', () => {
  const { next, skipped } = nextTestSetup({
    files: __dirname,
    skipStart: true,
    skipDeployment: true,
  })
  if (skipped) return

  let server: http.Server
  let externalPort: number

  beforeAll(async () => {
    externalPort = await findPort()
    server = http.createServer((req, res) => {
      res.statusCode = 200
      res.end(
        `<p id='data'>${JSON.stringify({
          url: req.url,

ace(/__EXTERNAL_PORT__/g, String(externalPort))
    )

    if (!isNextDev) {
      await next.build()
    }
    await next.start()
  })

  afterAll(() => {
    server.close()
  })

  it('should respond to default locale redirects correctly', async () => {

  })}</p>`
      )
    })
    await new Promise<void>((res, rej) => {
      server.listen(externalPort, (err?: Error) => (err ? rej(err) : res()))
    })

    await next.patchFile('next.config.js', (content) =>
      content.repl


th'

const describeCase = (
  caseName: string,
  callback: (context: ReturnType<typeof nextTestSetup>) => void
) => {
  describe(caseName, () => {
    const context = nextTestSetup({
      files: path.join(__dirname, caseName),
      skipDeployment: true,
    })
    if (context.skipped) return

    callback(context)
  })
}
describe('Instrumentation Hook', () => {
  describeCase('with-esm-import', ({ next }) => {
    it('with-esm-import should run the instrumentation hook', async () => {
      await next.re

entation hook', async () => {
      await next.render('/')
      await check(() => next.cliOutput, /instrumentation hook on the edge/)
    })
  })

  describeCase('with-edge-api', ({ next }) => {
    it('with-edge-api should run the instrumentation hook',

nder('/')
      await check(
        () => next.cliOutput,
        /register in instrumentation\.js is running/
      )
    })
  })

  describeCase('with-middleware', ({ next }) => {
    it('with-middleware should run the instrum


rl = new URL(req.url)
  const origPathname = parsedOrigUrl.pathname
  const lowerPathname = origPathname.toLowerCase()

  // ensure locale casing can be redirected
  if (
    (lowerPathname.startsWith('/en') || lowerPathname.startsWith('/ja-jp')) &&
    origPathname !== lowerPathname &&
    !lowerPathname.includes('_next')
  ) {
    parsedOrigUrl.pathname = lowerPathname
    return NextResponse.redirect(parsedOrigUrl)
  }

  console.log(req.nextUrl)
  let { pathname } = req.nextUrl

  if (pathname.startsWit

ned-rewrite')) {
    if (pathname.startsWith('/en')) {
      pathname = pathname.replace(/^\/en/, '') || '/'
    }

    if (pathname === '/docs') {
      pathname = '/'
    }

    console.log(
      `rewriting to https://middleware-external-rewrite-target.

h('/_next/data') && pathname.includes('locale-test')) {
    return NextResponse.json({
      locale: req.nextUrl.locale,
      pathname: req.nextUrl.pathname,
    })
  }

  if (pathname.includes('docs') || pathname.includes('chai


waitForNoRedbox, renderViaHTTP } from 'next-test-utils'
import cheerio from 'cheerio'

describe('Type module interop', () => {
  const { next } = nextTestSetup({
    files: {
      'pages/index.js': `
        import Link from 'next/link'
        import Head from 'next/head'
        import Script from 'next/script'
        import dynamic from 'next/dynamic'

        const Dynamic = dynamic(() => import('../components/example'))

        export default function Page() {
          return (
            <>

         <Head>
                <title>This page has a title 🤔</title>
                <meta charSet="utf-8" />
                <meta name="viewport" content="initial-scale=1.0, width=device-width" />
              </Head>


import { FileRef, isNextStart, nextTestSetup } from 'e2e-utils'
import { listClientChunks } from 'next-test-utils'

describe('Middleware Runtime', () => {
  const { next } = nextTestSetup({
    files: new FileRef(join(__dirname, 'app')),
  })
  let testPaths: Array<{ testPath: string }> = [
    { testPath: '/file.svg' },
    { testPath: '/vercel copy.svg' },
    { testPath: '/vercel%20copy.svg' },
    { testPath: '/another%2ffile.svg' },
    { testPath: '/another/file.svg' },
    { testPath: '/another/hello

  { testPath: '/glob/hello' },
    { testPath: '/pages-another/hello' },
    { testPath: '/pages-another%2fhello' },
    { testPath: '/pages-dynamic%2f/first' },
    { testPath: '/pages-dynamic/first' },
    { testPath: '/pages-glob%2fhello' },
    { testP

' },
    { testPath: '/another%2fhello' },
    { testPath: '/glob%2ffile.svg' },
    { testPath: '/glob/file.svg' },
    { testPath: '/dynamic%2f/first' },
    { testPath: '/dynamic/first' },
    { testPath: '/glob%2fhello' },


om 'next/link'
import type { GetStaticProps } from 'next'

type Props = {
  random: number
  draftMode: string
}

export const getStaticProps: GetStaticProps<Props> = ({ draftMode }) => {
  return {
    props: {
      random: Math.random(),
      draftMode: Boolean(draftMode).toString(),
    },
    revalidate: 100000,
  }
}

export default function Home(props: Props) {
  const [count, setCount] = useState(0)
  return (
    <>

Home

        Draft Mode: {props.draftMode}

=> setCount(count + 1)}>
        Increment
      </button>

        Count: {count}

        Random: {props.random}

      <Link href="/another">Visit another page</Link>

</em>
      </p>
      <button id="inc" onClick={()


tTestSetup, isNextDev } from 'e2e-utils'
;(isNextDev ? describe.skip : describe)('i18n-beforefiles-rewrite', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  const locales = ['en', 'fr']

  const autoStaticRoutes = [
    { pathname: '', content: 'index' },
    { pathname: '/home/a', content: 'Home A' },
    { pathname: '/home/b', content: 'Home B' },
    { pathname: '/dynamic/static', content: 'static route' },
    { pathname: '/dynamic/first', content: 'dynamic route' },
    { pathn

 const url = `/${locale}${pathname}`
        const res = await next.fetch(url)
        const html = await res.text()

        expect({ url, status: res.status }).toEqual({ url, status: 200 })
        expect(html).toContain(content)
      }
    }
  })

  it

ame: '/team/slug', content: '/[teamId]/[slug]' },
  ]

  it('should serve locale-prefixed auto-static pages', async () => {
    for (const { pathname, content } of autoStaticRoutes) {
      for (const locale of locales) {


from 'e2e-utils'
import { check } from 'next-test-utils'
describe('instrumentation-hook-rsc', () => {
  describe('instrumentation', () => {
    const { next, isNextDev, skipped } = nextTestSetup({
      files: __dirname,
      skipDeployment: true,
    })

    if (skipped) {
      return
    }

    it('should run the instrumentation hook', async () => {
      await next.render('/')
      await check(() => next.cliOutput, /instrumentation hook/)
    })
    it('should not overlap with a instrumentation page',

ext.render('/edge')
      await check(() => next.cliOutput, /instrumentation hook on the edge/)
    })
    if (isNextDev) {
      // TODO: Implement handling for changing the instrument file.
      it.skip('should reload the server when the instrumentation

 async () => {
      const page = await next.render('/instrumentation')
      expect(page).toContain('Hello')
    })
    it('should run the edge instrumentation compiled version with the edge runtime', async () => {
      await n


alid hrefs', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  const showsError = async (
    pathname: string,
    regex: RegExp,
    click = false,
    isWarn = false
  ) => {
    const browser = await next.browser(pathname)
    try {
      await browser.waitForElementByCss('#click-me')
      if (isWarn) {
        await browser.eval(`(function() {
          window.warnLogs = []
          var origWarn = window.console.warn
          window.console.warn = (...args) => {
            wi

 => setTimeout(resolve, 500))
      }
      if (isWarn) {
        await retry(async () => {
          const warnLogs = await browser.eval('window.warnLogs')
          expect(warnLogs.join('\n')).toMatch(regex)
        })
      } else {
        await waitFo

ndow.warnLogs.push(args.join(' '))
            origWarn.apply(window.console, args)
          }
        })()`)
      }
      if (click) {
        await browser.elementByCss('#click-me').click()
        await new Promise((resolve)


io.load(html)
  const nextData = $('#__NEXT_DATA__')
  const preEl = $('#props-pre')
  const routerData = JSON.parse($('#router').text())
  return {
    nextData: JSON.parse(nextData.html()!),
    pre: preEl.text(),
    routerData,
  }
}

describe('ServerSide Props Preview Mode', () => {
  const { next, skipped } = nextTestSetup({
    files: __dirname,
    // Assertions don't apply to deploy mode (output differs vs. local Next.js server).
    skipDeployment: true,
  })
  if (skipped) return

  if (isNextSta

plication', async () => {
      const res = await next.fetch('/')
      expect(res.status).toBe(200)
    })
  }

  it('should return page on first request', async () => {
    const html = await next.render('/')
    const { nextData, pre, routerData } = get

rt) {
    it('should compile successfully', async () => {
      expect(next.cliOutput).toMatch(/Compiled successfully/)
      expect(next.cliOutput).not.toContain('Build error occurred')
    })

    it('should start production ap


waitForRedbox, getRedboxHeader } from 'next-test-utils'

describe('withRouter', () => {
  const { next, isTurbopack, isNextDev } = nextTestSetup({
    files: __dirname,
  })

  ;(isTurbopack && isNextDev ? describe.skip : describe)(
    'production mode',
    () => {
      it('allows observation of navigation events using withRouter', async () => {
        const browser = await next.browser('/a')
        await browser.waitForElementByCss('#page-a')

        let activePage = await browser.elementByCss('.acti

    expect(activePage).toBe('Bar')
      })

      it('allows observation of navigation events using top level Router', async () => {
        const browser = await next.browser('/a')
        await browser.waitForElementByCss('#page-a')

        let activeP

ve').text()
        expect(activePage).toBe('Foo')

        await browser.elementByCss('button').click()
        await browser.waitForElementByCss('#page-b')

        activePage = await browser.elementByCss('.active').text()


sable jest/no-standalone-expect */
import { nextTestSetup } from 'e2e-utils'

describe('Root components import order', () => {
  const { next, isTurbopack } = nextTestSetup({
    files: __dirname,
  })

  it('root components should be imported in order _document > _app > page to respect side effects', async () => {
    const $ = await next.render$('/')

    const expectSideEffectsOrder = ['_document', '_app', 'page']
    const sideEffectCalls = $('.side-effect-calls')

    Array.from(sideEffectCalls).forEac

 be attached to the dom before page chunks',
    async () => {
      const $ = await next.render$('/')

      const requiredByRegex = /^\/_next\/static\/chunks\/(requiredBy\w*).*\.js/
      const chunks = Array.from($('head').contents())
        .filter(

h((sideEffectCall, index) => {
      expect($(sideEffectCall).text()).toEqual(expectSideEffectsOrder[index])
    })
  })

  // Test relies on webpack splitChunks overrides.
  ;(isTurbopack ? it.skip : it)(
    '_app chunks should


from 'next/link'
import { useRouter } from 'next/router'

export default function Page(props) {
  const router = useRouter()

  if (router.isFallback) return 'Loading...'

  return (
    <>

gsp page

{JSON.stringify(props)}

{router.locale}

{JSON.stringify(router.locales)}

{JSON.stringify(router.query)}

{router.pathname}

      <p id="ro

 without params
  if (!params || !params.slug) {
    throw new Error(`missing params ${JSON.stringify(params)}`)
  }

  if (locale === 'en' || locale === 'nl') {
    return {
      notFound: true,
    }
  }

  return {
    props: {
      params,
      loca

uter-as-path">{router.asPath}

      <Link href="/" id="to-index">
        to /
      </Link>

    </>
  )
}

export const getStaticProps = ({ params, locale, locales }) => {
  // ensure getStaticProps isn't called


import Link from 'next/link'

export default function Main({ message }) {
  return (

Hello {message}

          <Link href="/stream-response">Stream a response</Link>

          <Link
            href="/rewrite-me-to-about?message=refreshed"
            id="link-with-rewritten-url"
            className={message}
          >
            Rewrite me to about
          </Link>

          <Link

utes/hello-world"
            id="go-to-hello-world-anchor"
          >
            Hello World
          </Link>
        </li>
      </ul>
    </div>
  )
}

export const getServerSideProps = ({ query }) => ({
  props: { message: query.message || 'World' }

href="/rewrite-me-to-vercel">Rewrite me to Vercel</Link>

          <Link href="/redirect-me-to-about">redirect me to about</Link>

          <Link
            href="/dynamic-ro


'next/link'
import { useRouter } from 'next/router'

export default function Page(props) {
  const router = useRouter()

  return (
    <>

gssp page

{JSON.stringify(props)}

{router.locale}

{router.defaultLocale}

{JSON.stringify(router.locales)}

{JSON.stringify(router.query)}

{router.pathname}

  <Link href="/" id="to-index">
        to /
      </Link>
      <br />
    </>
  )
}

export const getServerSideProps = ({
  params,
  locale,
  locales,
  defaultLocale,
}) => {
  return {
    props: {
      params,
      locale,
      locales,
      def


t Link from 'next/link'
import { useRouter } from 'next/router'

export default function Page(props) {
  const router = useRouter()

  return (
    <>

gsp page

{JSON.stringify(props)}

{router.locale}

{router.defaultLocale}

{JSON.stringify(router.locales)}

{JSON.stringify(router.query)}

{router.pathn

}

      <Link href="/" id="to-index">
        to /
      </Link>

    </>
  )
}

export const getStaticProps = ({ locale, locales, defaultLocale }) => {
  return {
    props: {
      locale,
      locales,
      defaultLocale,
    },
  }
}


from 'next/link'
import { useRouter } from 'next/router'

export default function Page(props) {
  const router = useRouter()

  if (router.isFallback) return 'Loading...'

  return (
    <>

gsp page

{JSON.stringify(props)}

{router.locale}

{router.defaultLocale}

{JSON.stringify(router.locales)}

{JSON.stringify(router.query)}

locale, locales, defaultLocale }) => {
  // ensure getStaticProps isn't called without params
  if (!params || !params.slug) {
    throw new Error(`missing params ${JSON.stringify(params)}`)
  }

  return {
    props: {
      params,
      locale,
      lo

{router.pathname}

{router.asPath}

      <Link href="/" id="to-index">
        to /
      </Link>

    </>
  )
}

export const getStaticProps = ({ params,


#__NEXT_DATA__').html()),
    draft: $('#draft').text(),
    rand: $('#rand').text(),
    count: $('#count').text(),
  }
}

describe('Test Draft Mode', () => {
  const { next, isNextDev, isNextStart, skipped } = nextTestSetup({
    files: __dirname,
    skipDeployment: true,
  })
  if (skipped) return

  if (isNextDev) {
    it('should start development application', async () => {
      const html = await next.render('/')
      expect(html).toBeTruthy()
    })

    it('should enable draft mode via dev API',

ect(cookies[0]).toBeTruthy()
      expect(cookies[0].__prerender_bypass).toBeTruthy()
    })

    it('should start the client-side browser', async () => {
      const browser = await next.browser('/api/enable')
      await browser.close()
    })

    it('s

 async () => {
      const res = await next.fetch('/api/enable')
      expect(res.status).toBe(200)

      const cookies = res.headers
        .get('set-cookie')
        .split(',')
        .map((c) => cookie.parse(c))

      exp


estSetup, type Playwright } from 'e2e-utils'
import { check, waitFor } from 'next-test-utils'

import type { HistoryState } from 'next/dist/shared/lib/router/router'

const emitPopsStateEvent = (browser: Playwright, state: HistoryState) =>
  browser.eval(
    `window.dispatchEvent(new PopStateEvent("popstate", { state: ${JSON.stringify(
      state
    )} }))`
  )

describe('i18n: Event with stale state - static route previously was dynamic', () => {
  const { next } = nextTestSetup({
    files: {
      pag

ser = await next.browser('/sv/static')

    const state: HistoryState = {
      url: '/[dynamic]?',
      as: '/static',
      options: { locale: 'sv' },
      __N: true,
      key: '',
    }

    expect(await browser.elementByCss('#page-type').text()).toB

es: new FileRef(join(__dirname, 'app/pages')),
      'next.config.js': new FileRef(join(__dirname, 'app/next.config.js')),
    },
    dependencies: {},
  })

  test('Ignore event without query param', async () => {
    const brow


nk'
import { useRouter } from 'next/router'

export default function Page(props) {
  const router = useRouter()

  if (router.isFallback) {
    return (
      <>

Loading...

{JSON.stringify(router.query)}

      </>
    )
  }

  return (
    <>

gsp page

{JSON.stringify(props)}

{router.locale}

{router.defaultLocale}

{J

ex">
        to /
      </Link>
      <br />
    </>
  )
}

export const getStaticProps = ({ params, locale, locales, defaultLocale }) => {
  // ensure getStaticProps isn't called without params
  if (!params || !params.slug) {
    throw new Error(`missing

SON.stringify(router.locales)}

{JSON.stringify(router.query)}

{router.pathname}

{router.asPath}

      <Link href="/" id="to-ind


tTestSetup, isNextDev } from 'e2e-utils'

describe('Nullish configs in next.config.js', () => {
  const { next, skipped } = nextTestSetup({
    files: __dirname,
    skipStart: true,
    skipDeployment: true,
  })
  if (skipped) return

  afterEach(async () => {
    await next.stop().catch(() => {})
  })

  it('should ignore configs set to `undefined` in next.config.js', async () => {
    await next.patchFile(
      'next.config.js',
      `
      module.exports = {
        target: undefined,
        env: u

xpect(next.cliOutput).toMatch(/ready/i)
    } else {
      expect(next.cliOutput).toMatch(/Compiled successfully/i)
    }
  })

  it('should ignore configs set to `null` in next.config.js', async () => {
    await next.patchFile(
      'next.config.js',

ndefined,
        webpack: undefined,
        pageExtensions: undefined,
      }
    `
    )

    await next.start()

    const html = await next.render('/')
    expect(html).toContain('Hello World')

    if (isNextDev) {
      e


{
      sass: 'latest',
    },
    skipDeployment: true,
  })
  if (skipped) return

  it('should render the page', async () => {
    const $ = await next.render$('/hello')
    expect($('body').text()).toMatch(/Hello World/)
    expect($('body').text()).toMatch(/1000000000000/)
  })

  it('should render the cookies page', async () => {
    const $ = await next.render$('/ssr/cookies')
    expect($('#cookies').text()).toBe('{}')
  })

  it('should render the cookies page with cookies', async () => {
    const

, async () => {
    const $ = await next.render$('/generics')
    expect($('#value').text()).toBe('Hello World from Generic')
  })

  it('should render the angle bracket type assertions page', async () => {
    const $ = await next.render$('/angle-bracket-

 res = await next.fetch('/ssr/cookies', {
      headers: {
        Cookie: 'key=value;',
      },
    })
    const html = await res.text()
    expect(html).toContain(`{"key":"value"}`)
  })

  it('should render the generics page'


 { useRouter } from 'next/router'
import React, { type JSX } from 'react'
import { hello } from '../components/hello'
import Image from '../components/image'
import Link from '../components/link'
import Router from '../components/router'
import { World } from '../components/world'
import { value as resolveOrderValue } from '../extension-order/js-first'

export enum SearchEntity {
  SEARCH_ENTITY_NONE = 0,
  SEARCH_ENTITY_POSITION = 1,
  SEARCH_ENTITY_USER = 2,
  SEARCH_ENTITY_QUESTION = 3,
  SEARCH_ENTITY_T

on HelloPage(): JSX.Element {
  const router = useRouter()
  console.log(process.browser)
  console.log(router.pathname)
  console.log(router.isReady)
  console.log(router.isPreview)
  return (

One trillion dollars: {1_000_000_000_000}</

OPIC = 4,
}

// supports override
class Test {
  show() {
    console.log('show Test')
  }
}

class Test2 extends Test {
  override show() {
    console.log('overriding show Test')
  }
}

new Test2().show()

export default functi


from 'e2e-utils'

describe('Client-side rewrites resolving', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  it('should break rewrites chain when dynamic route matches', async () => {
    const browser = await next.browser('/')
    await browser.elementByCss('#product-link').click()
    await browser.waitForElementByCss('#product')

    expect(await browser.elementByCss('#product').text()).toBe('product: first')
  })

  it('should break rewrites chain when normal page matches', asyn

roducts')
  })

  it('should break rewrites chain when dynamic catch-all route matches', async () => {
    const browser = await next.browser('/')
    await browser.elementByCss('#category-link').click()
    await browser.waitForElementByCss('#category')

c () => {
    const browser = await next.browser('/')
    await browser.elementByCss('#products-link').click()
    await browser.waitForElementByCss('#products')

    expect(await browser.elementByCss('#products').text()).toBe('p


 { nextTestSetup } from 'e2e-utils'

describe('invalid-static-asset-404-pages-asset-prefix', () => {
  const { next } = nextTestSetup({
    files: __dirname,
    nextConfig: {
      assetPrefix: '/assets',
    },
  })

  it('should return correct output with status 200 on valid asset path', async () => {
    const buildManifestPath = `/assets/_next/static/${next.buildId}/_buildManifest.js${next.getDeploymentIdQuery()}`

    const res = await next.fetch(buildManifestPath)
    expect(res.status).toBe(200)

pect(res.status).toBe(404)
    const text = await res.text()
    expect(text).toContain('Custom Not Found')
  })

  it('should return 404 with plain text when fetching invalid asset path', async () => {
    const res = await next.fetch('/assets/_next/stati

 const text = await res.text()
    expect(text).toContain('__BUILD_MANIFEST')
  })

  it('should return custom 404 page when fetching invalid non-asset path', async () => {
    const res = await next.fetch('/invalid-path')
    ex


ort { nextTestSetup } from 'e2e-utils'

describe('invalid-static-asset-404-pages-base-path', () => {
  const { next } = nextTestSetup({
    files: __dirname,
    nextConfig: {
      basePath: '/base',
    },
  })

  it('should return correct output with status 200 on valid asset path', async () => {
    const buildManifestPath = `/base/_next/static/${next.buildId}/_buildManifest.js${next.getDeploymentIdQuery()}`

    const res = await next.fetch(buildManifestPath)
    expect(res.status).toBe(200)
    const

ct(res.status).toBe(404)
    const text = await res.text()
    expect(text).toContain('Custom Not Found')
  })

  it('should return 404 with plain text when fetching invalid asset path', async () => {
    const res = await next.fetch('/base/_next/static/in

text = await res.text()
    expect(text).toContain('__BUILD_MANIFEST')
  })

  it('should return custom 404 page when fetching invalid non-asset path', async () => {
    const res = await next.fetch('/base/invalid-path')
    expe


mport { nextTestSetup } from 'e2e-utils'

describe('invalid-static-asset-404-pages', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  it('should return correct output with status 200 on valid asset path', async () => {
    const buildManifestPath = `/_next/static/${next.buildId}/_buildManifest.js${next.getDeploymentIdQuery()}`

    const res = await next.fetch(buildManifestPath)
    expect(res.status).toBe(200)
    const text = await res.text()
    expect(text).toContain('__BUILD_MAN

t(text).toContain('Custom Not Found')
  })

  it('should return 404 with plain text when fetching invalid asset path', async () => {
    const res = await next.fetch('/_next/static/invalid-path')
    expect(res.status).toBe(404)
    const text = await res.

IFEST')
  })

  it('should return custom 404 page when fetching invalid non-asset path', async () => {
    const res = await next.fetch('/invalid-path')
    expect(res.status).toBe(404)
    const text = await res.text()
    expec


tTestSetup, isNextDev } from 'e2e-utils'

// `exportPathMap` + `useFileSystemPublicRoutes: false` is a dev-only routing
// behavior; the custom server runs `next({ dev: true })` so production mode is
// not exercised by the original integration test.
;(isNextDev ? describe : describe.skip)('FileSystemPublicRoutes', () => {
  const { next } = nextTestSetup({
    files: __dirname,
    startCommand: 'node server.js',
    serverReadyPattern: /- Local:/,
    dependencies: {
      'get-port': '5.1.1',
    },
  })

tPathMap defined routes in development', async () => {
    const res = await next.fetch('/exportpathmap-route')
    expect(res.status).toBe(200)
    const body = await res.text()
    expect(body).toMatch(/exportpathmap was here/)
  })

  it('should serve J

  it('should not route to the index page', async () => {
    const res = await next.fetch('/')
    expect(res.status).toBe(404)
    const body = await res.text()
    expect(body).toMatch(/404/)
  })

  it('should route to expor


 http = require('http')
const next = require('next')
const getPort = require('get-port')

const dev = process.env.NODE_ENV !== 'production'
const dir = __dirname

const app = next({ dev, dir })
const handleNextRequests = app.getRequestHandler()

async function main() {
  await app.prepare()
  const port = await getPort()

  const server = new http.Server((req, res) => {
    if (/setAssetPrefix/.test(req.url)) {
      app.setAssetPrefix(`http://127.0.0.1:${port}`)
    } else if (/setEmptyAssetPrefix/.test(re

  app.setAssetPrefix('')
    } else {
      app.setAssetPrefix('')
    }

    handleNextRequests(req, res)
  })

  server.listen(port, () => {
    console.log(`- Local: http://localhost:${port}`)
  })
}

main().catch((err) => {
  console.error(err)
  proce


 from 'child_process'
import { nextTestSetup, isNextDev } from 'e2e-utils'
import { shouldUseTurbopack } from 'next-test-utils'

const relayCompilerPath = join(
  __dirname,
  '../../../node_modules/relay-compiler/cli.js'
)

describe('Relay Compiler Transform - Multi Project Config', () => {
  beforeAll(() => {
    execFileSync(process.execPath, [relayCompilerPath], {
      cwd: __dirname,
      stdio: 'inherit',
    })
  })

  describe('project-a', () => {
    const { next } = nextTestSetup({
      files:

   // The relay SWC transform uses `process.cwd()` as its root, so the
      // Next.js process must run with its working directory set to the
      // sub-project. We do that here by wrapping the command in a shell
      // script defined via `packageJson


rated SignedSource<<9f92ea3ccfda1f64fa269e68b912abae>>
 * @lightSyntaxTransform
 * @nogrep
 */

/* tslint:disable */
/* eslint-disable */
// @ts-nocheck

import { ConcreteRequest, Query } from 'relay-runtime'
export type pagesBQuery$variables = {}
export type pagesBQueryVariables = pagesBQuery$variables
export type pagesBQuery$data = {
  readonly greeting: string
}
export type pagesBQueryResponse = pagesBQuery$data
export type pagesBQuery = {
  variables: pagesBQueryVariables
  response: pagesBQuery$data
}

Definitions: [],
      kind: 'Fragment',
      metadata: null,
      name: 'pagesBQuery',
      selections: v0 /*: any*/,
      type: 'Query',
      abstractKey: null,
    },
    kind: 'Request',
    operation: {
      argumentDefinitions: [],
      kind:

const node: ConcreteRequest = (function () {
  var v0 = [
    {
      alias: null,
      args: null,
      kind: 'ScalarField',
      name: 'greeting',
      storageKey: null,
    },
  ]
  return {
    fragment: {
      argument


nvironment,
  FetchFunction,
  fetchQuery,
  graphql,
  Network,
  RecordSource,
  Store,
} from 'relay-runtime'
import { GetServerSideProps } from 'next'
import { pagesBQuery } from '../__generated__/pagesBQuery.graphql'

type Props = { greeting: string }

export default function Index({ greeting }: Props) {
  return
Project B:{greeting}

}

function createGraphQLFetcher(host: string | undefined): FetchFunction {
  return async function fetchGraphQL(params, variables) {
    const url = host ? `http:/

    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,


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 pagesAQuery$data = {
  readonly greeting: string
}
export type pagesAQueryResponse = pagesAQuery$data
export type pagesAQuery = {
  variables: pagesAQueryVariables
  response: pagesAQuery$data
}

Definitions: [],
      kind: 'Fragment',
      metadata: null,
      name: 'pagesAQuery',
      selections: v0 /*: any*/,
      type: 'Query',
      abstractKey: null,
    },
    kind: 'Request',
    operation: {
      argumentDefinitions: [],
      kind:


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
Project A:{greeting}

}

function createGraphQLFetcher(host: string | undefined): FetchFunction {
  return async function fetchGraphQL(params, variables) {
    const url = host ? `http:/


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')),
      'next.config.js': new FileRef(join(__dirname, '../app/next.config.js')),
    },
  })
  function testsWithLocale(locale = '') {
    const label = locale ? `${locale} ` : ``

    it(`$

',
      ])
    })

    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


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
  const writer = writable.getWriter()
  const encoder = new TextEncoder()
  const next = NextResponse.next()

  // this is needed for tests to get the BUILD_ID
  if (url.pathname.startsWith('

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


nk'

export default function Home({ message }) {
  return (

Hello {message}

      <Link href="/stream-a-response">Stream a response</Link>

      <Link href="/stream-long">Stream a long response</Link>
      <Link href="/stream-end-stream">Test streaming after response ends</Link>

      <Link href="/stream-header-end">
        Attempt to add a header after stream ends
      </Link>

      <Link href="/redirect-stream">

d middleware effect)
      </Link>

      <Link href="/body-end-header">Respond with body, end, set a header</Link>

      <Link href="/body-end-body">
        Respond with body, end, send another body
      </Link>

Redirect to Google and attempt to stream after
      </Link>

      <Link href="/header">Respond with a header</Link>

      <Link href="/header?nested-header=true">
        Respond with 2 headers (neste


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
      next()
    ).toThrow(
      'The server has not been instantiated properly. https://nextjs.org/docs/messages/invalid-server-options'
    )
  })

  test('next() called with undefined parameter sho

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


getStaticProps() {
  return {
    props: { world: 'world', time: new Date().getTime() },
    // bad-prop
    revalidate: 2,
  }
}

const Page = ({ world, time }) => {
  return (
    <>

hello {world}

      time: {time}
      <Link href="/non-json/[p]" as="/non-json/1" id="non-json">
        to non-json
      </Link>

      <Link href="/another?hello=world" as="/another/?hello=world" id="another">
        to another
      </Link>

      <Link href="/something

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>

      <Link href="/normal" id="normal">
        to normal
      </Link>

      <Link href="/blog/[post]" as="/blog/post-1" id="post-1">
        to dyna


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,
      random: Math.random(),
      time: (await import('perf_hooks')).performance.now(),
    },
    revalidate: 2,
  }
}

export default ({ post, time, params }) => {
  if (useRouter().isFallback

<>

Post: {post}

      time: {time}

{JSON.stringify(params)}

{JSON.stringify(useRouter().query)}

      <Link href="/" id="home">
        to home
      </Link>
    </>
  )
}

) {
    return
hi fallback

  }

  return (


 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',
      '/blog/post.1', // handle duplicates
    ],
    fallback: true,
  }
}

let counter = 0

export async function getStaticProps({ params }) {
  if (params.post === 'post-10') {
    await new Promise(

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('


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'] } },
      '/catchall-explicit/second',
      { params: { slug: ['another', 'value'] } },
      '/catchall-explicit/hello/another',
      '/catchall-explicit/[first]/[second]',
      { params: { slug

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 (
    <>

Hi {slug.join(' ')}

      <p id=

: ['[third]', '[fourth]'] } },
    ],
    fallback:


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('resolve-static-props')
      break
    } catch (e) {}
    await new Promise((resolve) => setTimeout(resolve, 100))
  }

  return {
    props: {
      params,
      hello: 'world',
      post

i fallback

  }

  return (
    <>

Post: {post}

      time: {time}

{JSON.stringify(params)}

{JSON.stringify(useRouter().query)}

      <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


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: {
      params,
      hello: 'world',
      post: params.slug,
      random: Math.random(),
      time: (await import('perf_hooks')).performance.now(),
    },
    revalidate: 1,
  }
}

export default

llback) {
    return
hi fallback

  }

  return (
    <>

Post: {post}

      time: {time}

{JSON.stringify(params)}

{JSON.stringify(useRouter().query)}

      <Link href=

({ post, time, params }) => {
  if (useRouter().isFa


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: 'blocking',
  }
}

export async function getStaticProps({ params }) {
  if (params.slug === 'lots-of-data') {
    return {
      props: {
        lotsOfData: new Array(256 * 1000).fill('a').jo

)
      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'


 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 }) {
  await new Promise((resolve) => setTimeout(resolve, 1000))

  if (process.env.NEXT_PHASE !== 'phase-production-build') {
    if (params.slug === '404-on-manual-revalidate') {
      return {

idate: false,
  }
}

export default ({ post, time, params }) => {
  if (useRouter().isFallback) {
    return
hi fallback

  }

  return (
    <>

Post: {post}

      time: {time}

{JSON.stringif

    notFound: true,
      }
    }
  }

  return {
    props: {
      params,
      hello: 'world',
      post: params.slug,
      random: Math.random(),
      time: (await import('perf_hooks')).performance.now(),
    },
    reval


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 (skipped) {
    return
  }

  // TODO: Failure is not specific to Turbopack, edge runtime errors don't have source maps applied.
  ;(process.env.IS_TURBOPACK_TEST && isNextStart ? it.skip : it)

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


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': `
        export const config = { api: { bodyParser: { sizeLimit: '5mb' } } }
        export default (req, res) => res.json({ body: req.body })
      `,
      'pages/api/body_parser_false.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'


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 non-Turbopack tests', () => {})
    return
  }

  const { next, skipped } = nextTestSetup({
    files: __dirname,
    skipStart: true,
    skipDeployment: true,
  })

  if (skipped) {
    // Te

!: (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


;(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
          .split('\n')
          .filter((line) => line && !line.trim().startsWith('⚠'))
          .filter((line) => /\bError\b/.test(line))
        expect(errors).toEqual([])
        expect(next.cliOutp

  ;(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/)
      })
    }


 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 non-start mode', () => {})
        return
      }

      let ssrBundles = ''
      let staticBundles = ''

      beforeAll(async () => {
        const distDir = path.join(next.testDir, next.dist

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


 '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', {}],
      ['/', { hello: 'world' }],
      ['/en', { hello: 'world' }],
      ['/fr', { hello: 'world' }],
    ] as const) {
      const asPath = url.format({ pathname, query })
      const bro

      })

      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,


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 always be considered stale
      it('should support revalidateReason: "stale"', async () => {
        const res = await next.fetch('/')

        expect(res.status).toBe(200)

        expect(nex

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


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, next.url).href

      // There's a bug in node-fetch v2 where aborting the fetch will never abort
      // the connection, because the body is a transformed stream that doesn't
      // close th

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


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: NextRequest): Promise<Response> {
  if (req.nextUrl.searchParams.has('compile')) {
    // The request just wants to trigger compilation.
    return new Response(null, { status: 204 })
  }

  // Con

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


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<void> {
  const url = new URL(req.url!, 'http://localhost/')

  if (url.searchParams.has('compile')) {
    // The request just wants to trigger compilation.
    res.statusCode = 204
    res.end

 (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 =


-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 } = nextTestSetup({
      files: __dirname,
      skipDeployment: true,
    })

    it('should respond to 404 correctly', async () => {
      const res = await next.fetch('/404')
      expect(res.

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


('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.uncaughtErrors')).toEqual([])
  })

  it('should load getStaticProps page correctly', async () => {
    const browser = await next.browser('/gsp')
    expect(await browser.elementByCss('#gsp').text()).toBe

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


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 browser.eval('window.location.pathname')).toBe('/fr/about')
    })
    await retry(async () => {
      expect(await browser.eval('window.location.hash')).toBe('#hash')
    })

    expect(await b

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


rt Link from 'next/link'
import { useRouter } from 'next/router'

export default function Page(props) {
  const router = useRouter()

  return (
    <>

{props.locale}

{router.locale}

      <Link
        href={{ pathname: router.pathname, query: router.query, hash: '#hash' }}
        locale={router.locale === 'fr' ? 'en' : 'fr'}
        id="change-locale"
      >
        Change Locale
      </Link>
    </>
  )
}

export const getStaticProps = asy

ocale,
    },
  }
}

export const getStaticPaths = () => {
  return {
    paths: [
      {
        params: { slug: ['a'] },
        locale: 'en',
      },
      {
        params: { slug: ['a'] },
        locale: 'fr',
      },
    ],
    fallback: false,

nc ({ locale }) => {
  return {
    props: {
      l


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',
      },
    })

    it('should pass on both client and worker', async () => {
      const browser = await next.browser('/')
      await browser.waitForElementByCss('#web-status')
      await retry(async

#web-status').text()).toMatch(
          /PASS/i
        )
      })
      await browser.waitForElementByCss('#worker-status')
      await retry(async () => {
        expect(await browser.elementByCss('#worker-status').text()).toMatch(
          /PASS/i


 '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: isNextDev
        ? 'Page "/another/[slug]/page" is missing exported function "generateStaticParams()", which is required with "output: export" config.'
        : 'Page "/another/[slug]" is miss

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_


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.env.IS_TURBOPACK_TEST
    ? [
        expect.stringMatching(
          /_next\/static\/(immutable\/)?media\/favicon\.[0-9a-z_-]+\.ico/
        ),
      ]
    : []),
  expect.stringMatching(

/_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(


'next/link'
import { useRouter } from 'next/router'

export default function Page(props) {
  const router = useRouter()

  return (
    <>

gssp page

{JSON.stringify(props)}

{router.locale}

{router.defaultLocale}

{JSON.stringify(router.locales)}

{JSON.stringify(router.query)}

{router.pathname}

  <Link href="/" id="to-index">
        to /
      </Link>
      <br />
    </>
  )
}

export const getServerSideProps = ({
  locale,
  locales,
  defaultLocale,
  query,
}) => {
  return {
    props: {
      query,
      locale,
      locales,
      defau


Link from 'next/link'
import { useRouter } from 'next/router'

export default function Page(props) {
  const router = useRouter()

  return (
    <>

gsp page

{JSON.stringify(props)}

{router.locale}

{JSON.stringify(router.locales)}

{JSON.stringify(router.query)}

{router.pathname}

{router.asPath}

.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


from 'next/link'
import { useRouter } from 'next/router'

export default function Page(props) {
  const router = useRouter()

  return (
    <>

dynamic page

{router.locale}

{router.defaultLocale}

{JSON.stringify(router.locales)}

{JSON.stringify(router.query)}

{router.pathname}

{router.a

fallback-first">
        to /gsp/fallback/first
      </Link>

      <Link href="/gsp/fallback/hello" id="to-fallback-hello">
        to /gsp/fallback/hello
      </Link>

      <Link href="/gsp/no-fallback/first" id="to-no-fallback

sPath}

      <Link href="/another" id="to-another">
        to /another
      </Link>

      <Link href="/gsp" id="to-gsp">
        to /gsp
      </Link>

      <Link href="/gsp/fallback/first" id="to-


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_ID/p1/p2/nested-all-ssg/hello1/hello2.json?rest=hello1&rest=hello2',
            '/_next/data/BUILD_ID/post-1.json?fromHome=true&name=post-1',
            '/_next/data/BUILD_ID/post-1.json?hidd

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


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 turned into %3Fmy-post%3F
    { params: { slug: '?my-post?' } },
    // ampersand signs
    { params: { slug: '&my-post&' } },
    // non-ascii characters
    { params: { slug: '商業日語' } },

slug: ' my-post ' } },
    { params: { slug: encodeURIComponent('商業日語') } },
    `${pathPrefix}/%2Fsecond-post%2F`,
    `${pathPrefix}/%2Bsecond-post%2B`,
    `${pathPrefix}/%26second-post%26`,
    `${pathPrefix}/mixed-${encodeURIComponent('商業日語')}`,
  ]
}


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')) {
    // The request just wants to trigger compilation.
    return new Response(null, { status: 204 })
  }

  // Consume the entire request body.
  // This is so we don't confuse the request close with t

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.


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 request just wants to trigger compilation.
    return new Response(null, { status: 204 })
  }

  // Consume the entire request body.
  // This is so we don't confuse the request close with the

(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


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.browser('/')
    await browser.waitForElementByCss('#success')
    await retry(async () => {
      expect(await browser.elementByCss('#success').text()).toMatch(/yay/)
    })
  })

  it('should rend

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


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.useEffect(() => {
    worker.current = new Worker(new URL('../lib/worker.js', import.meta.url))
    worker.current.addEventListener('message', ({ data }) => {
      if (data) {
        setExpensive

xpensive()
      setExpensiveWebStatus('PASS')
    } catch {
      setExpensiveWebStatus('FAIL')
    }
  }, [])

  return (

$RefreshRegistry repro

Web: {expensiveWebStatus}

      <div id="worker-st

WorkerComplete('PASS')
      }
    })
    worker.current.addEventListener('error', (data) => {
      setExpensiveWorkerComplete('FAIL')
    })
  }, [worker, setExpensiveWorkerComplete])
  React.useEffect(() => {
    try {
      E


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 during next start with output export', async () => {
      const { exitCode } = await next.build()
      expect(exitCode).toBe(0)

      try {
        await next.start({ skipBuild: true })

 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.`
        )
      })
    })


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.Database,
  })

  const users = await db.all(`SELECT * FROM users`)

  return {
    props: {
      users,
      blog: true,
      params: params || null,
    },
  }
}

export const getStaticPaths

fallback: true,
  }
}

export default function Page(props) {
  const router = useRouter()

  if (router.isFallback) {
    return 'Loading...'
  }

  return (
    <>

blog page

{JSON.stringify(props)}

    </>

= () => {
  return {
    paths: ['/blog/first'],


(...args) {
    window.caughtWarns.push(args)
    origWarn(...args)
  }
}

const Page = () => {
  return (

My blog

      <Link href="/[name]" as="/post-1" id="view-post-1">
        View post 1
      </Link>

      <Link href="/[name]" as="/post-1#my-hash" id="view-post-1-hash-1">
        View post 1 (hash)
      </Link>

      <Link href="/post-1#my-hash" id="view-post-1-hash-1-href-only">
        View post 1 (hash only href)
      </Link>

      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',