Unverified Commit c9e238ed authored by Steven's avatar Steven Committed by GitHub

feat(next/image): support `new URL()` for `images.remotePatterns` (#77692)

Configuring `remotePatterns` can be a hassle because you have to define
each of the parts. And if you forget a part, its a wildcard meaning it
will match anything. This is usually not desirable since most remote
images don't allow query strings.

This PR adds support for using an array of `URL` objects when defining
`images.remotePatterns`.

```js
module.exports = {
  images: {
    remotePatterns: [
      new URL('https://res.cloudinary.com/my-account/**'),
      new URL('https://s3.my-account.*.amazonaws.com/**'),
    ],
  },
}
```

Note that wildcards must be explicit and anything missing is assumed to
no longer match.
parent 0959f7e5
...@@ -520,6 +520,16 @@ module.exports = { ...@@ -520,6 +520,16 @@ module.exports = {
To protect your application from malicious users, configuration is required in order to use external images. This ensures that only external images from your account can be served from the Next.js Image Optimization API. These external images can be configured with the `remotePatterns` property in your `next.config.js` file, as shown below: To protect your application from malicious users, configuration is required in order to use external images. This ensures that only external images from your account can be served from the Next.js Image Optimization API. These external images can be configured with the `remotePatterns` property in your `next.config.js` file, as shown below:
```js filename="next.config.js"
module.exports = {
images: {
remotePatterns: [new URL('https://example.com/account123/**')],
},
}
```
Versions of Next.js prior to 15.3.0 can configure `remotePatterns` using the object:
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
images: { images: {
...@@ -1106,6 +1116,7 @@ This `next/image` component uses browser native [lazy loading](https://caniuse.c ...@@ -1106,6 +1116,7 @@ This `next/image` component uses browser native [lazy loading](https://caniuse.c
| Version | Changes | | Version | Changes |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `v15.3.0` | `remotePatterns` added support for array of `URL` objects. |
| `v15.0.0` | `contentDispositionType` configuration default changed to `attachment`. | | `v15.0.0` | `contentDispositionType` configuration default changed to `attachment`. |
| `v14.2.23` | `qualities` configuration added. | | `v14.2.23` | `qualities` configuration added. |
| `v14.2.15` | `decoding` prop added and `localPatterns` configuration added. | | `v14.2.15` | `decoding` prop added and `localPatterns` configuration added. |
......
...@@ -10,6 +10,21 @@ One of your pages that leverages the `next/image` component, passed a `src` valu ...@@ -10,6 +10,21 @@ One of your pages that leverages the `next/image` component, passed a `src` valu
Add the protocol, hostname, port, and pathname to the `images.remotePatterns` config in `next.config.js`: Add the protocol, hostname, port, and pathname to the `images.remotePatterns` config in `next.config.js`:
```js filename="next.config.js"
module.exports = {
images: {
remotePatterns: [new URL('https://assets.example.com/account123/**')],
},
}
```
### Fixing older versions of Next.js
<details>
<summary>Using Next.js prior to 15.3.0?</summary>
Older versions of Next.js can configure `images.remotePatterns` using the object:
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
images: { images: {
...@@ -26,7 +41,7 @@ module.exports = { ...@@ -26,7 +41,7 @@ module.exports = {
} }
``` ```
### Fixing older versions of Next.js </details>
<details> <details>
<summary>Using Next.js prior to 12.3.0?</summary> <summary>Using Next.js prior to 12.3.0?</summary>
......
...@@ -668,5 +668,6 @@ ...@@ -668,5 +668,6 @@
"667": "receiveExpiredTags is deprecated, and not expected to be called.", "667": "receiveExpiredTags is deprecated, and not expected to be called.",
"668": "Internal Next.js error: Router action dispatched before initialization.", "668": "Internal Next.js error: Router action dispatched before initialization.",
"669": "Invariant: --turbopack is set but the build used Webpack", "669": "Invariant: --turbopack is set but the build used Webpack",
"670": "Invariant: --turbopack is not set but the build used Turbopack. Add --turbopack to \"next start\"." "670": "Invariant: --turbopack is not set but the build used Turbopack. Add --turbopack to \"next start\".",
"671": "Specified images.remotePatterns must have protocol \"http\" or \"https\" received \"%s\"."
} }
...@@ -582,7 +582,7 @@ async function writeImagesManifest( ...@@ -582,7 +582,7 @@ async function writeImagesManifest(
// By default, remotePatterns will allow no remote images ([]) // By default, remotePatterns will allow no remote images ([])
images.remotePatterns = (config?.images?.remotePatterns || []).map((p) => ({ images.remotePatterns = (config?.images?.remotePatterns || []).map((p) => ({
// Modifying the manifest should also modify matchRemotePattern() // Modifying the manifest should also modify matchRemotePattern()
protocol: p.protocol, protocol: p.protocol?.replace(/:$/, '') as 'http' | 'https' | undefined,
hostname: makeRe(p.hostname).source, hostname: makeRe(p.hostname).source,
port: p.port, port: p.port,
pathname: makeRe(p.pathname ?? '**', { dot: true }).source, pathname: makeRe(p.pathname ?? '**', { dot: true }).source,
......
...@@ -525,13 +525,16 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -525,13 +525,16 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(), .optional(),
remotePatterns: z remotePatterns: z
.array( .array(
z.strictObject({ z.union([
hostname: z.string(), z.instanceof(URL),
pathname: z.string().optional(), z.strictObject({
port: z.string().max(5).optional(), hostname: z.string(),
protocol: z.enum(['http', 'https']).optional(), pathname: z.string().optional(),
search: z.string().optional(), port: z.string().max(5).optional(),
}) protocol: z.enum(['http', 'https']).optional(),
search: z.string().optional(),
}),
])
) )
.max(50) .max(50)
.optional(), .optional(),
......
...@@ -364,6 +364,27 @@ function assignDefaults( ...@@ -364,6 +364,27 @@ function assignDefaults(
) )
} }
// We must convert URL to RemotePattern since URL has a colon in the protocol
// and also has additional properties we want to filter out. Also, new URL()
// accepts any protocol so we need manual validation here.
images.remotePatterns = images.remotePatterns.map(
({ protocol, hostname, port, pathname, search }) => {
const proto = protocol?.replace(/:$/, '')
if (!['http', 'https', undefined].includes(proto)) {
throw new Error(
`Specified images.remotePatterns must have protocol "http" or "https" received "${proto}".`
)
}
return {
protocol: proto as 'http' | 'https' | undefined,
hostname,
port,
pathname,
search,
}
}
)
// static images are automatically prefixed with assetPrefix // static images are automatically prefixed with assetPrefix
// so we need to ensure _next/image allows downloading from // so we need to ensure _next/image allows downloading from
// this resource // this resource
......
...@@ -113,7 +113,7 @@ export type ImageConfigComplete = { ...@@ -113,7 +113,7 @@ export type ImageConfigComplete = {
contentDispositionType: 'inline' | 'attachment' contentDispositionType: 'inline' | 'attachment'
/** @see [Remote Patterns](https://nextjs.org/docs/api-reference/next/image#remotepatterns) */ /** @see [Remote Patterns](https://nextjs.org/docs/api-reference/next/image#remotepatterns) */
remotePatterns: RemotePattern[] remotePatterns: Array<URL | RemotePattern>
/** @see [Remote Patterns](https://nextjs.org/docs/api-reference/next/image#localPatterns) */ /** @see [Remote Patterns](https://nextjs.org/docs/api-reference/next/image#localPatterns) */
localPatterns: LocalPattern[] | undefined localPatterns: LocalPattern[] | undefined
......
...@@ -2,10 +2,12 @@ import type { RemotePattern } from './image-config' ...@@ -2,10 +2,12 @@ import type { RemotePattern } from './image-config'
import { makeRe } from 'next/dist/compiled/picomatch' import { makeRe } from 'next/dist/compiled/picomatch'
// Modifying this function should also modify writeImagesManifest() // Modifying this function should also modify writeImagesManifest()
export function matchRemotePattern(pattern: RemotePattern, url: URL): boolean { export function matchRemotePattern(
pattern: RemotePattern | URL,
url: URL
): boolean {
if (pattern.protocol !== undefined) { if (pattern.protocol !== undefined) {
const actualProto = url.protocol.slice(0, -1) if (pattern.protocol.replace(/:$/, '') !== url.protocol.replace(/:$/, '')) {
if (pattern.protocol !== actualProto) {
return false return false
} }
} }
...@@ -41,7 +43,7 @@ export function matchRemotePattern(pattern: RemotePattern, url: URL): boolean { ...@@ -41,7 +43,7 @@ export function matchRemotePattern(pattern: RemotePattern, url: URL): boolean {
export function hasRemoteMatch( export function hasRemoteMatch(
domains: string[], domains: string[],
remotePatterns: RemotePattern[], remotePatterns: Array<RemotePattern | URL>,
url: URL url: URL
): boolean { ): boolean {
return ( return (
......
module.exports = {
images: {
remotePatterns: [{ hostname: 'image-optimization-test.vercel.app' }],
},
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
images: {
remotePatterns: [new URL('https://image-optimization-test.vercel.app/**')],
},
}
export default nextConfig
...@@ -567,6 +567,27 @@ describe('Image Optimizer', () => { ...@@ -567,6 +567,27 @@ describe('Image Optimizer', () => {
) )
}) })
it('should error when images.remotePatterns URL has invalid protocol', async () => {
await nextConfig.replace(
'{ /* replaceme */ }',
`{ images: { remotePatterns: [new URL('file://example.com/**')] } }`
)
let stderr = ''
app = await launchApp(appDir, await findPort(), {
onStderr(msg) {
stderr += msg || ''
},
})
await waitFor(1000)
await killApp(app).catch(() => {})
await nextConfig.restore()
expect(stderr).toContain(
`Specified images.remotePatterns must have protocol "http" or "https" received "file"`
)
})
it('should error when images.contentDispositionType is not valid', async () => { it('should error when images.contentDispositionType is not valid', async () => {
await nextConfig.replace( await nextConfig.replace(
'{ /* replaceme */ }', '{ /* replaceme */ }',
......
module.exports = { module.exports = {
images: { images: {
remotePatterns: [{ hostname: 'image-optimization-test.vercel.app' }], remotePatterns: [new URL('https://image-optimization-test.vercel.app/**')],
}, },
} }
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
import { import {
findPort, findPort,
getImagesManifest,
killApp, killApp,
launchApp, launchApp,
nextBuild, nextBuild,
...@@ -17,7 +18,7 @@ let appPort ...@@ -17,7 +18,7 @@ let appPort
let app let app
let browser let browser
function runTests() { function runTests(mode: 'server' | 'dev') {
it('should load static unicode image', async () => { it('should load static unicode image', async () => {
const src = await browser.elementById('static').getAttribute('src') const src = await browser.elementById('static').getAttribute('src')
expect(src).toMatch( expect(src).toMatch(
...@@ -65,6 +66,45 @@ function runTests() { ...@@ -65,6 +66,45 @@ function runTests() {
const res = await fetch(fullSrc) const res = await fetch(fullSrc)
expect(res.status).toBe(200) expect(res.status).toBe(200)
}) })
if (mode === 'server') {
it('should build correct images-manifest.json', async () => {
const manifest = getImagesManifest(appDir)
expect(manifest).toEqual({
version: 1,
images: {
contentDispositionType: 'attachment',
contentSecurityPolicy:
"script-src 'none'; frame-src 'none'; sandbox;",
dangerouslyAllowSVG: false,
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
disableStaticImages: false,
domains: [],
formats: ['image/webp'],
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
loader: 'default',
loaderFile: '',
remotePatterns: [
{
protocol: 'https',
hostname:
'^(?:^(?:image\\-optimization\\-test\\.vercel\\.app)$)$',
port: '',
pathname:
'^(?:\\/(?!\\.{1,2}(?:\\/|$))(?:(?:(?!(?:^|\\/)\\.{1,2}(?:\\/|$)).)*?))$',
search: '',
},
],
minimumCacheTTL: 60,
path: '/_next/image',
sizes: [
640, 750, 828, 1080, 1200, 1920, 2048, 3840, 16, 32, 48, 64, 96,
128, 256, 384,
],
unoptimized: false,
},
})
})
}
} }
describe('Image Component Unicode Image URL', () => { describe('Image Component Unicode Image URL', () => {
...@@ -82,7 +122,7 @@ describe('Image Component Unicode Image URL', () => { ...@@ -82,7 +122,7 @@ describe('Image Component Unicode Image URL', () => {
browser.close() browser.close()
} }
}) })
runTests() runTests('dev')
} }
) )
;(process.env.TURBOPACK_DEV ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
...@@ -100,7 +140,7 @@ describe('Image Component Unicode Image URL', () => { ...@@ -100,7 +140,7 @@ describe('Image Component Unicode Image URL', () => {
browser.close() browser.close()
} }
}) })
runTests() runTests('server')
} }
) )
}) })
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