Unverified Commit 8041a382 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

[Breaking] Require `images.localPatterns` for query in Image src (#84406)

This PR modifies Image behavior to require `images.localPatterns.search`
value when used with search queries in the `src` property:

```jsx
// Error
<Image src="/api/user?id=1" width="50" height="50" />
```

```ts
// next.config.ts

export default {
  images: {
    localPatterns: [
      {
        pathname: '/api/user',
        // Either set explicit query string or leave undefined to match all
        search: '?v=2',
      },
    ],
  },
}
```

It is to prevent malicious actors like Denial of Wallet (DoW) attacks
and strictly match the search queries for image optimization.

The deprecation warning was added at
https://github.com/vercel/next.js/pull/82627

---------
Co-authored-by: 's avatarSteven <steven@ceriously.com>
parent 5dcfec40
...@@ -528,6 +528,8 @@ module.exports = { ...@@ -528,6 +528,8 @@ module.exports = {
The example above will ensure the `src` property of `next/image` must start with `/assets/images/` and must not have a query string. Attempting to optimize any other path will respond with `400` Bad Request error. The example above will ensure the `src` property of `next/image` must start with `/assets/images/` and must not have a query string. Attempting to optimize any other path will respond with `400` Bad Request error.
> **Good to know**: Omitting the `search` property allows all search parameters which could allow malicious actors to optimize URLs you did not intend. Try using a specific value like `search: '?v=2'` to ensure an exact match.
#### `remotePatterns` #### `remotePatterns`
Use `remotePatterns` in your `next.config.js` file to allow images from specific external paths and block all others. This ensures that only external images from your account can be served. Use `remotePatterns` in your `next.config.js` file to allow images from specific external paths and block all others. This ensures that only external images from your account can be served.
......
...@@ -868,5 +868,6 @@ ...@@ -868,5 +868,6 @@
"867": "The %s \"%s\" must export a %s or a \\`default\\` function", "867": "The %s \"%s\" must export a %s or a \\`default\\` function",
"868": "No reference found for param: %s in reference: %s", "868": "No reference found for param: %s in reference: %s",
"869": "No reference found for segment: %s with reference: %s", "869": "No reference found for segment: %s with reference: %s",
"870": "refresh can only be called from within a Server Action. See more info here: https://nextjs.org/docs/app/api-reference/functions/refresh" "870": "refresh can only be called from within a Server Action. See more info here: https://nextjs.org/docs/app/api-reference/functions/refresh",
"871": "Image with src \"%s\" is using a query string which is not configured in images.localPatterns.\\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns"
} }
...@@ -546,6 +546,7 @@ export async function handler( ...@@ -546,6 +546,7 @@ export async function handler(
nextConfigOutput: nextConfig.output, nextConfigOutput: nextConfig.output,
crossOrigin: nextConfig.crossOrigin, crossOrigin: nextConfig.crossOrigin,
trailingSlash: nextConfig.trailingSlash, trailingSlash: nextConfig.trailingSlash,
images: nextConfig.images,
previewProps: prerenderManifest.preview, previewProps: prerenderManifest.preview,
deploymentId: nextConfig.deploymentId, deploymentId: nextConfig.deploymentId,
enableTainting: nextConfig.experimental.taint, enableTainting: nextConfig.experimental.taint,
......
...@@ -144,6 +144,7 @@ async function requestHandler( ...@@ -144,6 +144,7 @@ async function requestHandler(
nextConfigOutput: nextConfig.output, nextConfigOutput: nextConfig.output,
crossOrigin: nextConfig.crossOrigin, crossOrigin: nextConfig.crossOrigin,
trailingSlash: nextConfig.trailingSlash, trailingSlash: nextConfig.trailingSlash,
images: nextConfig.images,
previewProps: prerenderManifest.preview, previewProps: prerenderManifest.preview,
deploymentId: nextConfig.deploymentId, deploymentId: nextConfig.deploymentId,
enableTainting: nextConfig.experimental.taint, enableTainting: nextConfig.experimental.taint,
......
...@@ -364,10 +364,24 @@ export const Image = forwardRef<HTMLImageElement | null, ImageProps>( ...@@ -364,10 +364,24 @@ export const Image = forwardRef<HTMLImageElement | null, ImageProps>(
const configContext = useContext(ImageConfigContext) const configContext = useContext(ImageConfigContext)
const config = useMemo(() => { const config = useMemo(() => {
const c = configEnv || configContext || imageConfigDefault const c = configEnv || configContext || imageConfigDefault
const allSizes = [...c.deviceSizes, ...c.imageSizes].sort((a, b) => a - b) const allSizes = [...c.deviceSizes, ...c.imageSizes].sort((a, b) => a - b)
const deviceSizes = c.deviceSizes.sort((a, b) => a - b) const deviceSizes = c.deviceSizes.sort((a, b) => a - b)
const qualities = c.qualities?.sort((a, b) => a - b) const qualities = c.qualities?.sort((a, b) => a - b)
return { ...c, allSizes, deviceSizes, qualities } return {
...c,
allSizes,
deviceSizes,
qualities,
// During the SSR, configEnv (__NEXT_IMAGE_OPTS) does not include
// security sensitive configs like `localPatterns`, which is needed
// during the server render to ensure it's validated. Therefore use
// configContext, which holds the config from the server for validation.
localPatterns:
typeof window === 'undefined'
? configContext?.localPatterns
: c.localPatterns,
}
}, [configContext]) }, [configContext])
const { onLoad, onLoadingComplete } = props const { onLoad, onLoadingComplete } = props
...@@ -385,7 +399,6 @@ export const Image = forwardRef<HTMLImageElement | null, ImageProps>( ...@@ -385,7 +399,6 @@ export const Image = forwardRef<HTMLImageElement | null, ImageProps>(
const [blurComplete, setBlurComplete] = useState(false) const [blurComplete, setBlurComplete] = useState(false)
const [showAltText, setShowAltText] = useState(false) const [showAltText, setShowAltText] = useState(false)
const { props: imgAttributes, meta: imgMeta } = getImgProps(props, { const { props: imgAttributes, meta: imgMeta } = getImgProps(props, {
defaultLoader, defaultLoader,
imgConf: config, imgConf: config,
......
...@@ -120,6 +120,25 @@ function defaultLoader({ ...@@ -120,6 +120,25 @@ function defaultLoader({
width, width,
quality, quality,
}: ImageLoaderPropsWithConfig): string { }: ImageLoaderPropsWithConfig): string {
if (!config.dangerouslyAllowSVG && src.split('?', 1)[0].endsWith('.svg')) {
// Special case to make svg serve as-is to avoid proxying
// through the built-in Image Optimization API.
return src
}
if (
src.startsWith('/') &&
src.includes('?') &&
config.localPatterns?.length === 1 &&
config.localPatterns[0].pathname === '**' &&
config.localPatterns[0].search === ''
) {
throw new Error(
`Image with src "${src}" is using a query string which is not configured in images.localPatterns.` +
`\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns`
)
}
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
const missingValues = [] const missingValues = []
...@@ -192,12 +211,6 @@ function defaultLoader({ ...@@ -192,12 +211,6 @@ function defaultLoader({
const q = findClosestQuality(quality, config) const q = findClosestQuality(quality, config)
if (!config.dangerouslyAllowSVG && src.split('?', 1)[0].endsWith('.svg')) {
// Special case to make svg serve as-is to avoid proxying
// through the built-in Image Optimization API.
return src
}
return `${normalizePathTrailingSlash(config.path)}?url=${encodeURIComponent( return `${normalizePathTrailingSlash(config.path)}?url=${encodeURIComponent(
src src
)}&w=${width}&q=${q}` )}&w=${width}&q=${q}`
...@@ -645,7 +658,19 @@ export default function Image({ ...@@ -645,7 +658,19 @@ export default function Image({
const allSizes = [...c.deviceSizes, ...c.imageSizes].sort((a, b) => a - b) const allSizes = [...c.deviceSizes, ...c.imageSizes].sort((a, b) => a - b)
const deviceSizes = c.deviceSizes.sort((a, b) => a - b) const deviceSizes = c.deviceSizes.sort((a, b) => a - b)
const qualities = c.qualities?.sort((a, b) => a - b) const qualities = c.qualities?.sort((a, b) => a - b)
return { ...c, allSizes, deviceSizes, qualities } return {
...c,
allSizes,
deviceSizes,
qualities, // During the SSR, configEnv (__NEXT_IMAGE_OPTS) does not include
// security sensitive configs like `localPatterns`, which is needed
// during the server render to ensure it's validated. Therefore use
// configContext, which holds the config from the server for validation.
localPatterns:
typeof window === 'undefined'
? configContext?.localPatterns
: c.localPatterns,
}
}, [configContext]) }, [configContext])
let rest: Partial<ImageProps> = all let rest: Partial<ImageProps> = all
...@@ -865,19 +890,6 @@ export default function Image({ ...@@ -865,19 +890,6 @@ export default function Image({
) )
} }
if (
src.startsWith('/') &&
src.includes('?') &&
(!config?.localPatterns?.length ||
(config.localPatterns.length === 1 &&
config.localPatterns[0].pathname === '/_next/static/media/**'))
) {
warnOnce(
`Image with src "${src}" is using a query string which is not configured in images.localPatterns. This config will be required starting in Next.js 16.` +
`\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns`
)
}
if (!unoptimized && loader !== defaultImageLoader) { if (!unoptimized && loader !== defaultImageLoader) {
const urlStr = loader({ const urlStr = loader({
config, config,
......
...@@ -209,6 +209,8 @@ import { ...@@ -209,6 +209,8 @@ import {
import type { ExperimentalConfig } from '../config-shared' import type { ExperimentalConfig } from '../config-shared'
import type { Params } from '../request/params' import type { Params } from '../request/params'
import { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers' import { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'
import { ImageConfigContext } from '../../shared/lib/image-config-context.shared-runtime'
import { imageConfigDefault } from '../../shared/lib/image-config'
export type GetDynamicParamFromSegment = ( export type GetDynamicParamFromSegment = (
// [slug] / [[slug]] / [...slug] // [slug] / [[slug]] / [...slug]
...@@ -1359,12 +1361,14 @@ function App<T>({ ...@@ -1359,12 +1361,14 @@ function App<T>({
clientReferenceManifest, clientReferenceManifest,
ServerInsertedHTMLProvider, ServerInsertedHTMLProvider,
nonce, nonce,
images,
}: { }: {
reactServerStream: BinaryStreamOf<T> reactServerStream: BinaryStreamOf<T>
reactDebugStream: ReadableStream<Uint8Array> | undefined reactDebugStream: ReadableStream<Uint8Array> | undefined
preinitScripts: () => void preinitScripts: () => void
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']> clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }> ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }>
images: RenderOpts['images']
nonce?: string nonce?: string
}): JSX.Element { }): JSX.Element {
preinitScripts() preinitScripts()
...@@ -1404,9 +1408,11 @@ function App<T>({ ...@@ -1404,9 +1408,11 @@ function App<T>({
nonce, nonce,
}} }}
> >
<ImageConfigContext.Provider value={images ?? imageConfigDefault}>
<ServerInsertedHTMLProvider> <ServerInsertedHTMLProvider>
<AppRouter actionQueue={actionQueue} globalErrorState={response.G} /> <AppRouter actionQueue={actionQueue} globalErrorState={response.G} />
</ServerInsertedHTMLProvider> </ServerInsertedHTMLProvider>
</ImageConfigContext.Provider>
</HeadManagerContext.Provider> </HeadManagerContext.Provider>
) )
} }
...@@ -1421,6 +1427,7 @@ function ErrorApp<T>({ ...@@ -1421,6 +1427,7 @@ function ErrorApp<T>({
clientReferenceManifest, clientReferenceManifest,
ServerInsertedHTMLProvider, ServerInsertedHTMLProvider,
nonce, nonce,
images,
}: { }: {
reactServerStream: BinaryStreamOf<T> reactServerStream: BinaryStreamOf<T>
reactDebugStream: ReadableStream<Uint8Array> | undefined reactDebugStream: ReadableStream<Uint8Array> | undefined
...@@ -1428,6 +1435,7 @@ function ErrorApp<T>({ ...@@ -1428,6 +1435,7 @@ function ErrorApp<T>({
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']> clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }> ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }>
nonce?: string nonce?: string
images: RenderOpts['images']
}): JSX.Element { }): JSX.Element {
preinitScripts() preinitScripts()
const response = React.use( const response = React.use(
...@@ -1457,9 +1465,11 @@ function ErrorApp<T>({ ...@@ -1457,9 +1465,11 @@ function ErrorApp<T>({
const actionQueue = createMutableActionQueue(initialState, null) const actionQueue = createMutableActionQueue(initialState, null)
return ( return (
<ImageConfigContext.Provider value={images ?? imageConfigDefault}>
<ServerInsertedHTMLProvider> <ServerInsertedHTMLProvider>
<AppRouter actionQueue={actionQueue} globalErrorState={response.G} /> <AppRouter actionQueue={actionQueue} globalErrorState={response.G} />
</ServerInsertedHTMLProvider> </ServerInsertedHTMLProvider>
</ImageConfigContext.Provider>
) )
} }
...@@ -2422,6 +2432,7 @@ async function renderToStream( ...@@ -2422,6 +2432,7 @@ async function renderToStream(
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce} nonce={nonce}
images={ctx.renderOpts.images}
/>, />,
postponed, postponed,
{ onError: htmlRendererErrorHandler, nonce } { onError: htmlRendererErrorHandler, nonce }
...@@ -2467,6 +2478,7 @@ async function renderToStream( ...@@ -2467,6 +2478,7 @@ async function renderToStream(
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce} nonce={nonce}
images={ctx.renderOpts.images}
/>, />,
{ {
onError: htmlRendererErrorHandler, onError: htmlRendererErrorHandler,
...@@ -2627,6 +2639,7 @@ async function renderToStream( ...@@ -2627,6 +2639,7 @@ async function renderToStream(
preinitScripts={errorPreinitScripts} preinitScripts={errorPreinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
nonce={nonce} nonce={nonce}
images={ctx.renderOpts.images}
/> />
), ),
streamOptions: { streamOptions: {
...@@ -3010,6 +3023,7 @@ async function spawnDynamicValidationInDev( ...@@ -3010,6 +3023,7 @@ async function spawnDynamicValidationInDev(
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce} nonce={nonce}
images={ctx.renderOpts.images}
/>, />,
{ {
signal: initialClientReactController.signal, signal: initialClientReactController.signal,
...@@ -3239,6 +3253,7 @@ async function spawnDynamicValidationInDev( ...@@ -3239,6 +3253,7 @@ async function spawnDynamicValidationInDev(
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce} nonce={nonce}
images={ctx.renderOpts.images}
/>, />,
{ {
signal: finalClientReactController.signal, signal: finalClientReactController.signal,
...@@ -3753,6 +3768,7 @@ async function prerenderToStream( ...@@ -3753,6 +3768,7 @@ async function prerenderToStream(
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce} nonce={nonce}
images={ctx.renderOpts.images}
/>, />,
{ {
signal: initialClientReactController.signal, signal: initialClientReactController.signal,
...@@ -3987,6 +4003,7 @@ async function prerenderToStream( ...@@ -3987,6 +4003,7 @@ async function prerenderToStream(
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce} nonce={nonce}
images={ctx.renderOpts.images}
/>, />,
{ {
signal: finalClientReactController.signal, signal: finalClientReactController.signal,
...@@ -4151,6 +4168,7 @@ async function prerenderToStream( ...@@ -4151,6 +4168,7 @@ async function prerenderToStream(
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce} nonce={nonce}
images={ctx.renderOpts.images}
/>, />,
JSON.parse(JSON.stringify(postponed)), JSON.parse(JSON.stringify(postponed)),
{ {
...@@ -4258,6 +4276,7 @@ async function prerenderToStream( ...@@ -4258,6 +4276,7 @@ async function prerenderToStream(
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce} nonce={nonce}
images={ctx.renderOpts.images}
/>, />,
{ {
onError: htmlRendererErrorHandler, onError: htmlRendererErrorHandler,
...@@ -4399,6 +4418,7 @@ async function prerenderToStream( ...@@ -4399,6 +4418,7 @@ async function prerenderToStream(
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce} nonce={nonce}
images={ctx.renderOpts.images}
/>, />,
JSON.parse(JSON.stringify(postponed)), JSON.parse(JSON.stringify(postponed)),
{ {
...@@ -4483,6 +4503,7 @@ async function prerenderToStream( ...@@ -4483,6 +4503,7 @@ async function prerenderToStream(
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce} nonce={nonce}
images={ctx.renderOpts.images}
/>, />,
{ {
onError: htmlRendererErrorHandler, onError: htmlRendererErrorHandler,
...@@ -4657,6 +4678,7 @@ async function prerenderToStream( ...@@ -4657,6 +4678,7 @@ async function prerenderToStream(
preinitScripts={errorPreinitScripts} preinitScripts={errorPreinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
nonce={nonce} nonce={nonce}
images={ctx.renderOpts.images}
/> />
), ),
streamOptions: { streamOptions: {
......
...@@ -9,6 +9,7 @@ import type { NextFontManifest } from '../../build/webpack/plugins/next-font-man ...@@ -9,6 +9,7 @@ import type { NextFontManifest } from '../../build/webpack/plugins/next-font-man
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { AppPageModule } from '../route-modules/app-page/module' import type { AppPageModule } from '../route-modules/app-page/module'
import type { DeepReadonly } from '../../shared/lib/deep-readonly' import type { DeepReadonly } from '../../shared/lib/deep-readonly'
import type { ImageConfigComplete } from '../../shared/lib/image-config'
import type { __ApiPreviewProps } from '../api-utils' import type { __ApiPreviewProps } from '../api-utils'
import s from 'next/dist/compiled/superstruct' import s from 'next/dist/compiled/superstruct'
...@@ -77,6 +78,7 @@ export interface RenderOptsPartial { ...@@ -77,6 +78,7 @@ export interface RenderOptsPartial {
dev?: boolean dev?: boolean
basePath: string basePath: string
trailingSlash: boolean trailingSlash: boolean
images: ImageConfigComplete
clientReferenceManifest?: DeepReadonly<ClientReferenceManifest> clientReferenceManifest?: DeepReadonly<ClientReferenceManifest>
supportsDynamicResponse: boolean supportsDynamicResponse: boolean
runtime?: ServerRuntime runtime?: ServerRuntime
......
...@@ -477,6 +477,14 @@ function assignDefaultsAndValidate( ...@@ -477,6 +477,14 @@ function assignDefaultsAndValidate(
search: '', search: '',
}) })
} }
} else {
// All paths are not allowed for a search query by default.
images.localPatterns = [
{
pathname: '**',
search: '',
},
]
} }
if (images.remotePatterns) { if (images.remotePatterns) {
......
...@@ -560,18 +560,6 @@ export function getImgProps( ...@@ -560,18 +560,6 @@ export function getImgProps(
`\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-qualities` `\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-qualities`
) )
} }
if (
src.startsWith('/') &&
src.includes('?') &&
(!config?.localPatterns?.length ||
(config.localPatterns.length === 1 &&
config.localPatterns[0].pathname === '/_next/static/media/**'))
) {
warnOnce(
`Image with src "${src}" is using a query string which is not configured in images.localPatterns. This config will be required starting in Next.js 16.` +
`\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns`
)
}
if (placeholder === 'blur' && !blurDataURL) { if (placeholder === 'blur' && !blurDataURL) {
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match next-image-loader const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match next-image-loader
......
...@@ -7,6 +7,19 @@ function defaultLoader({ ...@@ -7,6 +7,19 @@ function defaultLoader({
width, width,
quality, quality,
}: ImageLoaderPropsWithConfig): string { }: ImageLoaderPropsWithConfig): string {
if (
src.startsWith('/') &&
src.includes('?') &&
config.localPatterns?.length === 1 &&
config.localPatterns[0].pathname === '**' &&
config.localPatterns[0].search === ''
) {
throw new Error(
`Image with src "${src}" is using a query string which is not configured in images.localPatterns.` +
`\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns`
)
}
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
const missingValues = [] const missingValues = []
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import Image from 'next/legacy/image'
export default function Page() {
// src with query without localPatterns will throw an error
return <Image src="/test.png?v=1" alt="test" width={100} height={100} />
}
import { nextTestSetup } from 'e2e-utils'
describe('next-image-legacy-src-with-query-without-local-patterns', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
it('should throw error for relative image with query without localPatterns for legacy Image', async () => {
if (isNextDev) {
await next.start()
await next.browser('/')
expect(next.cliOutput).toContain(
'Image with src "/test.png?v=1" is using a query string which is not configured in images.localPatterns.\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns'
)
} else {
const { cliOutput } = await next.build()
expect(cliOutput).toContain(
'Image with src "/test.png?v=1" is using a query string which is not configured in images.localPatterns.\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns'
)
}
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import Image from 'next/image'
export default function Page() {
// src with query without localPatterns will throw an error
return <Image src="/test.png?v=1" alt="test" width={100} height={100} />
}
import { nextTestSetup } from 'e2e-utils'
describe('next-image-src-with-query-without-local-patterns', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
it('should throw error for relative image with query without localPatterns', async () => {
if (isNextDev) {
await next.start()
await next.browser('/')
expect(next.cliOutput).toContain(
'Image with src "/test.png?v=1" is using a query string which is not configured in images.localPatterns.\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns'
)
} else {
const { cliOutput } = await next.build()
expect(cliOutput).toContain(
'Image with src "/test.png?v=1" is using a query string which is not configured in images.localPatterns.\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns'
)
}
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
describe('next-image-legacy-src-with-query-without-local-patterns', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
it('should throw error for relative image with query without localPatterns for legacy Image', async () => {
if (isNextDev) {
await next.start()
await next.browser('/')
expect(next.cliOutput).toContain(
'Image with src "/test.png?v=1" is using a query string which is not configured in images.localPatterns.\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns'
)
} else {
const { cliOutput } = await next.build()
expect(cliOutput).toContain(
'Image with src "/test.png?v=1" is using a query string which is not configured in images.localPatterns.\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns'
)
}
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import Image from 'next/legacy/image'
export default function Page() {
// src with query without localPatterns will throw an error
return <Image src="/test.png?v=1" alt="test" width={100} height={100} />
}
import { nextTestSetup } from 'e2e-utils'
describe('next-image-src-with-query-without-local-patterns', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
it('should throw error for relative image with query without localPatterns', async () => {
if (isNextDev) {
await next.start()
await next.browser('/')
expect(next.cliOutput).toContain(
'Image with src "/test.png?v=1" is using a query string which is not configured in images.localPatterns.\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns'
)
} else {
const { cliOutput } = await next.build()
expect(cliOutput).toContain(
'Image with src "/test.png?v=1" is using a query string which is not configured in images.localPatterns.\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns'
)
}
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import Image from 'next/image'
export default function Page() {
// src with query without localPatterns will throw an error
return <Image src="/test.png?v=1" alt="test" width={100} height={100} />
}
...@@ -101,7 +101,13 @@ function runTests(mode: 'dev' | 'server') { ...@@ -101,7 +101,13 @@ function runTests(mode: 'dev' | 'server') {
loader: 'default', loader: 'default',
loaderFile: '', loaderFile: '',
remotePatterns: [], remotePatterns: [],
localPatterns: undefined, localPatterns: [
{
pathname:
'^(?:(?!(?:^|\\/)\\.{1,2}(?:\\/|$))(?:(?:(?!(?:^|\\/)\\.{1,2}(?:\\/|$)).)*?)\\/?)$',
search: '',
},
],
minimumCacheTTL: 14400, minimumCacheTTL: 14400,
path: '/_next/image', path: '/_next/image',
qualities: [42, 69, 88], qualities: [42, 69, 88],
......
...@@ -1787,7 +1787,13 @@ function runTests(mode: 'dev' | 'server') { ...@@ -1787,7 +1787,13 @@ function runTests(mode: 'dev' | 'server') {
loader: 'default', loader: 'default',
loaderFile: '', loaderFile: '',
remotePatterns: [], remotePatterns: [],
localPatterns: undefined, localPatterns: [
{
pathname:
'^(?:(?!(?:^|\\/)\\.{1,2}(?:\\/|$))(?:(?:(?!(?:^|\\/)\\.{1,2}(?:\\/|$)).)*?)\\/?)$',
search: '',
},
],
minimumCacheTTL: 14400, minimumCacheTTL: 14400,
path: '/_next/image', path: '/_next/image',
qualities: [75], qualities: [75],
......
...@@ -94,6 +94,13 @@ function runTests(mode: 'server' | 'dev') { ...@@ -94,6 +94,13 @@ function runTests(mode: 'server' | 'dev') {
search: '', search: '',
}, },
], ],
localPatterns: [
{
pathname:
'^(?:(?!(?:^|\\/)\\.{1,2}(?:\\/|$))(?:(?:(?!(?:^|\\/)\\.{1,2}(?:\\/|$)).)*?)\\/?)$',
search: '',
},
],
minimumCacheTTL: 14400, minimumCacheTTL: 14400,
path: '/_next/image', path: '/_next/image',
qualities: [75], qualities: [75],
......
...@@ -109,7 +109,13 @@ function runTests(url: string, mode: 'dev' | 'server') { ...@@ -109,7 +109,13 @@ function runTests(url: string, mode: 'dev' | 'server') {
loader: 'default', loader: 'default',
loaderFile: '', loaderFile: '',
remotePatterns: [], remotePatterns: [],
localPatterns: undefined, localPatterns: [
{
pathname:
'^(?:(?!(?:^|\\/)\\.{1,2}(?:\\/|$))(?:(?:(?!(?:^|\\/)\\.{1,2}(?:\\/|$)).)*?)\\/?)$',
search: '',
},
],
minimumCacheTTL: 14400, minimumCacheTTL: 14400,
path: '/_next/image', path: '/_next/image',
qualities: [75], qualities: [75],
......
...@@ -574,26 +574,6 @@ describe('getImageProps()', () => { ...@@ -574,26 +574,6 @@ describe('getImageProps()', () => {
['src', '/test.svg'], ['src', '/test.svg'],
]) ])
}) })
it('should auto unoptimized for relative svg with query', async () => {
const { props } = getImageProps({
alt: 'a nice desc',
src: '/test.svg?v=1',
width: 100,
height: 200,
})
expect(warningMessages).toStrictEqual([
'Image with src "/test.svg?v=1" is using a query string which is not configured in images.localPatterns. This config will be required starting in Next.js 16.\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns',
])
expect(Object.entries(props)).toStrictEqual([
['alt', 'a nice desc'],
['loading', 'lazy'],
['width', 100],
['height', 200],
['decoding', 'async'],
['style', { color: 'transparent' }],
['src', '/test.svg?v=1'],
])
})
it('should auto unoptimized for absolute svg', async () => { it('should auto unoptimized for absolute svg', async () => {
const { props } = getImageProps({ const { props } = getImageProps({
alt: 'a nice desc', alt: 'a nice desc',
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment