te to count each image load callback
  const [idToCount, setIdToCount] = useState({})
  const [clicked, setClicked] = useState(false)

  return (

On Loading Complete Test

      <ImageWithMessage
        id="1"
        src="/test.jpg"
        width="128"
        height="128"
        idToCount={idToCount}
        setIdToCount={setIdToCount}
      />

      <ImageWithMessage
        id="2"
        src={require('../public/test.png')}
        placeholder="blur"
        idToCount={idToCou

>

      <ImageWithMessage
        id="4"
        src="/test.ico"
        width={200}
        height={200}
        idToCount={idToCount}
        setIdToCount={setIdToCount}
      />

      <ImageWithMessage
        id="5"
        src="data:image/png;base64

nt}
        setIdToCount={setIdToCount}
      />

      <ImageWithMessage
        id="3"
        src="/test.svg"
        width="1200"
        height="1200"
        idToCount={idToCount}
        setIdToCount={setIdToCount}
      /


import Image from 'next/image'

const Page = () => {
  return (

Preload Page

      <Image
        preload
        id="basic-image"
        alt="basic-image"
        src="/test.jpg"
        width="400"
        height="400"
      ></Image>
      <Image
        preload
        id="basic-image-crossorigin"
        alt="basic-image-crossorigin"
        src="/test.webp"
        width="400"
        height="400"
        crossOrigin="use-credentials"
      ></Image>
      <Image
        prelo

g="eager"
        id="load-eager"
        alt="load-eager"
        src="/test.png"
        width="200"
        height="200"
      ></Image>
      <Image
        preload
        id="responsive1"
        alt="responsive1"
        src="/wide.png"
        widt

ad
        id="basic-image-referrerpolicy"
        alt="basic-image-referrerpolicy"
        src="/test.png"
        width="400"
        height="400"
        referrerPolicy="no-referrer"
      ></Image>
      <Image
        loadin


import Image from 'next/image'

const Page = () => {
  return (

Priority Page

      <Image
        priority
        id="basic-image"
        alt="basic-image"
        src="/test.jpg"
        width="400"
        height="400"
      ></Image>
      <Image
        priority
        id="basic-image-crossorigin"
        alt="basic-image-crossorigin"
        src="/test.webp"
        width="400"
        height="400"
        crossOrigin="use-credentials"
      ></Image>
      <Image
        pr

ading="eager"
        id="load-eager"
        alt="load-eager"
        src="/test.png"
        width="200"
        height="200"
      ></Image>
      <Image
        priority
        id="responsive1"
        alt="responsive1"
        src="/wide.png"

iority
        id="basic-image-referrerpolicy"
        alt="basic-image-referrerpolicy"
        src="/test.png"
        width="400"
        height="400"
        referrerPolicy="no-referrer"
      ></Image>
      <Image
        lo


mport testPNG from '../public/test.png'
import testWEBP from '../public/test.webp'
import testAVIF from '../public/test.avif'
import testSVG from '../public/test.svg'
import testGIF from '../public/test.gif'
import testBMP from '../public/test.bmp'
import testICO from '../public/test.ico'
import widePNG from '../public/wide.png'
import tallPNG from '../components/tall.png'
import superWidePNG from '../public/super-wide.png'

import TallImage from '../components/TallImage'

const blurDataURL =
  'data:image/


ort React from 'react'
import Image from 'next/image'

const Page = () => {
  return (

Wrapper Div

        <Image
          id="img1"
          src="/wide.png"
          width="1200"
          height="700"
          loading="eager"
        />

        <Image
          id="img2"
          src="/wide.png"
          width="1200"
          height="700"
          style={{
            paddingLeft: '4rem',

h="400"
          height="400"
          loading="eager"
        />
      </div>
      <div id="image-container4">
        <Image
          id="img4"
          src="/test.png"
          width="400"
          height="400"
          loading="eager"

      width: '100%',
            objectPosition: '30% 30%',
          }}
          sizes="50vh"
        />
      </div>
      <div id="image-container3">
        <Image
          id="img3"
          src="/test.png"
          widt


 nextTestSetup } from 'e2e-utils'

describe('Image Component from node_modules', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  it('should apply image config for node_modules', async () => {
    const browser = await next.browser('/')
    const src = await browser
      .elementById('image-from-node-modules')
      .getAttribute('src')
    expect(src).toMatch('i.imgur.com')

    const srcset = await browser
      .elementById('image-from-node-modules')
      .getAttribute('srcset')

ld warn when using images.domains config', async () => {
    expect(next.cliOutput).toContain(
      '`images.domains` is deprecated in favor of `images.remotePatterns`. Please update next.config.js to protect your application from malicious users.'
    )

    expect(srcset).toMatch('1234')
  })

  it('shou


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

describe('TypeScript Image Component Build Errors', () => {
  if (isNextDev) {
    it('no-op in dev', () => {})
    return
  }

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

  it('should fail to build invalid usage of the Image component', async () => {
    const { exitCode } = await next.build()
    expect(next.cliOutput).toMatch(/Failed to type check/)
    expect(next.cliOutput).toMatch(/is not assig

{
    await next.patchFile(
      'next.config.js',
      (content) =>
        content.replace('// disableStaticImages', 'disableStaticImages'),
      async () => {
        const { exitCode } = await next.build()
        expect(next.cliOutput).toMatch(/Fai

nable to type/)
    expect(exitCode).toBe(1)
    const envTypes = await next.readFile('next-env.d.ts')
    expect(envTypes).toContain('image-types/global')
  })

  it('should remove global image types when disabled', async () =>


import Image from 'next/image'

const Invalid = () => {
  return (

Invalid TS

      <Image
        id="invalid-src"
        alt="invalid-src"
        src={new Date()}
        width={500}
        height={500}
      />
      <Image
        id="invalid-width"
        alt="invalid-width"
        src="https://image-optimization-test.vercel.app/test.jpg"
        width={new Date()}
        height={500}
      />
      <Image
        id="invalid-placeholder"
        alt="invalid-placeholder

ring-type"
        src="https://image-optimization-test.vercel.app/test.jpg"
        width="500foo"
      />
      <Image
        id="invalid-height-string-type"
        alt="invalid-height-string-type"
        src="https://image-optimization-test.vercel.a

"
        src="https://image-optimization-test.vercel.app/test.jpg"
        width="500"
        height="500"
        placeholder="invalid"
      />
      <Image
        id="invalid-width-string-type"
        alt="invalid-width-st


ort svg from '../public/test.svg'
import avif from '../public/test.avif'
import { ImageCard } from '../components/image-card'
import { DynamicSrcImage } from '../components/image-dynamic-src'
import { ImageWithLoader } from '../components/image-with-loader'

const Page = () => {
  return (

Valid TS

      <Image
        id="width-and-height-num"
        alt="width-and-height-num"
        src="https://image-optimization-test.vercel.app/test.jpg"
        width={500}
        height={500}

d="fill-no-width-and-height"
        src="https://image-optimization-test.vercel.app/test.jpg"
        fill
        alt=""
      />
      <Image
        id="quality-num"
        src="https://image-optimization-test.vercel.app/test.jpg"
        quality={80}

      />
      <Image
        id="width-and-height-str"
        alt="width-and-height-str"
        src="https://image-optimization-test.vercel.app/test.jpg"
        width="500"
        height="500"
      />
      <Image
        i


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

describe('Image localPatterns config', () => {
  const { next } = nextTestSetup({
    files: __dirname,
    skipDeployment: true,
  })

  async function getSrc(browser: Playwright, id: string) {
    const src = await browser.elementById(id).getAttribute('src')
    if (src) {
      const url = new URL(src, next.url)
      return url.href.slice(url.origin.length)
    }
  }

  it('should load matching images', async () => {
    const browser = await nex

romise.all(urls.map((url) => next.fetch(url)))
    const statuses = responses.map((res) => res.status)
    expect(statuses).toStrictEqual([200, 200])
  })

  it.each([
    'does-not-exist',
    'nested-assets-query',
    'nested-blocked',
    'top-level',

t.browser('/')
    if (isNextDev) {
      await waitForNoRedbox(browser)
    }
    const ids = ['nested-assets', 'static-img']
    const urls = await Promise.all(ids.map((id) => getSrc(browser, id)))
    const responses = await P


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

  it('should load static unicode image', async () => {
    const browser = await next.browser('/')
    const src = await browser.elementById('static').getAttribute('src')
    expect(src).toMatch(
      /_next%2Fstatic%2F(immutable%2F)?media%2F%C3%A4%C3%B6%C3%BC%C5%A1%C4%8D%C5%99%C3%AD(.+)png/
    )
    const fullSrc = new URL(src, next.url)
    const res = await next.fetch(fullSrc.pathname + fullSrc.search)
    ex

ch(
      '/_next/image?url=%2F%C3%A4%C3%B6%C3%BC%C5%A1%C4%8D%C5%99%C3%AD.png'
    )
    const fullSrc = new URL(src, next.url)
    const res = await next.fetch(fullSrc.pathname + fullSrc.search)
    expect(res.status).toBe(200)
  })

  it('should load ext

pect(res.status).toBe(200)
  })

  it('should load internal unicode image', async () => {
    const browser = await next.browser('/')
    const src = await browser.elementById('internal').getAttribute('src')
    expect(src).toMat


mport { check, retry } from 'next-test-utils'

const pathnames = {
  '/404': ['/not/a/real/page?with=query', '/not/a/real/page'],
  // Special handling is done for the error cases because these need to be
  // prefixed with the basePath if it's enabled for that test suite. These also
  // should only run when the application is tested in production.
  '/_error': ['/error?with=query', '/error'],
}

const basePath = '/docs'

const table = [
  { basePath: false, i18n: true, middleware: false },
  { basePath: t

s failure in development
        { basePath: false, i18n: false, middleware: true },
      ]),
]

const baseNextConfig = `
module.exports = {
  BASE_PATH
  I18N
}
`

describe('404-page-router', () => {
  const { next } = nextTestSetup({
    files: {

rue, i18n: false, middleware: false },
  { basePath: true, i18n: true, middleware: false },
  { basePath: false, i18n: false, middleware: false },

  ...((global as any).isNextDev
    ? []
    : [
        // TODO: investigate thi


r } from 'next/router'
import { useEffect, useState } from 'react'
import Debug from './debug'

function transform(router) {
  return {
    pathname: router.pathname,
    asPath: router.asPath,
    query: Object.entries(router.query)
      .map(([key, value]) => [key, value].join('='))
      .join('&'),
    isReady: router.isReady ? 'true' : 'false',
  }
}

export default function DebugError({ children }) {
  const router = useRouter()
  const [debug, setDebug] = useState({})

  useEffect(() => {
    setDeb

 <>
      <dl>
        <Debug name="pathname" value={debug.pathname} />
        <Debug name="asPath" value={debug.asPath} />
        <Debug name="query" value={debug.query} />
        <Debug name="isReady" value={debug.isReady} />
      </dl>
      {childr

ug(transform(router))
  }, [router])

  return (


import { retry } from 'next-test-utils'
import { join } from 'path'

describe('link-with-api-rewrite', () => {
  const { next } = nextTestSetup({
    files: {
      pages: new FileRef(join(__dirname, 'app/pages')),
      'next.config.js': new FileRef(join(__dirname, 'app/next.config.js')),
    },
    dependencies: {},
  })

  it('should perform hard navigation for rewritten urls', async () => {
    const browser = await next.browser('/')

    try {
      // Click the link on the page, we expect that there w

sync () => {
        expect(await browser.eval('window.beforeNav')).not.toEqual('hi')
      })

      // Check to see that we were in fact navigated to the correct page.
      const pathname = await browser.eval('window.location.pathname')
      expect(pat

ill be a hard
      // navigation later (we do this be checking that the window global is
      // unset).
      await browser.eval('window.beforeNav = "hi"')
      await browser.elementById('rewrite').click()
      await retry(a


ss.env.__NEXT_CACHE_COMPONENTS === 'true' ? describe.skip : describe)(
  'Build Error Tests',
  () => {
    const { next, isTurbopack } = nextTestSetup({
      files: __dirname,
      skipStart: true,
      skipDeployment: true,
    })

    if (isNextDev) {
      it('no-op in dev', () => {})
      return
    }

    it('should throw build error when import statement is used with missing file', async () => {
      await next.patchFile(
        'app/static-img/page.js',
        (content) =>
          content.r

(
            "Module not found: Can't resolve '../../public/foo/test-rect-broken.jpg"
          )
          if (isTurbopack) {
            expect(cliOutput).toContain('app/static-img/page.js')
          } else {
            expect(cliOutput).toContain('./

eplace(
            '../../public/foo/test-rect.jpg',
            '../../public/foo/test-rect-broken.jpg'
          ),
        async () => {
          const { cliOutput } = await next.build()
          expect(cliOutput).toContain


e client'
import { useState } from 'react'
import Image from 'next/image'

const Page = () => {
  const [clicked, setClicked] = useState(false)

  return (

Test onError

        If error occurred while loading image, native onError should be called.

      <button id="toggle" onClick={() => setClicked(!clicked)}>
        Toggle
      </button>

      <ImageWithMessage id="1" src="/test.png" width={200} height={200} />
      <ImageWithMessage
        id="2"

rred for img${id}`)

  return (
    <>
      <div className="wrap">
        <Image
          id={`img${id}`}
          onError={(e) => {
            setMsg(`error occurred while loading ${e.target.id}`)
          }}
          {...props}
        />
      </

 src={clicked ? '/404.jpg' : '/test.jpg'}
        width="200"
        height="200"
      />
      <div id="footer" />
    </div>
  )
}

function ImageWithMessage({ id, ...props }) {
  const [msg, setMsg] = useState(`no error occu


ffect, useState } from 'react'

export default function Home() {
  const [displayImage, setDisplayImage] = useState(true)

  const refWithCleanup = useCallback((el) => {
    if (!el) {
      throw new Error(
        'callback refs that returned a cleanup should never be called with null'
      )
    }

    return () => {
      console.log('callback ref was cleaned up')
    }
  }, [])

  useEffect(() => {
    setDisplayImage(false)
  }, [])

  return (
    <main>
      <h1>Should call ref cleanup on unmount<

     <div style={{ position: 'relative', width: 10, height: 10 }}>
            <Image
              ref={refWithCleanup}
              priority
              fill
              src="/test.jpg"
              alt="alt"
              sizes="10px"

/h1>
      <section>
        {displayImage ? (


port React from 'react'
import Image from 'next/image'

export default function Page() {
  return (

Blurry Placeholder

      <Image
        priority
        id="blurry-placeholder-raw"
        src="/test.ico"
        width="400"
        height="400"
        placeholder="blur"
        blurDataURL="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8P4nhDwAGuAKPn6cicwAAAABJRU5ErkJggg=="
      />

       src="/test.bmp"
        width="400"
        height="400"
        placeholder="blur"
        blurDataURL="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mO0/8/wBwAE/wI85bEJ6gAAAABJRU5ErkJggg=="
      />
    </div>
  )

  <Image
        id="blurry-placeholder-with-lazy"


 = require('path')

// A simple webpack loader that logs when an entry is being processed
module.exports = function entryLoggerLoader(source) {
  const callback = this.async()
  const resourcePath = this.resourcePath
  const logFile = path.join(__dirname, '.entry-log')

  console.log('loader', resourcePath)

  // Extract the page name from the resource path
  let pageName = resourcePath
  if (resourcePath.includes('/app/')) {
    pageName = resourcePath.split('/app/')[1] || resourcePath
  } else if (resourc

Path.split('/pages/')[1] || resourcePath
  }

  // Log the entry processing with timestamp
  const logEntry = `${Date.now()}:${pageName}\n`

  fs.appendFile(logFile, logEntry, (err) => {
    if (err) {
      console.error('Failed to write entry log:', err)

ePath.includes('/pages/')) {
    pageName = resource


ls'
import { retry } from 'next-test-utils'

describe('href resolving trailing-slash', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  it('should route to /blog/another/ correctly', async () => {
    const browser = await next.browser('/')
    await browser.elementByCss('#to-blog-another').click()

    await browser.waitForElementByCss('#another')
    expect(await browser.elementByCss('#another').text()).toBe('blog another')
  })

  it('should route to /blog/first-post/ correctly',

'blog slug first-post'
    )
  })

  it('should route to /catch-all/hello/world/ correctly', async () => {
    const browser = await next.browser('/')
    await browser.elementByCss('#to-catch-all-item').click()

    await browser.waitForElementByCss('#slu

async () => {
    const browser = await next.browser('/')
    await browser.elementByCss('#to-blog-post').click()

    await browser.waitForElementByCss('#slug')
    expect(await browser.elementByCss('#slug').text()).toBe(


, Request as PlaywrightRequest } from 'playwright'
import { retry } from 'next-test-utils'

const _describe =
  // prefetching is disabled in dev.
  isNextDev ? describe.skip : describe

_describe('app dir - form prefetching', () => {
  const { next } = nextTestSetup({
    files: __dirname,
    nextConfig: {
      typescript: {
        ignoreBuildErrors: true,
      },
    },
  })

  it("should prefetch a loading state for the form's target", async () => {
    const interceptor = new RequestInterceptor({

1'
        const isPrefetch = !!headers[NEXT_ROUTER_PREFETCH_HEADER]
        return isRSC && !isPrefetch
      },
      log: true,
    })

    const session = await next.browser('/forms/basic', {
      beforePageLoad: interceptor.beforePageLoad,
    })

    pattern: '**/search*',
      requestFilter: async (request) => {
        // only capture RSC requests that *aren't* prefetches
        const headers = await request.allHeaders()
        const isRSC = headers[RSC_HEADER] === '


 'react'
import { type ComponentProps, useActionState, useState } from 'react'
import Form from 'next/form'
import { useRouter } from 'next/navigation'

export default function Page() {
  const destination = '/redirected-from-action'
  const [query, setQuery] = useState('')
  return (
    <Form action="/search" id="search-form">
      <input
        name="query"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />

      <NavigateButton to={destination + '?' + new URLSearchParam

</NavigateButton>
    </Form>
  )
}

function NavigateButton({
  to,
  ...props
}: { to: string } & ComponentProps<'button'>) {
  const router = useRouter()
  const [, dispatch] = useActionState(() => router.push(to), undefined)
  return <button type="subm

s({ query })}>
        Submit (client action)


use client'
import * as React from 'react'
import Form from 'next/form'
import { useRouter } from 'next/router'

const isReact18 = typeof React.useActionState !== 'function'

export default isReact18 ? DummyPage : Page

function DummyPage() {
  return <>This test cannot run in React 18</>
}

function Page() {
  const destination = '/pages-dir/redirected-from-action'
  const [query, setQuery] = React.useState('')
  return (
    <Form action="/pages-dir/search" id="search-form">
      <input
        name="que

rm>
  )
}

function NavigateButton({
  to,
  ...props
}: { to: string } & React.ComponentProps<'button'>) {
  const router = useRouter()
  const [, dispatch] = React.useActionState(() => {
    router.push(to)
  }, undefined)
  return <button type="submit"

ry"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />

      <NavigateButton to={destination + '?' + new URLSearchParams({ query })}>
        Submit (client action)
      </NavigateButton>
    </Fo


lient'
import * as React from 'react'
import Form from 'next/form'
import { useRouter } from 'next/router'

export default function Home() {
  const searchParams = useRouter().query
  const attribute = searchParams.attribute as string | undefined
  return (
    <div
      onSubmit={(e) => {
        // should fire if the form let the event bubble up
        if (e.defaultPrevented) {
          console.log('incorrect: default submit behavior was prevented')
        } else {
          console.log('correct: defa

-form">
        <input name="query" />
        <button
          type="submit"
          formAction="/pages-dir/search"
          formEncType={
            attribute === 'formEncType' ? 'multipart/form-data' : undefined
          }
          formMethod={at

ult submit behavior was not prevented')
          e.preventDefault() // this submission will do something stupid, we don't want it to actually go through.
        }
      }}
    >
      <Form action="/pages-dir/search" id="search


tTestSetup } from 'e2e-utils'

describe('app dir - form - with basepath', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  it('should add basePath to `action`', async () => {
    const session = await next.browser('/base/forms/basic')

    const start = Date.now()
    await session.eval(`window.__MPA_NAV_ID = ${start}`)

    const searchInput = await session.elementByCss('input[name="query"]')
    await searchInput.fill('my search')

    const submitButton = await session.elementByCs

_ID`)).toEqual(start)
  })

  it("should not add basePath to a submitter's formAction", async () => {
    const session = await next.browser('/base/forms/button-formaction')

    const start = Date.now()
    await session.eval(`window.__MPA_NAV_ID = ${star

s('[type="submit"]')
    await submitButton.click()

    const result = await session.waitForElementByCss('#search-results').text()
    expect(result).toMatch(/query: "my search"/)

    expect(await session.eval(`window.__MPA_NAV


 * as React from 'react'
import * as react from 'library-with-exports/react'
import * as serverFavoringBrowser from 'library-with-exports/server-favoring-browser'
import * as serverFavoringEdge from 'library-with-exports/server-favoring-edge'

export const config = {
  runtime: 'nodejs',
}

let server = {
  react: react.condition,
  serverFavoringBrowser: serverFavoringBrowser.condition,
  serverFavoringEdge: serverFavoringEdge.condition,
}
if (typeof window !== 'undefined') {
  server = JSON.parse(
    doc

react.condition,
      serverFavoringBrowser: serverFavoringBrowser.condition,
      serverFavoringEdge: serverFavoringEdge.condition,
    })
  }, [])

  return (
    <output aria-busy={client === null}>
      {client === null ? (
        <pre data-testid=

ument.querySelector('[data-testid="server"]')!.textContent!
  )
}

export default function Page() {
  const [client, setClient] = React.useState<unknown | null>(null)

  React.useLayoutEffect(() => {
    setClient({
      react:


tTestSetup, isNextStart } from 'e2e-utils'
;(process.env.TURBOPACK_DEV && isNextStart ? describe.skip : describe)(
  'API routes',
  () => {
    const { next, skipped } = nextTestSetup({
      files: __dirname,
      // Assertions don't apply to deploy mode (output differs vs. local Next.js server).
      skipDeployment: true,
    })
    if (skipped) return

    it('should return data when catch-all', async () => {
      const data = await next
        .fetch('/api/users/1', {})
        .then((res) => res.o

t: 'manual',
      })
      expect(res.status).toBe(308)
      const text = await res.text()
      expect(text).toEqual('/api/users')
    })

    it('should return data when catch-all with index and trailing slash', async () => {
      const data = await n

k && res.json())

      expect(data).toEqual({ slug: ['1'] })
    })

    it('should return redirect when catch-all with index and trailing slash', async () => {
      const res = await next.fetch('/api/users/', {
        redirec


.toEqual({
      fetchpriority: '',
      imagesizes: '',
      imagesrcset: `/_next/image?url=%2Ftest.webp&w=640&q=75${dpl} 1x, /_next/image?url=%2Ftest.webp&w=828&q=75${dpl} 2x`,
      crossorigin: 'use-credentials',
      referrerpolicy: '',
    })

    expect(
      entries.find(
        (item) =>
          item.imagesrcset ===
          `/_next/image?url=%2Fwide.png&w=640&q=75${dpl} 640w, /_next/image?url=%2Fwide.png&w=750&q=75${dpl} 750w, /_next/image?url=%2Fwide.png&w=828&q=75${dpl} 828w, /_next/imag

.png&w=3840&q=75${dpl} 3840w`
      )
    ).toEqual({
      fetchpriority: '',
      imagesizes: '100vw',
      imagesrcset: `/_next/image?url=%2Fwide.png&w=640&q=75${dpl} 640w, /_next/image?url=%2Fwide.png&w=750&q=75${dpl} 750w, /_next/image?url=%2Fwide.p

e?url=%2Fwide.png&w=1080&q=75${dpl} 1080w, /_next/image?url=%2Fwide.png&w=1200&q=75${dpl} 1200w, /_next/image?url=%2Fwide.png&w=1920&q=75${dpl} 1920w, /_next/image?url=%2Fwide.png&w=2048&q=75${dpl} 2048w, /_next/image?url=%2Fwide


mage'

// We don't use a static import intentionally
const shimmer = `data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjIwMCIgaGVpZ2h0PSIyMDAiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgPGRlZnM+CiAgICA8bGluZWFyR3JhZGllbnQgaWQ9ImciPgogICAgICA8c3RvcCBzdG9wLWNvbG9yPSIjMzMzIiBvZmZzZXQ9IjIwJSIgLz4KICAgICAgPHN0b3Agc3RvcC1jb2xvcj0iIzIyMiIgb2Zmc2V0PSI1MCUiIC8+CiAgICAgIDxzdG9wIHN0b3AtY29sb3I9IiMzMzMiIG9mZnNldD0iNzAlIiAvPgogICAgPC9saW5lYXJH

m9tPSItMjAwIiB0bz0iMjAwIiBkdXI9IjFzIiByZXBlYXRDb3VudD0iaW5kZWZpbml0ZSIgIC8+Cjwvc3ZnPg==`

export default function Page() {
  return (
    <>

Image with fill with Data URL placeholder

      <div style={{ position: 'relative', display: 'flex', m


t/link'

export default function Page() {
  return (

      This is a static page.

      <Runtime />

      <Time />

      <Link href="/node-rsc" id="link-node-rsc">
        to /node-rsc
      </Link>

      <Link href="/node-rsc-ssg" id="link-node-rsc-ssg">
        to /node-rsc-ssg
      </Link>

      <Link href="/node-rsc-ssr" id="link-node-rsc-ssr">
        to /node-rsc-ssr
      </Link>

      <Link href="/node-rsc-isr"

</Link>

      <Link href="/node-ssg" id="link-node-ssg">
        to /node-ssg
      </Link>

      <Link href="/node-ssr" id="link-node-ssr">
        to /node-ssr
      </Link>

  )
}

export const config = {
  runtime

id="link-node-rsc-isr">
        to /node-rsc-isr


g')
const callbackLogFile = path.join(__dirname, '.callback-log')
const deferredPageFile = path.join(__dirname, 'app', 'deferred', 'page.tsx')
const routeHandlerFile = path.join(
  __dirname,
  'app',
  'route-handler',
  'route.ts'
)
const homePageFile = path.join(__dirname, 'app', 'page.tsx')

let lastHomePageContent = null

/** @type {import('next').NextConfig} */
module.exports = {
  experimental: {
    deferredEntries: ['/deferred', '/route-handler'],
    onBeforeDeferredEntries: async () => {
      co

Mutate the deferred entry source directly so the deferred build picks
      // up callback-time content.
      if (shouldWriteDeferredTimestamp) {
        const deferredPageContent = fs.readFileSync(deferredPageFile, 'utf-8')
        const nextDeferredPage

nst timestamp = Date.now()
      const homePageContent = fs.readFileSync(homePageFile, 'utf-8')
      const shouldWriteDeferredTimestamp =
        lastHomePageContent === null || lastHomePageContent !== homePageContent

      //


nction Index() {
  return (
    <>
      <Link href="/blog/another/" id="to-blog-another">
        to /blog/another/
      </Link>

      <Link href="/blog/first-post/" id="to-blog-post">
        to /blog/first-post/
      </Link>

      <Link href="/catch-all/hello/world/" id="to-catch-all-item">
        to /catch-all/hello/world/
      </Link>

      <Link href="/catch-all/first/" id="to-catch-all-first">
        to /catch-all/first/
      </Link>

      <Li

ther/
      </Link>

      <Link href="/top-level-slug/" id="to-slug">
        to /top-level-slug/
      </Link>

      <Link as="/world" href="/[slug]" id="to-slug-manual">
        to /world/
      </Link>

    </>
  )

nk href="/another/" id="to-another">
        to /ano


import React, { Suspense } from 'react'
import Form from 'next/form'

type AnySearchParams = Promise<{
  [key: string]: string | Array<string> | undefined
}>

function Home({ searchParams }: { searchParams: AnySearchParams }) {
  const attribute = React.use(searchParams).attribute
  return (
    <div
      onSubmit={(e) => {
        // should fire if the form let the event bubble up
        if (e.defaultPrevented) {
          console.log('incorrect: default submit behavior was prevented')
        } else {

action="/search" id="search-form">
        <input name="query" />
        <button
          type="submit"
          formAction="/search"
          formEncType={
            attribute === 'formEncType' ? 'multipart/form-data' : undefined
          }

          console.log('correct: default submit behavior was not prevented')
          e.preventDefault() // this submission will do something stupid, we don't want it to actually go through.
        }
      }}
    >
      <Form


lient'
import * as React from 'react'
import * as react from 'library-with-exports/react'
import * as serverFavoringBrowser from 'library-with-exports/server-favoring-browser'
import * as serverFavoringEdge from 'library-with-exports/server-favoring-edge'

export default function ClientPage({
  action,
  server,
}: {
  action: () => Promise<Record<string, string>>
  server: unknown
}) {
  const [actionValue, formAction, isPending] = React.useActionState(
    action,
    undefined
  )
  const [client, setCli

ion,
    })
  }, [])

  return (
    <form action={formAction}>
      <input type="submit" />
      <output aria-busy={client === null || isPending}>
        {client === null ? (
          <pre>{JSON.stringify({ server }, null, 2)}</pre>
        ) : (

ent] = React.useState<unknown | null>(null)
  React.useEffect(() => {
    setClient({
      react: react.condition,
      serverFavoringBrowser: serverFavoringBrowser.condition,
      serverFavoringEdge: serverFavoringEdge.condit


2ftest-file.txt')
  })

  it('should prevent traversing with /..%2f..%2f..%2f..%2ftest-file.txt', async () => {
    await expectStatus('/..%2f..%2f..%2f..%2ftest-file.txt')
  })

  it('should prevent traversing with /..%2f..%2f..%2f..%2f..%2ftest-file.txt', async () => {
    await expectStatus('/..%2f..%2f..%2f..%2f..%2ftest-file.txt')
  })

  it('should prevent traversing with /..%2f..%2f..%2f..%2f..%2f..%2ftest-file.txt', async () => {
    await expectStatus('/..%2f..%2f..%2f..%2f..%2f..%2ftest-file.txt')

/..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2ftest-file.txt', async () => {
    await expectStatus('/..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2ftest-file.txt')
  })

  it('should prevent traversing with /%2e%2e/test-file.txt', async () => {
    await expectStatus(

  })

  it('should prevent traversing with /..%2f..%2f..%2f..%2f..%2f..%2f..%2ftest-file.txt', async () => {
    await expectStatus('/..%2f..%2f..%2f..%2f..%2f..%2f..%2ftest-file.txt')
  })

  it('should prevent traversing with


ort React from 'react'
import Image from 'next/image'

const Page = () => {
  return (

Wrapper Div

        <Image
          id="img1"
          src="/wide.png"
          width="1200"
          height="700"
          loading="eager"
        />

        <Image
          id="img2"
          src="/wide.png"
          width="1200"
          height="700"
          style={{
            paddingLeft: '4rem',

h="400"
          height="400"
          loading="eager"
        />
      </div>
      <div id="image-container4">
        <Image
          id="img4"
          src="/test.png"
          width="400"
          height="400"
          loading="eager"

      width: '100%',
            objectPosition: '30% 30%',
          }}
          sizes="50vh"
        />
      </div>
      <div id="image-container3">
        <Image
          id="img3"
          src="/test.png"
          widt


  typescript: {
          ignoreBuildErrors: true,
        },
      },
    })

    const isAppDir = type === 'app'
    const pathPrefix = isAppDir ? '' : '/pages-dir'

    it(
      'should soft-navigate on submit' +
        (isAppDir ? ' and show the prefetched loading state' : ''),
      async () => {
        const session = await next.browser(pathPrefix + '/forms/basic')
        const navigationTracker = await trackMpaNavs(session)

        const searchInput = await session.elementByCss('input[name="quer

ading state, so it should be displayed
          await session.waitForElementByCss('#loading')
        }

        const result = await session
          .waitForElementByCss('#search-results')
          .text()
        expect(result).toMatch(/query: "my se

y"]')
        await searchInput.fill('my search')

        const submitButton = await session.elementByCss('[type="submit"]')
        await submitButton.click()

        if (isAppDir) {
          // we should have prefetched a lo


 deployed
      {
        'library-with-exports': 'file:./library-with-exports',
      }
    : {
        'library-with-exports': 'link:./library-with-exports',
      }

  const { next } = nextTestSetup({
    files: __dirname,
    dependencies,
  })

  it('Pages Router page headers with edge runtime', async () => {
    const response = await next.fetch('/pages/edge-page')

    const middlewareHeaders = {
      react: response.headers.get('x-react-condition'),
      serverFavoringBrowser: response.headers.get

',
      serverFavoringBrowser: 'browser',
      serverFavoringEdge: 'edge-light',
    })
  })

  it('Pages Router page with edge runtime', async () => {
    const browser = await next.browser('/pages/edge-page')

    const json = await browser.elementByCs

(
        'x-server-favoring-browser-condition'
      ),
      serverFavoringEdge: response.headers.get(
        'x-server-favoring-edge-condition'
      ),
    }
    expect(middlewareHeaders).toEqual({
      react: 'react-server


/ Hoisted state to count each image load callback
  const [idToCount, setIdToCount] = useState({})
  const [clicked, setClicked] = useState(false)

  return (

On Loading Complete Test

      <ImageWithMessage
        id="1"
        src="/test.jpg"
        width="128"
        height="128"
        idToCount={idToCount}
        setIdToCount={setIdToCount}
      />

      <ImageWithMessage
        id="2"
        src={require('../../public/test.png')}
        placeholder="blur"
        id

ToCount}
      />

      <ImageWithMessage
        id="4"
        src="/test.ico"
        width={200}
        height={200}
        idToCount={idToCount}
        setIdToCount={setIdToCount}
      />

      <ImageWithMessage
        id="5"
        src="data:

ToCount={idToCount}
        setIdToCount={setIdToCount}
      />

      <ImageWithMessage
        id="3"
        src="/test.svg"
        width="1200"
        height="1200"
        idToCount={idToCount}
        setIdToCount={setId


rt * as React from 'react'
import Form from 'next/form'
import { useRouter } from 'next/router'

const isReact18 = typeof React.useActionState !== 'function'

export default isReact18 ? DummyPage : Page

function DummyPage() {
  return <>This test cannot run in React 18</>
}

function Page() {
  const destination = '/pages-dir/redirected-from-action'
  const router = useRouter()
  const [, dispatch] = React.useActionState(() => {
    const to = destination + '?' + new URLSearchParams({ query })
    router.p

 React.useState('')
  return (
    <Form action={dispatch} id="search-form">
      <input
        name="query"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />

      <button type="submit">Submit (client action)</button>

ush(to)
  }, undefined)

  const [query, setQuery] =


nc(logPath, 'utf-8')
  const lines = content.split('\n').filter(Boolean)
  if (lines.length === 0) {
    return null
  }
  const [, timestamp] = lines[0].split(':')
  return parseInt(timestamp, 10)
}

function parseCurrentTimeTimestamp(html: string): number {
  const match = html.match(/id="current-time">(\d+)</)
  if (!match) {
    throw new Error('Could not find current-time timestamp in response HTML')
  }
  return parseInt(match[1], 10)
}

function parseDeferredCallbackTimestamp(html: string): number {

1], 10)
}

async function expectPngResponse(res: Response) {
  expect(res.status).toBe(200)
  expect(res.headers.get('content-type')).toContain('image/png')

  const body = Buffer.from(await res.arrayBuffer())
  expect(body.byteLength).toBeGreaterThan(8)

  const match = html.match(
    /id="deferred-callback-timestamp">(?:<!-- -->)?(\d+)/
  )
  if (!match) {
    throw new Error(
      'Could not find deferred callback timestamp in response HTML'
    )
  }
  return parseInt(match[


jpg from '../public/test.jpg'
import png from '../public/test.png'
import avif from '../public/test.avif'
import webp from '../public/test.webp'

const Page = () => {
  return (
    <>

Layout fill inside non-relative parent

        <Image id="static" layout="fill" priority src={jpg} />

        <Image id="fixed" layout="fill" prior

sition: 'absolute', width: '200px', height: '200px' }}>
        <Image id="absolute" layout="fill" priority src={avif} />
      </div>
      <div style={{ position: 'relative', width: '200px', height: '200px' }}>
        <Image id="relative" layout="fill"

ity src={png} />
      </div>
      <div style={{ po


from 'react'
import Image from 'next/legacy/image'

const Page = () => {
  return (

Layout Fill

        <Image id="fill1" src="/wide.png" layout="fill" />

Layout Fill

        <Image
          id="fill2"
          src="/wide.png"
          layout="fill"
          objectFit="cover"
          objectPosition=

objectFit="cover"
          objectPosition="left center"
          sizes="(min-width: 1200px) 90vw,
                 (min-width: 800px) 30vw,
                 100vw"
        />

Layout Fill

      <div style={{ position: 'rel

"left center"
        />

Layout Fill

        <Image
          id="fill3"
          src="/wide.png"
          layout="fill"


port React from 'react'
import Image from 'next/legacy/image'

const Page = () => {
  return (

Layout Intrinsic

      <Image
        id="intrinsic1"
        src="/wide.png"
        width="1200"
        height="700"
        layout="intrinsic"
      ></Image>
      <Image
        id="intrinsic2"
        src="/wide.png"
        width="1200"
        height="700"
        layout="intrinsic"
      ></Image>
      <Image
        id="intrinsic3"
        src="/wide.png"
        width="1200"

00"
        layout="intrinsic"
      ></Image>
      <Image
        id="intrinsic4"
        src="/wide.png"
        width="1200"
        height="700"
        layout="intrinsic"
      ></Image>

Layout Intrinsic

  )
}

export default


, { useRef } from 'react'
import Image from 'next/legacy/image'

const Page = () => {
  const myRef = useRef(null)

  return (
    <>

hello

          <Image
            id="myImage1"

c="/test.png"
            alt="mine"
            width="400"
            height="400"
            lazyBoundary="1800px"
          />
          <Image
            lazyRoot={myRef}
            id="myImage3"
            src="/test.svg"
            alt="mine"

        src="/test.jpg"
            alt="mine"
            width="400"
            height="400"
            lazyBoundary="1500px"
          />
          <Image
            lazyRoot={myRef}
            id="myImage2"
            sr


import { useState } from 'react'
import Image from 'next/legacy/image'

const Page = () => {
  return (

Test onError

        If error occurred while loading image, native onError should be called.

      <ImageWithMessage id="1" src="/test.png" layout="fill" />

      <ImageWithMessage id="2" src="/nonexistent-img.png" layout="fill" />

  )
}

function ImageWithMessage({ id, ...props }) {
  const [msg, setMsg] = useState('no er

${id}`}
          onError={(e) => {
            const msg = `error occurred while loading ${e.target.id}`
            setMsg(msg)
          }}
          {...props}
        />

      <p id={`msg${id}`}>{msg}

    </>
  )
}

expor

ror occurred')
  const style =
    props.layout === 'fill'
      ? { position: 'relative', width: '64px', height: '64px' }
      : {}

  return (
    <>
      <div className="wrap" style={style}>
        <Image
          id={`img


'next/legacy/image'

const Page = () => {
  // Hoisted state to count each image load callback
  const [idToCount, setIdToCount] = useState({})
  const [clicked, setClicked] = useState(false)

  return (

Test onLoad

        This is the native onLoad which doesn't work as many places as
        onLoadingComplete

      <ImageWithMessage
        id="1"
        src="/test.jpg"
        layout="intrinsic"
        width="128"
        height="128"
        idToCount={idT

dToCount={setIdToCount}
      />

      <ImageWithMessage
        id="3"
        src="/test.svg"
        layout="responsive"
        width="1200"
        height="1200"
        idToCount={idToCount}
        setIdToCount={setIdToCount}
      />

      <Image

oCount}
        setIdToCount={setIdToCount}
      />

      <ImageWithMessage
        id="2"
        src={require('../public/test.png')}
        placeholder="blur"
        layout="fixed"
        idToCount={idToCount}
        setI


ted state to count each image load callback
  const [idToCount, setIdToCount] = useState({})
  const [clicked, setClicked] = useState(false)

  return (

On Loading Complete Test

      <ImageWithMessage
        id="1"
        src="/test.jpg"
        layout="intrinsic"
        width="128"
        height="128"
        idToCount={idToCount}
        setIdToCount={setIdToCount}
      />

      <ImageWithMessage
        id="2"
        src={require('../public/test.png')}
        placeholder

ight="1200"
        idToCount={idToCount}
        setIdToCount={setIdToCount}
      />

      <ImageWithMessage
        id="4"
        src="/test.ico"
        layout="fill"
        objectFit="contain"
        idToCount={idToCount}
        setIdToCount={set

="blur"
        layout="fixed"
        idToCount={idToCount}
        setIdToCount={setIdToCount}
      />

      <ImageWithMessage
        id="3"
        src="/test.svg"
        layout="responsive"
        width="1200"
        he


import Image from 'next/legacy/image'

const Page = () => {
  return (

Priority Page

      <Image
        priority
        id="basic-image"
        src="/test.jpg"
        width="400"
        height="400"
      ></Image>
      <Image
        priority
        id="basic-image-with-crossorigin"
        crossOrigin="use-credentials"
        src="/test.gif"
        width="400"
        height="400"
      ></Image>
      <Image
        priority
        id="basic-image-with-referrerpolicy"

        src="/test.png"
        width="400"
        height="400"
      ></Image>
      <Image
        loading="eager"
        id="load-eager"
        src="/test.png"
        width="400"
        height="400"
      ></Image>
      <Image
        priority

       referrerPolicy="no-referrer"
        src="/test.png"
        width="400"
        height="400"
      ></Image>
      <Image
        priority
        id="basic-image-with-referrerpolicy"
        referrerPolicy="no-referrer"


import testImg from '../public/foo/test-rect.jpg'
import testImgProp from '../public/exif-rotation.jpg'
import Image from 'next/legacy/image'

import testJPG from '../public/test.jpg'
import testPNG from '../public/test.png'
import testWEBP from '../public/test.webp'
import testAVIF from '../public/test.avif'
import testSVG from '../public/test.svg'
import testGIF from '../public/test.gif'
import testBMP from '../public/test.bmp'
import testICO from '../public/test.ico'

import TallImage from '../component

   src={testImg}
        layout="fixed"
        placeholder="blur"
      />
      <Image
        id="basic-staticprop"
        src={testImgProp}
        layout="fixed"
        placeholder="blur"
      />
      <TallImage />
      <Image
        id="defined

s/TallImage'

export const getStaticProps = () => ({
  props: { testImgProp },
})

const Page = ({ testImgProp }) => {
  return (

Static Image

      <Image
        id="basic-static"


age from 'next/legacy/image'
import style from '../style.module.css'

const Page = () => {
  return (

Image Style Inheritance

      <Image
        id="img-fixed"
        layout="fixed"
        src="/test.jpg"
        width="400"
        height="400"
      />

      <Image
        id="img-intrinsic"
        layout="intrinsic"
        src="/test.jpg"
        width="400"
        height="400"
      />

      <div style={{ position: 're

 <Image id="img-fill" layout="fill" src="/test.jpg" objectFit="cover" />
      </div>

      <Image
        id="img-responsive"
        layout="responsive"
        src="/test.jpg"
        width="400"
        height="400"
      />

      <footer>Footer</foo

lative', width: '200px', height: '200px' }}>


eact from 'react'
import Image from 'next/legacy/image'

const Page = () => {
  return (

Style prop usage and warnings

      <Image
        layout="fixed"
        id="with-styles"
        src="/test.png"
        width={400}
        height={400}
        style={{ borderRadius: '10px', padding: 10 }}
        loading="eager"
      />
      <Image
        layout="intrinsic"
        id="with-overlapping-styles-intrinsic"
        src="/test.jpg"
        width={400}
        height={400}

argin: '15px' }}
        loading="eager"
      />
      <Image
        layout="responsive"
        id="without-styles-responsive"
        src="/test.webp"
        width={400}
        height={400}
        loading="eager"
      />
    </div>
  )
}

export de

style={{ width: '10px', borderRadius: '10px', m


oin } from 'path'

describe('TypeScript Image Component', () => {
  const { next, skipped } = nextTestSetup({
    files: __dirname,
    skipStart: true,
    skipDeployment: true,
  })
  if (skipped) return

  if (isNextStart) {
    it('should fail to build invalid usage of the Image component', async () => {
      const { cliOutput, exitCode } = await next.build()
      expect(cliOutput).toMatch(/Failed to type check/)
      expect(cliOutput).toMatch(/is not assignable to type/)
      expect(exitCode).toBe(

d', async () => {
      const nextConfigPath = join(next.testDir, 'next.config.js')
      const content = await fs.readFile(nextConfigPath, 'utf8')
      await fs.writeFile(
        nextConfigPath,
        content.replace('// disableStaticImages', 'disable

1)
      const envTypes = await fs.readFile(
        join(next.testDir, 'next-env.d.ts'),
        'utf8'
      )
      expect(envTypes).toContain('image-types/global')
    })

    it('should remove global image types when disable


from 'react'
import Image from 'next/legacy/image'

const Invalid = () => {
  return (

Invalid TS

      <Image id="invalid-src" src={new Date()} width={500} height={500}></Image>
      <Image
        id="invalid-width"
        src="https://image-optimization-test.vercel.app/test.jpg"
        width={new Date()}
        height={500}
      ></Image>
      <Image
        id="invalid-layout"
        src="https://image-optimization-test.vercel.app/test.jpg"
        width="500"
        he

alid"
      ></Image>
      <Image
        id="invalid-width-string-type"
        alt="invalid-width-string-type"
        src="https://image-optimization-test.vercel.app/test.jpg"
        width="500foo"
      />
      <Image
        id="invalid-height-stri

ight="500"
        layout="invalid"
      ></Image>
      <Image
        id="invalid-placeholder"
        src="https://image-optimization-test.vercel.app/test.jpg"
        width="500"
        height="500"
        placeholder="inv


ng'
import svg from '../public/test.svg'
import avif from '../public/test.avif'
import { ImageCard } from '../components/image-card'
import { DynamicSrcImage } from '../components/image-dynamic-src'

const Page = () => {
  return (

Valid TS

      <Image
        id="width-and-height-num"
        src="https://image-optimization-test.vercel.app/test.jpg"
        width={500}
        height={500}
      />
      <Image
        id="width-and-height-str"
        src="https://image-optimizatio

on-test.vercel.app/test.jpg"
          layout="fill"
        />
      </div>
      <Image
        id="quality-num"
        src="https://image-optimization-test.vercel.app/test.jpg"
        quality={80}
        width={500}
        height={500}
      />

n-test.vercel.app/test.jpg"
        width="500"
        height="500"
      />
      <div style={{ position: 'relative', width: 100, height: 100 }}>
        <Image
          id="layout-fill"
          src="https://image-optimizati


('Image Component Unicode Image URL', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  it('should load static unicode image', async () => {
    const browser = await next.browser('/')
    const src = await browser.elementById('static').getAttribute('src')
    expect(src).toMatch(
      /_next%2Fstatic%2F(immutable%2F)?media%2F%C3%A4%C3%B6%C3%BC%C5%A1%C4%8D%C5%99%C3%AD(.+)png/
    )
    const fullSrc = new URL(src, next.url)
    const res = await fetch(fullSrc)
    expect(res.status).

/image?url=%2F%C3%A4%C3%B6%C3%BC%C5%A1%C4%8D%C5%99%C3%AD.png'
    )
    const fullSrc = new URL(src, next.url)
    const res = await fetch(fullSrc)
    expect(res.status).toBe(200)
  })

  it('should load external unicode image', async () => {
    const br

toBe(200)
  })

  it('should load internal unicode image', async () => {
    const browser = await next.browser('/')
    const src = await browser.elementById('internal').getAttribute('src')
    expect(src).toMatch(
      '/_next


ed Image Tests', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  it('should not optimize any image', async () => {
    const browser = await next.browser('/')

    expect(
      await browser.elementById('internal-image').getAttribute('src')
    ).toMatch('data:')
    expect(
      await browser.elementById('static-image').getAttribute('src')
    ).toMatch('data:')
    expect(
      await browser.elementById('external-image').getAttribute('src')
    ).toMatch('data:')
    expect(

.elementById('static-image').getAttribute('srcset')
    ).toBeNull()
    expect(
      await browser.elementById('external-image').getAttribute('srcset')
    ).toBeNull()
    expect(
      await browser.elementById('eager-image').getAttribute('srcset')

    await browser.elementById('eager-image').getAttribute('src')
    ).toMatch(/\/test\.webp/)

    expect(
      await browser.elementById('internal-image').getAttribute('srcset')
    ).toBeNull()
    expect(
      await browser


t React from 'react'
import Image from 'next/legacy/image'
import testJpg from '../public/test.jpg'

const Page = () => {
  return (

Unoptimized Config

Scroll down...

      <Image id="internal-image" src="/test.png" width={400} height={400} />

      <Image id="static-image" src={testJpg} width={400} height={400} />

      <Image
        id="external-image"
        src="https://image-optimization-test.ve

jpg"
        width={400}
        height={400}
      />
      <div style={{ height: '1000vh' }} />
      <Image
        id="eager-image"
        src="/test.webp"
        width={400}
        height={400}
        loading="eager"
      />
    </div>
  )
}

exp


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

describe('Legacy Image Component assetPrefix Tests', () => {
  const { next, isTurbopack } = nextTestSetup({
    files: __dirname,
  })

  it('should include assetPrefix when placeholder=blur during dev', async () => {
    if (!isNextDev) return
    const browser = await next.browser('/')
    const id = 'test1'
    const bgImage = await browser.eval(
      `document.getElementById('${id}').style['background-image']`
    )
    if (isTurbopack) {
      expect

se base64 data url with placeholder=blur during production', async () => {
    if (isNextDev) return
    const browser = await next.browser('/')
    const id = 'test1'
    const bgImage = await browser.eval(
      `document.getElementById('${id}').style['b

(bgImage).toContain('data:image/jpeg;')
    } else {
      expect(bgImage).toMatch(
        /\/_next\/image\?url=https%3A%2F%2Fexample.com%2Fpre%2F_next%2Fstatic%2Fmedia%2Ftest(.+).jpg&w=8&q=70/
      )
    }
  })

  it('should u


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

describe('Image Component Trailing Slash Tests', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  it('should include trailing slash when trailingSlash is set on config file', async () => {
    const browser = await next.browser('/')
    const id = 'test1'

    // Use retry for both dev and production modes since the legacy Image component
    // needs time to load and replace the initial placeholder data U

c () => {
      const srcImage = await browser.eval(
        `document.getElementById('${id}').src`
      )
      expect(srcImage).toMatch(
        /\/_next\/image\/\?url=%2F_next%2Fstatic%2F(immutable%2F)?media%2Ftest(.+).jpg&w=828&q=75/
      )
    })

RL with the optimized image URL
    await retry(asyn


skipDeployment: true,
  })

  if (isNextDev) {
    it('no-op in dev', () => {})
    return
  }

  it('should throw build error when import statement is used with missing file', async () => {
    await next.patchFile(
      'pages/static-img.js',
      (content) =>
        content.replace(
          '../public/foo/test-rect.jpg',
          '../public/foo/test-rect-broken.jpg'
        ),
      async () => {
        const { cliOutput } = await next.build()
        expect(cliOutput).toContain(
          "Module

xt, isTurbopack, skipped } = nextTestSetup({
    files: __dirname,
    skipDeployment: true,
  })
  if (skipped) return

  let browser: Playwright
  let html: string

  beforeAll(async () => {
    html = await next.render('/docs/static-img')
    browser =

 not found: Can't resolve '../public/foo/test-rect-broken.jpg"
        )
        expect(cliOutput).toContain('pages/static-img.js')
      }
    )
  })
})

describe('Static Image Component Tests for basePath', () => {
  const { ne


Id(next.testDir, ...)`, which reads the local
    // `.next/required-server-files.json`. In deploy mode that file lives on
    // Vercel's infrastructure (not on disk locally), so the constructed
    // expected URL omits the `&dpl=...` query that Vercel injects at
    // runtime. The assertions are about local-build URL shape, not deploy
    // CDN URLs, so skip in deploy.
    skipDeployment: true,
  })
  if (skipped) return

  let dpl: string
  beforeAll(() => {
    dpl = getDeploymentId(next.testDir, isN

rl).toString()
      )
    )
  }

  async function getComputed(browser, id, prop) {
    const val = await browser.eval(`document.getElementById('${id}').${prop}`)
    if (typeof val === 'number') {
      return val
    }
    if (typeof val === 'string') {

extDev).getDeploymentIdQuery(true)
  })

  async function getImageUrls(browser) {
    return await Promise.all(
      (await browser.elementsByCss('img')).map(async (link) =>
        new URL(await link.getAttribute('src'), next.u


'
import Image from 'next/legacy/image'

const Page = () => {
  return (

Layout Intrinsic

      <Image
        id="intrinsic1"
        src="/docs/wide.png"
        width="1200"
        height="700"
        layout="intrinsic"
      ></Image>
      <Image
        id="intrinsic2"
        src="/docs/wide.png"
        width="1200"
        height="700"
        layout="intrinsic"
      ></Image>
      <Image
        id="intrinsic3"
        src="/docs/wide.png"
        width="1200"
        he

layout="intrinsic"
      ></Image>
      <Image
        id="intrinsic4"
        src="/docs/wide.png"
        width="1200"
        height="700"
        layout="intrinsic"
      ></Image>

Layout Intrinsic

  )
}

export default Pa


port React from 'react'
import Image from 'next/legacy/image'

const Page = () => {
  return (

Layout Responsive

      <Image
        id="responsive1"
        src="/docs/wide.png"
        width="1200"
        height="700"
        layout="responsive"
      />
      <Image
        id="responsive2"
        src="/docs/wide.png"
        width="1200"
        height="700"
        layout="responsive"
      />
      <Image
        id="responsive3"
        src="/docs/wide.png"
        width="12

ight="700"
        layout="responsive"
      />
      <Image
        id="responsive4"
        src="/docs/wide.png"
        width="1200"
        height="700"
        layout="responsive"
      />

Layout Responsive

  )
}

export defaul


import testImg from '../public/foo/test-rect.jpg'
import Image from 'next/legacy/image'

import testJPG from '../public/test.jpg'
import testPNG from '../public/test.png'
import testWEBP from '../public/test.webp'
import testAVIF from '../public/test.avif'
import testSVG from '../public/test.svg'
import testGIF from '../public/test.gif'
import testBMP from '../public/test.bmp'
import testICO from '../public/test.ico'

import TallImage from '../components/TallImage'

const Page = () => {
  return (
    <div

ic"
        src={testPNG}
        layout="fixed"
        height="200"
        width="200"
      />
      <Image id="require-static" src={require('../public/foo/test-rect.jpg')} />
      <Image
        id="basic-non-static"
        src="/test-rect.jpg"

>

Static Image

      <Image
        id="basic-static"
        src={testImg}
        layout="fixed"
        placeholder="blur"
      />
      <TallImage />
      <Image
        id="defined-size-stat


n } from 'path'
import { renderViaHTTP, check } from 'next-test-utils'
import { FileRef, nextTestSetup } from 'e2e-utils'

describe('React Context', () => {
  const { next } = nextTestSetup({
    files: {
      pages: new FileRef(join(__dirname, 'app/pages')),
      'context.js': new FileRef(join(__dirname, 'app/context.js')),
    },
  })

  it('should render a page with context', async () => {
    const html = await renderViaHTTP(next.url, '/')
    expect(html).toMatch(/Value: .*?hello world/)
  })

  it('

der with context after change', async () => {
      const aboutAppPagePath = 'pages/_app.js'
      const originalContent = await next.readFile(aboutAppPagePath)
      await next.patchFile(
        aboutAppPagePath,
        originalContent.replace('hello wo

should render correctly with context consumer', async () => {
    const html = await renderViaHTTP(next.url, '/consumer')
    expect(html).toMatch(/Value: .*?12345/)
  })

  if ((globalThis as any).isNextDev) {
    it('should ren


.toBe(
          'Param found: shirts_and_tops, mens_ua_playoff_polo_2.0, 1327037.html'
        )
      })

      it('should work using browser', async () => {
        const browser = await next.browser(
          '/product/shirts_and_tops/mens_ua_playoff_polo_2.0/1327037.html'
        )
        expect(await browser.elementByCss('#text').text()).toBe(
          'Param found: shirts_and_tops, mens_ua_playoff_polo_2.0, 1327037.html'
        )
      })

      it('should work when navigating', async () => {

_ua_playoff_polo_2.0, 1327037.html'
        )
      })
    })

    describe('without .html extension', () => {
      it('should work when requesting the page directly', async () => {
        const $ = await next.render$(
          '/product/shirts_and_tops

     const browser = await next.browser('/html-links')
        await browser.elementByCss('#with-html').click()
        expect(await browser.waitForElementByCss('#text').text()).toBe(
          'Param found: shirts_and_tops, mens


er'

export async function middleware(request) {
  const url = request.nextUrl

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

  if (request.headers.get('x-prerender-revalidate')) {
    return NextResponse.next({
      headers: { 'x-middleware': 'hi' },
    })
  }

  if (url.pathname === '/about/') {
    return NextResponse.rewrite(new URL('/about/a', request.url))
  }

  if (url.pathname === '/ssr-page/') {

ame = '/ssg/hello'
    url.searchParams.set('from', 'middleware')
    return NextResponse.rewrite(url)
  }

  if (url.pathname === '/sha/') {
    url.pathname = '/shallow'
    return NextResponse.rewrite(url)
  }

  if (url.pathname === '/rewrite-to-dynami

    url.pathname = '/ssr-page-2'
    return NextResponse.rewrite(url)
  }

  if (url.pathname === '/') {
    url.pathname = '/ssg/first'
    return NextResponse.rewrite(url)
  }

  if (url.pathname === '/to-ssg/') {
    url.pathn


export default function Shallow({ message }) {
  const { pathname, query } = useRouter()
  return (

{message}

          <Link href="/sha?hello=world" shallow id="shallow-link">
            Shallow link to ?hello=world
          </Link>

          <Link href="/sha?hello=goodbye" id="deep-link">
            Deep link to ?hello=goodbye
          </Link>

            Current query: {JSON.stringify(query)}

  )
}

let i = 0

export const getServerSideP


{ useEffect } from 'react'
import { useState } from 'react'

export default function Page(props) {
  const router = useRouter()
  const [asPath, setAsPath] = useState(
    router.isReady ? router.asPath : router.href
  )

  useEffect(() => {
    if (router.isReady) {
      setAsPath(router.asPath)
    }
  }, [router.asPath, router.isReady])

  return (
    <>

/blog/[slug]

{JSON.stringify(router.query)}

{router.pathname}

      <p id="as

ify(props)}</p>
    </>
  )
}

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

export function getStaticPaths() {
  return {
    paths: ['/ssg/first', '/ssg/hello'],
    fallback: 'blo


('Unoptimized Image Tests', () => {
  const { next } = nextTestSetup({
    files: __dirname,
    skipDeployment: true,
  })

  function runTests(url: string) {
    it(`should not optimize any image (${url})`, async () => {
      const browser = await next.browser(url)
      expect(
        await browser.elementById('internal-image').getAttribute('src')
      ).toMatch(/\/test.png(\?dpl=.*)?/)
      expect(
        await browser.elementById('static-image').getAttribute('src')
      ).toMatch(/test(.*)jpg/)

'src')
      ).toMatch(/\/test.webp(\?dpl=.*)?/)

      expect(
        await browser.elementById('internal-image').getAttribute('srcset')
      ).toBeNull()
      expect(
        await browser.elementById('static-image').getAttribute('srcset')
      ).toB

     expect(
        await browser.elementById('external-image').getAttribute('src')
      ).toBe('https://image-optimization-test.vercel.app/test.jpg')
      expect(
        await browser.elementById('eager-image').getAttribute(


t React from 'react'
import Image from 'next/image'
import testJpg from '../public/test.jpg'

const Page = () => {
  return (

Unoptimized Config

Scroll down...

      <Image id="internal-image" src="/test.png" width={400} height={400} />

      <Image id="static-image" src={testJpg} width={400} height={400} />

      <Image
        id="external-image"
        src="https://image-optimization-test.vercel.ap

      width={400}
        height={400}
      />
      <div style={{ height: '1000vh' }} />
      <Image
        id="eager-image"
        src="/test.webp"
        width={400}
        height={400}
        loading="eager"
      />
    </div>
  )
}

export def


'next-test-utils'

describe('Image qualities config', () => {
  const { next } = nextTestSetup({
    files: __dirname,
    skipDeployment: true,
  })

  async function getSrc(browser: Playwright, id: string) {
    const src = await browser.elementById(id).getAttribute('src')
    if (src) {
      const url = new URL(src, next.url)
      return url.href.slice(url.origin.length)
    }
  }

  it('should load img when quality is undefined', async () => {
    const browser = await next.browser('/')
    if (isNext

'should load img when quality 42', async () => {
    const browser = await next.browser('/')
    if (isNextDev) {
      await waitForNoRedbox(browser)
    }
    const url = await getSrc(browser, 'q-42')
    const res = await next.fetch(url)
    expect(res.

Dev) {
      await waitForNoRedbox(browser)
    }
    const url = await getSrc(browser, 'q-undefined')
    const res = await next.fetch(url)
    expect(res.status).toStrictEqual(200)
    expect(url).toContain('&q=69')
  })

  it(


('Image Loader Config with Default Loader and File', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  describe('component', () => {
    it('should work with loaderFile config, leaving default image optimization enabled', async () => {
      const browser = await next.browser('/')
      expect(await browser.elementById('img1').getAttribute('src')).toBe(
        '/_next/image/?url=/logo.png&w=828&q=50'
      )
      expect(await browser.elementById('img1').getAttribute('srcset')).toBe(

g1').naturalWidth !== 0`
        )
      ).toBe(true)
    })

    it('should work with loader prop', async () => {
      const browser = await next.browser('/')
      expect(await browser.elementById('img2').getAttribute('src')).toBe(
        '/logo.png?wi

        '/_next/image/?url=/logo.png&w=640&q=50 1x, /_next/image/?url=/logo.png&w=828&q=50 2x'
      )

      expect(
        await browser.eval(
          `document.getElementById('img1').complete && document.getElementById('im


port statement is used with missing file', async () => {
    await next.patchFile(
      'pages/static-img.js',
      (content) =>
        content.replace(
          '../public/foo/test-rect.jpg',
          '../public/foo/test-rect-broken.jpg'
        ),
      async () => {
        const { cliOutput } = await next.build()
        expect(cliOutput).toContain(
          "Module not found: Can't resolve '../public/foo/test-rect-broken.jpg"
        )
        if (isTurbopack) {
          expect(cliOutput).toCont

tatic Image Component Tests for basePath', () => {
  const { next, isTurbopack, skipped } = nextTestSetup({
    files: __dirname,
    skipDeployment: true,
  })
  if (skipped) return

  let browser: Playwright
  let $: ReturnType<typeof cheerio.load>

  be

ain('/pages/static-img.js')
        } else {
          expect(cliOutput).toContain('./pages/static-img.js')
        }
        expect(cliOutput).not.toContain('Import trace for requested module')
      }
    )
  })
})

describe('S


tRedboxHeader,
  getDeploymentId,
  retry,
} from 'next-test-utils'

describe('Image Component basePath Tests', () => {
  const { next, skipped } = nextTestSetup({
    files: __dirname,
    disableAutoSkewProtection: true,
    // Image URL assertions construct expected URLs via
    // `getDeploymentId(next.testDir, ...)`, which reads the local
    // `.next/required-server-files.json`. In deploy mode that file lives on
    // Vercel's infrastructure (not on disk locally), so the constructed
    // expected

 string
  beforeAll(() => {
    dpl = getDeploymentId(next.testDir, isNextDev).getDeploymentIdQuery(true)
  })

  async function getImageUrls(browser) {
    return await Promise.all(
      (await browser.elementsByCss('img')).map(async (link) =>
        ne

URL omits the `&dpl=...` query that Vercel injects at
    // runtime. The assertions are about local-build URL shape, not deploy
    // CDN URLs, so skip in deploy.
    skipDeployment: true,
  })
  if (skipped) return

  let dpl:


allow Routing', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  it('should not shallowly navigate back in history when current page was not shallow', async () => {
    const browser = await next.browser('/first')

    const props = JSON.parse(await browser.elementByCss('#props').text())
    expect(props.params).toEqual({ slug: 'first' })

    await browser.elementByCss('#add-query-shallow').click()
    await retry(async () => {
      const props2 = JSON.parse(await browser.elementBy

text())
      expect(props3).toEqual(props)
    })

    await browser.elementByCss('#to-another').click()
    await retry(async () => {
      const text = await browser.elementByCss('#props').text()
      expect(text).toMatch(/another/)
    })

    const p

Css('#props').text())
      expect(props2).toEqual(props)
    })

    await browser.elementByCss('#remove-query-shallow').click()
    await retry(async () => {
      const props3 = JSON.parse(await browser.elementByCss('#props').


,
  }
}

describe('Prerender Preview Mode', () => {
  const { next, isNextDev, isNextStart } = nextTestSetup({
    files: __dirname,
    dependencies: {
      cookie: '0.7.2',
    },
  })

  if (isNextStart) {
    it('should return prerendered page on first request', async () => {
      const html = await next.render('/')
      const { nextData, pre, routerData } = getData(html)
      expect(nextData).toMatchObject({ isFallback: false })
      expect(nextData.isPreview).toBeUndefined()
      expect(pre).toB

 } = getData(html)
      expect(nextData).toMatchObject({ isFallback: false })
      expect(nextData.isPreview).toBeUndefined()
      expect(pre).toBe('false and null')
      expect(routerData.isPreview).toBe(false)
    })
  }

  it('should throw error whe

e('false and null')
      expect(routerData.isPreview).toBe(false)
    })

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


i18n } = require('./next.config')

const pages = [
  { url: '/about', page: '/about', params: null },
  { url: '/blog/about', page: '/[slug]/about', params: { slug: 'blog' } },
]

function checkDataRoute(data: any, page: string) {
  expect(data).toHaveProperty('pageProps')
  expect(data.pageProps).toHaveProperty('page', page)
}

describe('i18n-data-route', () => {
  const { next, skipped } = nextTestSetup({
    files: __dirname,
    // This test skips deployment because env vars that are doubled underscore

  describe('with locale prefix', () => {
    describe.each(i18n.locales)('/%s', (locale) => {
      const prefixed = pages.map((page) => ({
        ...page,
        url: `/${locale}${page.url}`,
      }))

      it.each(prefixed)(
        'should render $

prefixed
    // are not supported.
    skipDeployment: true,
    env: {
      // Disable internal header stripping so we can test the invoke output.
      __NEXT_NO_STRIP_INTERNAL_HEADERS: '1',
    },
  })

  if (skipped) return


xt-test-utils'
import fs from 'fs-extra'
import path from 'path'

const warningText = `You are using a non-standard "NODE_ENV" value in your environment`

describe('Non-Standard NODE_ENV', () => {
  ;(isNextDev ? describe : describe.skip)('dev mode', () => {
    describe('no NODE_ENV set', () => {
      const { next } = nextTestSetup({
        files: __dirname,
      })

      it('should not show the warning with no NODE_ENV set', async () => {
        expect(next.cliOutput).not.toContain(warningText)

 to valid value', async () => {
        expect(next.cliOutput).not.toContain(warningText)
      })
    })

    describe('NODE_ENV=development (custom server)', () => {
      const { next } = nextTestSetup({
        files: __dirname,
        startCommand: '

 })
    })

    describe('NODE_ENV=development', () => {
      const { next } = nextTestSetup({
        files: __dirname,
        env: { NODE_ENV: 'development' },
      })

      it('should not show the warning with NODE_ENV set


rated SignedSource<<187ead9fb6e7b26d71c9161bda6ab902>>
 * @lightSyntaxTransform
 * @nogrep
 */

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

import { ConcreteRequest, Query } from 'relay-runtime'
export type pagesQuery$variables = {}
export type pagesQueryVariables = pagesQuery$variables
export type pagesQuery$data = {
  readonly greeting: string
}
export type pagesQueryResponse = pagesQuery$data
export type pagesQuery = {
  variables: pagesQueryVariables
  response: pagesQuery$data
}

const no

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

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


xtProd = !(global as any).isNextDev && !(global as any).isNextDeploy

describe('streaming SSR with custom next configs', () => {
  const { next } = nextTestSetup({
    files: join(__dirname, 'streaming-ssr'),
  })

  it('should match more specific route along with dynamic routes', async () => {
    const res1 = await fetchViaHTTP(next.url, '/api/user/login')
    const res2 = await fetchViaHTTP(next.url, '/api/user/any')
    expect(await res1.text()).toBe('login')
    expect(await res2.text()).toBe('[id]')

and render when slash is appended', async () => {
    const page = '/hello'
    const redirectRes = await fetchViaHTTP(
      next.url,
      page,
      {},
      { redirect: 'manual' }
    )
    const res = await fetchViaHTTP(next.url, page + '/')
    co

 })

  it('should render styled-jsx styles in streaming', async () => {
    const html = await renderViaHTTP(next.url, '/')
    expect(html).toMatch(/color:(?:blue|#00f)/)
  })

  it('should redirect paths without trailing-slash


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

describe('Edge compiler module exports preference', () => {
  if ((global as any).isNextDeploy) {
    // this test is skipped when deployed because it manually creates a package in the node_modules directory
    // which is unsupported
    it('should skip next deploy', () => {})
    return
  }

  const { next } = nextTestSetup({
    files: {
      'pages/index.js': `
        export default function Page() {
          return
hello world

          'x-imported': lib
            }
          })
        }
      `,
      'node_modules/my-lib/package.json': JSON.stringify({
        name: 'my-lib',
        version: '1.0.0',
        main: 'index.js',
        browser: 'browser.js',
      }),

        }
      `,
      'middleware.js': `
        import { NextResponse } from 'next/server';
        import lib from 'my-lib';

        export default (req) => {
          return NextResponse.next({
            headers: {


> {
  const { next, isTurbopack, isNextDeploy } = nextTestSetup({
    files: __dirname,
    skipStart: true,
    skipDeployment: true,
  })
  if (isNextDeploy) return
  ;(isNextStart ? it : it.skip)(
    'should throw build error when import statement is used with missing file',
    async () => {
      await next.patchFile(
        'pages/static-img.js',
        (content) =>
          content.replace(
            '../public/foo/test-rect.jpg',
            '../public/foo/test-rect-broken.jpg'
          ),

) {
            expect(cliOutput).toContain('pages/static-img.js')
          } else {
            expect(cliOutput).toContain('./pages/static-img.js')
          }
          expect(cliOutput).not.toContain('Import trace for requested module')
        }

      async () => {
          const { cliOutput } = await next.build()
          expect(cliOutput).toContain(
            "Module not found: Can't resolve '../public/foo/test-rect-broken.jpg"
          )
          if (isTurbopack


turn (

Blurry Placeholder

      <Image
        priority
        id="blurry-placeholder"
        src="/test.ico"
        width="400"
        height="400"
        placeholder="blur"
        blurDataURL="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='400' viewBox='0 0 400 400'%3E%3Cfilter id='blur' filterUnits='userSpaceOnUse' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20' edgeMode='duplicate' /%3E%3CfeComponentTransfer%3E%3CfeF

PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlT/wAALCAAKAAoBAREA/8QAMwABAQEAAAAAAAAAAAAAAAAAAAcJEAABAwUAAwAAAAAAAAAAAAAFAAYRAQMEEyEVMlH/2gAIAQEAAD8Az1bLPaxhiuk0QdeCOLDtHixN2dmd2bsc5FPX7VTREX//2Q==' x='0' y='0' height='100%25' width='100%25'/%3E%3C/svg%3E"
      />

uncA type='discrete' tableValues='1 1' /%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter='url(%23blur)' href='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4


port React from 'react'
import Image from 'next/legacy/image'

const Page = () => {
  return (

Warn when "sizes" is not used

      <Image
        layout="fixed"
        src="/test.png"
        width={400}
        height={400}
        sizes="50vw"
      />
      <Image
        layout="intrinsic"
        src="/test.jpg"
        width={400}
        height={400}
        sizes="50vw"
      />
      <Image
        layout="responsive"
        src="/test.webp"
        width={400}
        he

sizes="50vw"
      />

        <Image src="/test.gif" layout="fill" objectFit="cover" sizes="50vw" />

      footer

  )
}

export defa


 { nextTestSetup } from 'e2e-utils'

describe('Image Loader Config with Edge Runtime', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  it('should add "src" to img1 based on the loader config', async () => {
    const browser = await next.browser('/')
    expect(await browser.elementById('img1').getAttribute('src')).toBe(
      '/logo.png#w:828,q:50'
    )
  })

  it('should add "srcset" to img1 based on the loader config', async () => {
    const browser = await next.browser('/')

er = await next.browser('/')
    expect(await browser.elementById('img2').getAttribute('src')).toBe(
      '/logo.png?wid=640&qual=35'
    )
  })

  it('should add "srcset" to img2 based on the loader prop', async () => {
    const browser = await next.bro

  expect(await browser.elementById('img1').getAttribute('srcset')).toBe(
      '/logo.png#w:640,q:50 1x, /logo.png#w:828,q:50 2x'
    )
  })

  it('should add "src" to img2 based on the loader prop', async () => {
    const brows


mport React from 'react'
import { getImageProps } from 'next/image'
import testJpg from '../public/test.jpg'

const Page = () => {
  const { props: img1 } = getImageProps({
    id: 'internal-image',
    src: '/test.png',
    width: 400,
    height: 400,
  })
  const { props: img2 } = getImageProps({
    id: 'static-image',
    src: testJpg,
    width: 400,
    height: 400,
  })
  const { props: img3 } = getImageProps({
    id: 'external-image',
    src: 'https://image-optimization-test.vercel.app/test.jpg',

width: 400,
    height: 400,
  })
  const { props: img4 } = getImageProps({
    id: 'eager-image',
    src: '/test.webp',
    width: 400,
    height: 400,
    loading: 'eager',
  })
  return (

Unoptimized


tTestSetup, isNextDev } from 'e2e-utils'

describe('Image Component assetPrefix Tests', () => {
  const { next, isTurbopack } = nextTestSetup({
    files: __dirname,
  })

  it('should include assetPrefix when placeholder=blur during dev', async () => {
    if (!isNextDev) return
    const browser = await next.browser('/')
    const id = 'test1'
    const bgImage = await browser.eval(
      `document.getElementById('${id}').style['background-image']`
    )
    if (isTurbopack) {
      expect(bgImage).toCont

se64 data url with placeholder=blur during production', async () => {
    if (isNextDev) return
    const browser = await next.browser('/')
    const id = 'test1'
    const bgImage = await browser.eval(
      `document.getElementById('${id}').style['backgr

ain('data:image/svg+xml;')
    } else {
      expect(bgImage).toMatch(
        /\/_next\/image\?url=https%3A%2F%2Fexample\.vercel\.sh%2Fpre%2F_next%2Fstatic%2Fmedia%2Ftest(.+).jpg&w=8&q=70/
      )
    }
  })

  it('should use ba


v className="flex flex-col items-center justify-center min-h-screen py-2">

          Welcome to{' '}

            Next.js!

          Get started by editing{' '}
          <code className="p-3 font-mono text-

g/docs"
            className="p-6 mt-6 text-left border w-96 rounded-xl hover:text-blue-600 focus:text-blue-600"
          >

Documentation →

              Fi

lg bg-gray-100 rounded-md">
            pages/index.js
          </code>
        </p>

        <div className="flex flex-wrap items-center justify-around max-w-4xl mt-6 sm:w-full">
          <a
            href="https://nextjs.or


import { useState } from 'react'
import { useRouter } from 'next/router'

export function getStaticProps({ preview, previewData }) {
  return {
    props: {
      hasProps: true,
      random: Math.random(),
      preview: !!preview,
      previewData: previewData || null,
    },
  }
}

export default function ({ hasProps, preview, previewData, random }) {
  const router = useRouter()
  const [reloaded, setReloaded] = useState(false)

  return (
    <>
      <pre id="props-pre">
        {hasProps

      id="reload-props"
        onClick={async () => {
          await router.replace(router.asPath)
          setReloaded(true)
        }}
      >
        Reload static props
      </button>
      <p id="router">{JSON.stringify({ isPreview: router.isPrevi

? JSON.stringify(preview) + ' and ' + JSON.stringify(previewData)
          : 'Has No Props'}

{random}

      {reloaded ?
Reloaded
 : null}
      <button


extTestSetup, isNextDev, isNextStart } from 'e2e-utils'
;((isNextDev && process.env.TURBOPACK_BUILD) ||
  (isNextStart && process.env.TURBOPACK_DEV)
  ? describe.skip
  : describe)('Relay Compiler Transform - Single Project Config', () => {
  const { next } = nextTestSetup({
    files: __dirname,
    dependencies: {
      'relay-compiler': '13.0.2',
      'relay-runtime': '13.0.2',
      '@types/relay-runtime': 'latest',
    },
    // Relay expects the project root to contain relay.config.js. Run the compil

r install so generated artifacts match the schema before dev/start.
    installCommand: 'pnpm install && npx relay-compiler',
  })

  it('should resolve index page correctly', async () => {
    const html = await next.render('/')
    expect(html).toContain


import { fetchViaHTTP, renderViaHTTP } from 'next-test-utils'
import fs from 'fs-extra'
import { join } from 'path'

describe('og-api', () => {
  const { next, skipped } = nextTestSetup({
    files: new FileRef(join(__dirname, 'app')),
    skipDeployment: process.env.TEST_OUTPUT_STANDALONE === 'true',
  })

  if (skipped) return

  it('should respond from index', async () => {
    const html = await renderViaHTTP(next.url, '/')
    expect(html).toContain('hello world')
  })

  it('should work in pages/api',

BeGreaterThan(0)
  })

  it('should work in app route', async () => {
    const res = await fetchViaHTTP(next.url, '/og')
    expect(res.status).toBe(200)
    expect(res.headers.get('content-type')).toContain('image/png')
    const body = await res.blob()

 async () => {
    const res = await fetchViaHTTP(next.url, '/api/og')
    expect(res.status).toBe(200)
    expect(res.headers.get('content-type')).toContain('image/png')
    const body = await res.blob()
    expect(body.size).to


lementById('basic-image').naturalWidth`
      )
      expect(result).toBeGreaterThan(0)
    })

    expect(await getImageUrls(browser)).toContain(
      `${next.url}/_next/image?url=%2Ftest.jpg&w=828&q=75${dpl}`
    )
  })

  it('should preload priority images', async () => {
    const browser = await next.browser('/priority')

    await retry(async () => {
      const result = await browser.eval(
        `document.getElementById('basic-image').naturalWidth`
      )
      expect(result).toBeGreaterThan(0)

await link.getAttribute('imagesizes')
      entries.push({ imagesrcset, imagesizes })
    }

    expect(entries).toEqual([
      {
        imagesizes: '',
        imagesrcset: `/_next/image?url=%2Ftest.jpg&w=640&q=75${dpl} 1x, /_next/image?url=%2Ftest.jpg&

   })

    const links = await browser.elementsByCss('link[rel=preload][as=image]')
    const entries = []
    for (const link of links) {
      const imagesrcset = await link.getAttribute('imagesrcset')
      const imagesizes =


'
import { getDeploymentId } from 'next-test-utils'

describe('Image Component basePath + trailingSlash Tests', () => {
  const { next, skipped } = nextTestSetup({
    files: __dirname,
    disableAutoSkewProtection: true,
    // Image URL assertions construct expected URLs via
    // `getDeploymentId(next.testDir, ...)`, which reads the local
    // `.next/required-server-files.json`. In deploy mode that file lives on
    // Vercel's infrastructure (not on disk locally), so the constructed
    // expected

 string
  let assetDpl: string
  beforeAll(() => {
    dpl = getDeploymentId(next.testDir, isNextDev).getDeploymentIdQuery(true)
    assetDpl = getDeploymentId(next.testDir, isNextDev).getAssetQuery(true)
  })

  it('should correctly load image src from im

URL omits the `&dpl=...` query that Vercel injects at
    // runtime. The assertions are about local-build URL shape, not deploy
    // CDN URLs, so skip in deploy.
    skipDeployment: true,
  })
  if (skipped) return

  let dpl:


ublic/foo/test-rect.jpg'
import Image from 'next/image'

import testJPG from '../public/test.jpg'
import testPNG from '../public/test.png'
import testWEBP from '../public/test.webp'
import testAVIF from '../public/test.avif'
import testSVG from '../public/test.svg'
import testGIF from '../public/test.gif'
import testBMP from '../public/test.bmp'
import testICO from '../public/test.ico'
import widePNG from '../public/wide.png'

import TallImage from '../components/TallImage'

const shimmer = `data:image/svg+


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

type Props = { greeting: string }

export default function Index({ greeting }: Props) {
  return <p>{greeting}</p>
}

function createGraphQLFetcher(host: string | undefined): FetchFunction {
  return async function fetchGraphQL(p

 JSON.stringify({
        query: params.text,
        variables,
      }),
    })

    return await response.json()
  }
}

export const getServerSideProps: GetServerSideProps = async ({ req }) => {
  const environment = new Environment({
    store: new Sto

arams, variables) {
    const url = host ? `http://${host}/api/query` : `/api/query`

    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body:


=> 'hi'`

describe('Config Experimental Warning', () => {
  ;(isNextDev ? describe : describe.skip)('development mode', () => {
    describe('default config from function', () => {
      const { next } = nextTestSetup({
        files: {
          'pages/index.js': pageContent,
          'next.config.js': `
            module.exports = (phase, { defaultConfig }) => {
              return {
                ...defaultConfig,
                experimental: {
                  ...defaultConfig.experimental,

om function', async () => {
        const output = stripAnsi(next.cliOutput)
        expect(output).not.toMatch(experimentalHeader)
      })
    })

    describe('config from object', () => {
      const { next } = nextTestSetup({
        files: __dirname,

             // We enable this by default in CI
                  strictRouteTypes: false,
                }
              }
            }
          `,
        },
      })

      it('should not show warning with default config fr


from 'e2e-utils'

describe('Image Loader Config', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  describe('component', () => {
    it('should work with loaderFile config', async () => {
      const browser = await next.browser('/')
      expect(await browser.elementById('img1').getAttribute('src')).toBe(
        '/logo.png#w:828,q:50'
      )
      expect(await browser.elementById('img1').getAttribute('srcset')).toBe(
        '/logo.png#w:640,q:50 1x, /logo.png#w:828,q:50 2x'

     expect(await browser.elementById('img2').getAttribute('srcset')).toBe(
        '/logo.png?wid=256&qual=35 1x, /logo.png?wid=640&qual=35 2x'
      )
    })
  })

  describe('getImageProps', () => {
    it('should work with loaderFile config', async ()

 )
    })

    it('should work with loader prop', async () => {
      const browser = await next.browser('/')
      expect(await browser.elementById('img2').getAttribute('src')).toBe(
        '/logo.png?wid=640&qual=35'
      )


 { nextTestSetup } from 'e2e-utils'

describe('favicon-short-circuit', () => {
  const { next, isNextDev } = nextTestSetup({
    files: __dirname,
  })

  if (isNextDev) {
    it('should short circuit the favicon in development', async () => {
      const res = await next.fetch('/favicon.ico')

      // Expect we got the right status and headers.
      expect(res.status).toBe(404)
      expect(res.headers.get('content-type')).toBeNull()

      // Expect we got no body.
      const text = await res.text()

, async () => {
      const res = await next.fetch('/favicon.ico')

      // Expect we got the right status and headers.
      expect(res.status).toBe(404)
      expect(res.headers.get('content-type')).toBe('text/html; charset=utf-8')

      // Expect we g

    expect(text).toBeEmpty()

      // Expect we didn't compile the not found route.
      expect(next.cliOutput).not.toContain('compiling /not-found')
    })
  } else {
    it('should not short circuit the favicon in production'


React from 'react'
import Image from 'next/legacy/image'

const Page = () => {
  return (

Warn for this loader that doesnt use width

      <Image
        id="no-width"
        src="/test.png"
        width={100}
        height={100}
        loader={({ src }) => `${src}`}
      />
      <Image
        id="width-path"
        src="/test.jpg"
        width={100}
        height={100}
        loader={({ src, width }) => `${src}/${width}/file.jpg`}
      />
      <Image
        id="width

     width={100}
        height={100}
        loader={({ src, width }) =>
          `https://example.vercel.sh${src}?width=${width * 2}`
        }
      />
      <Image
        id="width-querystring-size"
        src="/test.tiff"
        width={100}

-querystring-w"
        src="/test.webp"
        width={100}
        height={100}
        loader={({ src, width }) => `${src}?w=${width / 2}`}
      />
      <Image
        id="width-querystring-width"
        src="/test.gif"


tTestSetup } from 'e2e-utils'

describe('next-phase', () => {
  const { next, isNextDev, skipped } = nextTestSetup({
    // This test is skipped when deployed because it asserts against runtime
    // logs that cannot be queried in a deployed environment.
    skipDeployment: true,
    files: {
      'app/layout.js': `export default function Layout({ children }) {
        return {children}
      }`,
      'app/page.js': `export default function Page() { return <p>{'app'}</p> }`,

   }
      `,
    },
  })

  if (skipped) return

  it('should render page with next phase correctly', async () => {
    await next.fetch('/')
    await next.fetch('/foo')

    const phases = {
      dev: 'phase-development-server',
      build: 'phase-pro

   'pages/foo.js': `export default function Page() { return <p>{'pages'}</p> }`,
      'next.config.js': `
        module.exports = (phase, { defaultConfig }) => {
          console.log(phase)
          return defaultConfig


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('Event with stale state - static route previously was dynamic', () => {
  const { next } = nextTestSetup({
    files: {
      pages: ne

/static')

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

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

    // 1st event is ignored

w FileRef(join(__dirname, 'app/pages')),
      // Don't use next.config.js to avoid getting i18n
    },
    dependencies: {},
  })

  test('Ignore event without query param', async () => {
    const browser = await next.browser('


eslint-disable jest/no-standalone-expect */

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

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

const isModeDeploy = process.env.NEXT_TEST_MODE === 'deploy'

describe('Middleware custom matchers basePath', () => {
  const { next } = nextTestSetup({
    files: new FileRef(join(__dirname, '../app')),
  })

  // FIXME
  // See https://linear.app/vercel/issue/EC-170/middle

nst res = await fetchViaHTTP(next.url, path)
      expect(res.status).toBe(200)
      expect(res.headers.get('x-from-middleware')).toBeDefined()
    }
  })

  it.each(['/hello', '/invalid/docs/hello'])(
    'should not match',
    async (path) => {
      c

ware-rewrite-of-nextjs-with-basepath-does-not-work-on-vercel
  itif(!isModeDeploy)('should match', async () => {
    for (const path of [
      '/docs/hello',
      `/docs/_next/data/${next.buildId}/hello.json`,
    ]) {
      co


rt { FileRef, nextTestSetup } from 'e2e-utils'
import cheerio from 'cheerio'
import type { Response } from 'node-fetch'

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

  describe.each([
    {
      title: 'Serverless Functions

 {
      title: 'getServerSideProps',
      path: '/ssr-page',
      toJson: async (res: Response) => {
        const $ = cheerio.load(await res.text())
        return JSON.parse($('#headers').text())
      },
    },
  ])('$title Backend', ({ path, toJson

',
      path: '/api/dump-headers-serverless',
      toJson: (res: Response) => res.json(),
    },
    {
      title: 'Edge Functions',
      path: '/api/dump-headers-edge',
      toJson: (res: Response) => res.json(),
    },


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

describe('Custom routes i18n support index rewrite', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  const locales = ['nl-NL', 'nl-BE', 'nl', 'fr-BE', 'fr', 'en']

  it('should rewrite index route correctly', async () => {
    for (const locale of locales) {
      const html = await next.render(`/${locale === 'en' ? '' : locale}`)
      const $ = cheerio.load(html)

orrectly', async () => {
    for (const locale of locales) {
      const browser = await next.browser(
        `${locale === 'en' ? '' : `/${locale}`}/hello`
      )

      expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
        p

    expect(JSON.parse($('#props').text())).toEqual({
        params: {
          slug: ['company', 'about-us'],
        },
        locale,
        hello: 'world',
      })
    }
  })

  it('should handle index rewrite on client c


tTestSetup } from 'e2e-utils'
import cheerio from 'cheerio'

const config = require('./next.config')

async function verify(res, locale) {
  expect(res.status).toBe(200)

  // Verify that we loaded the right page and the locale is correct.
  const html = await res.text()
  const $ = cheerio.load(html)
  expect($('#page').text()).toBe('index page')
  expect($('#router-locale').text()).toBe(locale)
}

describe('i18n-disallow-multiple-locales', () => {
  const { next, skipped } = nextTestSetup({
    files: __d

 redirect: 'manual' })

    await verify(res, config.i18n.defaultLocale)
  })

  it.each(config.i18n.locales)('/%s should 200', async (locale) => {
    const res = await next.fetch(`/${locale}`, { redirect: 'manual' })

    await verify(res, locale)
  })

irname,
    // TODO: re-enable after this behavior is corrected
    skipDeployment: true,
  })

  if (skipped) {
    return
  }

  it('should verify the default locale works', async () => {
    const res = await next.fetch('/', {


h'
import { nextTestSetup } from 'e2e-utils'
import { findPort, initNextServerScript, killApp } from 'next-test-utils'

describe('Trailing Slash Rewrite Proxying', () => {
  const { next, isNextDev, skipped } = nextTestSetup({
    files: __dirname,
    skipStart: true,
    // Spawns a custom proxy server in front of `next.start()`; deploy mode
    // doesn't run a local server.
    skipDeployment: true,
  })
  if (skipped) return

  let proxyServer: any

  beforeAll(async () => {
    const proxyPort = await

NextDev) {
      await next.build()
    }
    await next.start()
  })

  afterAll(async () => {
    await killApp(proxyServer)
  })

  it('should resolve index page correctly', async () => {
    const html = await next.render('/')
    expect(html).toContai

 findPort()
    proxyServer = await initNextServerScript(
      join(__dirname, 'server.js'),
      /ready on/i,
      { ...process.env, PORT: String(proxyPort) }
    )

    next.env.EXTERNAL_PORT = String(proxyPort)

    if (!is


 throw new Error(
          `did not find window.errorLoad, current url: ${await browser.url()}`
        )
      }

      if (isDev) break
    }
  }

  // Always resolve to a numeric port. We cannot use `next.fetch(...)` for
  // URLs that start with `//` or contain `\\` because `next.fetch` internally
  // runs them through `new URL(path, baseUrl)`, which normalizes them as
  // protocol-relative URLs (e.g. `//google.com` becomes `http://google.com/`).
  // `fetchViaHTTP` with a numeric port concatenates t

solvePort()) =>
    next.browser(url, { baseUrl })

  if (!isExport) {
    it('should normalize repeated slashes in redirects correctly', async () => {
      const res = await fetchViaHTTP(
        resolvePort(),
        '/redirect-forward-slashes',

he path onto the origin
  // verbatim, preserving the repeated-slash/backslash behavior under test.
  const resolvePort = () => (getPort ? getPort() : Number(next.appPort))
  const openBrowser = (url: string, baseUrl: number = re