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

chore(next/image)!: mark `domains` as deprecated in favor `remotePatterns` (#57062)

We already had `domains` as "not recommended" but this PR marks it as "deprecated" and prints a warning if its detected.

I also updated all examples to switch from `domains` to `remotePatterns`.
parent 194e94ed
...@@ -447,7 +447,7 @@ The `**` syntax does not work in the middle of the pattern. ...@@ -447,7 +447,7 @@ The `**` syntax does not work in the middle of the pattern.
### `domains` ### `domains`
> **Warning**: Deprecated since Next.js 14. We recommend configuring strict [`remotePatterns`](#remotepatterns) instead of `domains` in order to protect your application from malicious users. Only use `domains` if you own all the content served from the domain. > **Warning**: Deprecated since Next.js 14 in favor of strict [`remotePatterns`](#remotepatterns) in order to protect your application from malicious users. Only use `domains` if you own all the content served from the domain.
Similar to [`remotePatterns`](#remotepatterns), the `domains` configuration can be used to provide a list of allowed hostnames for external images. Similar to [`remotePatterns`](#remotepatterns), the `domains` configuration can be used to provide a list of allowed hostnames for external images.
...@@ -805,6 +805,7 @@ This `next/image` component uses browser native [lazy loading](https://caniuse.c ...@@ -805,6 +805,7 @@ This `next/image` component uses browser native [lazy loading](https://caniuse.c
| Version | Changes | | Version | Changes |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `v14.0.0` | `onLoadingComplete` prop and `domains` config deprecated. |
| `v13.4.14` | `placeholder` prop support for `data:/image...` | | `v13.4.14` | `placeholder` prop support for `data:/image...` |
| `v13.2.0` | `contentDispositionType` configuration added. | | `v13.2.0` | `contentDispositionType` configuration added. |
| `v13.0.6` | `ref` prop added. | | `v13.0.6` | `ref` prop added. |
......
...@@ -396,7 +396,7 @@ The `**` syntax does not work in the middle of the pattern. ...@@ -396,7 +396,7 @@ The `**` syntax does not work in the middle of the pattern.
### Domains ### Domains
> **Warning**: We recommend configuring strict [`remotePatterns`](#remote-patterns) instead of `domains` in order to protect your application from malicious users. Only use `domains` if you own all the content served from the domain. > **Warning**: Deprecated since Next.js 14 in favor of strict [`remotePatterns`](#remote-patterns) in order to protect your application from malicious users. Only use `domains` if you own all the content served from the domain.
Similar to [`remotePatterns`](#remote-patterns), the `domains` configuration can be used to provide a list of allowed hostnames for external images. Similar to [`remotePatterns`](#remote-patterns), the `domains` configuration can be used to provide a list of allowed hostnames for external images.
......
...@@ -17,7 +17,7 @@ module.exports = { ...@@ -17,7 +17,7 @@ module.exports = {
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840], deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
// limit of 25 imageSizes values // limit of 25 imageSizes values
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384], imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
// limit of 50 domains values // limit of 50 domains values (deprecated)
domains: [], domains: [],
// path prefix for Image Optimization API, useful with `loader` // path prefix for Image Optimization API, useful with `loader`
path: '/_next/image', path: '/_next/image',
......
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
module.exports = { module.exports = {
images: { images: {
domains: ['cdn.builder.io'], remotePatterns: [
{
protocol: 'https',
hostname: 'cdn.builder.io',
port: '',
pathname: '/my-account/**',
},
],
}, },
async headers() { async headers() {
return [ return [
......
...@@ -31,6 +31,13 @@ module.exports = { ...@@ -31,6 +31,13 @@ module.exports = {
})) }))
}, },
images: { images: {
domains: ['cdn.buttercms.com'], remotePatterns: [
{
protocol: 'https',
hostname: 'cdn.buttercms.com',
port: '',
pathname: '/my-account/**',
},
],
}, },
} }
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
module.exports = { module.exports = {
images: { images: {
domains: ['imgix.cosmicjs.com'], remotePatterns: [
{
protocol: 'https',
hostname: 'imgix.cosmicjs.com',
port: '',
pathname: '/my-account/**',
},
],
}, },
} }
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
module.exports = { module.exports = {
images: { images: {
domains: ['www.datocms-assets.com'], remotePatterns: [
{
protocol: 'https',
hostname: 'www.datocms-assets.com',
port: '',
pathname: '/my-account/**',
},
],
}, },
} }
NEXT_PUBLIC_DRUPAL_BASE_URL=http://localhost:8080 NEXT_PUBLIC_DRUPAL_BASE_URL=http://localhost:8080
NEXT_IMAGE_DOMAIN=localhost
DRUPAL_SITE_ID= DRUPAL_SITE_ID=
DRUPAL_CLIENT_ID= DRUPAL_CLIENT_ID=
DRUPAL_CLIENT_SECRET= DRUPAL_CLIENT_SECRET=
......
/** @type {import('next').NextConfig} */
module.exports = {
images: {
domains: [process.env.NEXT_IMAGE_DOMAIN],
},
}
module.exports = { module.exports = {
images: { images: {
domains: ['res.cloudinary.com'], remotePatterns: [
{
protocol: 'https',
hostname: 'res.cloudinary.com',
port: '',
pathname: '/my-account/**',
},
],
}, },
} }
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
module.exports = { module.exports = {
images: { images: {
domains: ['static.ghost.org'], remotePatterns: [
{
protocol: 'https',
hostname: 'static.ghost.org',
port: '',
pathname: '/my-account/**',
},
],
}, },
} }
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
module.exports = { module.exports = {
images: { images: {
domains: ['media.graphcms.com'], remotePatterns: [
{
protocol: 'https',
hostname: 'media.graphcms.com',
port: '',
pathname: '/my-account/**',
},
],
}, },
} }
...@@ -6,7 +6,7 @@ PAYLOAD_PUBLIC_CMS_URL=http://localhost:3000 ...@@ -6,7 +6,7 @@ PAYLOAD_PUBLIC_CMS_URL=http://localhost:3000
S3_ACCESS_KEY_ID= S3_ACCESS_KEY_ID=
S3_SECRET_ACCESS_KEY= S3_SECRET_ACCESS_KEY=
S3_REGION= S3_REGION=
NEXT_PUBLIC_S3_ENDPOINT= NEXT_PUBLIC_S3_HOSTNAME=
NEXT_PUBLIC_S3_BUCKET= NEXT_PUBLIC_S3_BUCKET=
PAYLOAD_PRIVATE_REGENERATION_SECRET= PAYLOAD_PRIVATE_REGENERATION_SECRET=
NEXT_PRIVATE_REGENERATION_SECRET= NEXT_PRIVATE_REGENERATION_SECRET=
\ No newline at end of file
...@@ -39,7 +39,7 @@ export const Image: React.FC<Props> = (props) => { ...@@ -39,7 +39,7 @@ export const Image: React.FC<Props> = (props) => {
let filename = fullFilename let filename = fullFilename
src = `${process.env.NEXT_PUBLIC_S3_ENDPOINT}/${process.env.NEXT_PUBLIC_S3_BUCKET}/${filename}` src = `https://${process.env.NEXT_PUBLIC_S3_HOSTNAME}/${process.env.NEXT_PUBLIC_S3_BUCKET}/${filename}`
} }
// NOTE: this is used by the browser to determine which image to download at different screen sizes // NOTE: this is used by the browser to determine which image to download at different screen sizes
......
...@@ -7,11 +7,19 @@ const nextConfig = withPayload( ...@@ -7,11 +7,19 @@ const nextConfig = withPayload(
reactStrictMode: true, reactStrictMode: true,
rewrites: [{ source: '/admin/(.*)', destination: '/admin/index.html' }], rewrites: [{ source: '/admin/(.*)', destination: '/admin/index.html' }],
images: { images: {
domains: [ remotePatterns: [
'localhost', {
'nextjs-vercel.payloadcms.com', protocol: 'https',
process.env.NEXT_PUBLIC_APP_URL ? process.env.NEXT_PUBLIC_APP_URL : '', hostname: 'nextjs-vercel.payloadcms.com',
`${process.env.NEXT_PUBLIC_S3_ENDPOINT}`.replace('https://', ''), port: '',
pathname: '/my-account/**',
},
{
protocol: 'https',
hostname: process.env.NEXT_PUBLIC_S3_HOSTNAME,
port: '',
pathname: `/${process.env.NEXT_PUBLIC_S3_BUCKET}/**`,
},
], ],
}, },
}, },
......
...@@ -9,7 +9,7 @@ import { Media } from './collections/Media' ...@@ -9,7 +9,7 @@ import { Media } from './collections/Media'
const adapter = s3Adapter({ const adapter = s3Adapter({
config: { config: {
endpoint: process.env.NEXT_PUBLIC_S3_ENDPOINT, endpoint: `https://${process.env.NEXT_PUBLIC_S3_HOSTNAME}`,
region: process.env.S3_REGION, region: process.env.S3_REGION,
forcePathStyle: true, forcePathStyle: true,
credentials: { credentials: {
......
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
module.exports = { module.exports = {
images: { images: {
domains: [ remotePatterns: [
'b-cdn.net', {
'prepr-example-content-demo-patterns.stream.prepr.io', protocol: 'https',
'demo-site-patterns.stream.prepr.io', hostname: 'b-cdn.net',
port: '',
pathname: '/my-account/**',
},
{
protocol: 'https',
hostname: '*.stream.prepr.io',
port: '',
pathname: '/my-account/**',
},
], ],
}, },
} }
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
module.exports = { module.exports = {
images: { images: {
domains: ['images.prismic.io'], remotePatterns: [
{
protocol: 'https',
hostname: 'images.prismic.io',
port: '',
pathname: '/my-account/**',
},
],
}, },
} }
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
module.exports = { module.exports = {
images: { images: {
domains: ['media.umbraco.io'], remotePatterns: [
{
protocol: 'https',
hostname: 'media.umbraco.io',
port: '',
pathname: '/my-account/**',
},
],
}, },
} }
module.exports = { module.exports = {
images: { images: {
domains: ['d16nhgqznszc7v.cloudfront.net'], remotePatterns: [
{
protocol: 'https',
hostname: 'myaccount.cloudfront.net',
port: '',
},
],
}, },
} }
if (!process.env.WORDPRESS_API_URL) { if (!URL.canParse(process.env.WORDPRESS_API_URL)) {
throw new Error(` throw new Error(`
Please provide a valid WordPress instance URL. Please provide a valid WordPress instance URL.
Add to your environment variables WORDPRESS_API_URL. Add to your environment variables WORDPRESS_API_URL.
`) `)
} }
const { protocol, hostname, port, pathname } = new URL(
process.env.WORDPRESS_API_URL
)
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
module.exports = { module.exports = {
images: { images: {
domains: [ remotePatterns: [
process.env.WORDPRESS_API_URL.match(/(?!(w+)\.)\w*(?:\w+\.)+\w+/)[0], // Valid WP Image domain. {
'0.gravatar.com', protocol: protocol.slice(0, -1),
'1.gravatar.com', hostname,
'2.gravatar.com', port,
'secure.gravatar.com', pathname: `${pathname}/**`,
},
], ],
}, },
} }
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
reactStrictMode: true,
images: { images: {
domains: ['raw.githubusercontent.com'], remotePatterns: [
{
protocol: 'https',
hostname: 'raw.githubusercontent.com',
port: '',
pathname: '/my-account/**',
},
],
}, },
} }
......
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
reactStrictMode: false,
compiler: { compiler: {
styledComponents: true, styledComponents: true,
}, },
images: { images: {
domains: ['vod.api.video'], remotePatterns: [
{
protocol: 'https',
hostname: 'vod.api.video',
port: '',
pathname: '/my-account/**',
},
],
}, },
} }
......
module.exports = { module.exports = {
images: { images: {
formats: ['image/avif', 'image/webp'], formats: ['image/avif', 'image/webp'],
domains: ['res.cloudinary.com'], remotePatterns: [
{
protocol: 'https',
hostname: 'res.cloudinary.com',
port: '',
pathname: '/my-account/**',
},
],
}, },
} }
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
module.exports = { module.exports = {
reactStrictMode: true,
images: { images: {
domains: ['avatars.githubusercontent.com'], remotePatterns: [
{
protocol: 'https',
hostname: 'avatars.githubusercontent.com',
port: '',
pathname: '/my-account/**',
},
],
}, },
} }
module.exports = { module.exports = {
reactStrictMode: true, reactStrictMode: true,
images: { images: {
domains: ['zzte-003.dx.commercecloud.salesforce.com'], remotePatterns: [
{
protocol: 'https',
hostname: 'myaccount.dx.commercecloud.salesforce.com',
port: '',
},
],
}, },
} }
...@@ -3,7 +3,6 @@ import { promises } from 'fs' ...@@ -3,7 +3,6 @@ import { promises } from 'fs'
import { cpus } from 'os' import { cpus } from 'os'
import type { IncomingMessage, ServerResponse } from 'http' import type { IncomingMessage, ServerResponse } from 'http'
import { mediaType } from 'next/dist/compiled/@hapi/accept' import { mediaType } from 'next/dist/compiled/@hapi/accept'
import { bold, yellow } from '../lib/picocolors'
import contentDisposition from 'next/dist/compiled/content-disposition' import contentDisposition from 'next/dist/compiled/content-disposition'
import { getOrientation, Orientation } from 'next/dist/compiled/get-orientation' import { getOrientation, Orientation } from 'next/dist/compiled/get-orientation'
import imageSizeOf from 'next/dist/compiled/image-size' import imageSizeOf from 'next/dist/compiled/image-size'
...@@ -28,6 +27,7 @@ import type { ...@@ -28,6 +27,7 @@ import type {
} from './response-cache' } from './response-cache'
import { sendEtagResponse } from './send-payload' import { sendEtagResponse } from './send-payload'
import { getContentType, getExtension } from './serve-static' import { getContentType, getExtension } from './serve-static'
import * as Log from '../build/output/log'
type XCacheHeader = 'MISS' | 'HIT' | 'STALE' type XCacheHeader = 'MISS' | 'HIT' | 'STALE'
...@@ -169,6 +169,12 @@ export class ImageOptimizerCache { ...@@ -169,6 +169,12 @@ export class ImageOptimizerCache {
const { url, w, q } = query const { url, w, q } = query
let href: string let href: string
if (domains.length > 0) {
Log.warnOnce(
'The "images.domains" configuration is deprecated. Please use "images.remotePatterns" configuration instead.'
)
}
if (!url) { if (!url) {
return { errorMessage: '"url" parameter is required' } return { errorMessage: '"url" parameter is required' }
} else if (Array.isArray(url)) { } else if (Array.isArray(url)) {
...@@ -348,7 +354,7 @@ export class ImageOptimizerCache { ...@@ -348,7 +354,7 @@ export class ImageOptimizerCache {
value.etag value.etag
) )
} catch (err) { } catch (err) {
console.error(`Failed to write image to cache ${cacheKey}`, err) Log.error(`Failed to write image to cache ${cacheKey}`, err)
} }
} }
} }
...@@ -438,9 +444,8 @@ export async function optimizeImage({ ...@@ -438,9 +444,8 @@ export async function optimizeImage({
chromaSubsampling: '4:2:0', // same as webp chromaSubsampling: '4:2:0', // same as webp
}) })
} else { } else {
console.warn( Log.warnOnce(
yellow(bold('Warning: ')) + `Your installed version of the 'sharp' package does not support AVIF images. Run 'npm i sharp@latest' to upgrade to the latest version.\n` +
`Your installed version of the 'sharp' package does not support AVIF images. Run 'npm i sharp@latest' to upgrade to the latest version.\n` +
'Read more: https://nextjs.org/docs/messages/sharp-version-avif' 'Read more: https://nextjs.org/docs/messages/sharp-version-avif'
) )
transformer.webp({ quality }) transformer.webp({ quality })
...@@ -457,16 +462,15 @@ export async function optimizeImage({ ...@@ -457,16 +462,15 @@ export async function optimizeImage({
// End sharp transformation logic // End sharp transformation logic
} else { } else {
if (showSharpMissingWarning && nextConfigOutput === 'standalone') { if (showSharpMissingWarning && nextConfigOutput === 'standalone') {
console.error( Log.error(
`Error: 'sharp' is required to be installed in standalone mode for the image optimization to function correctly. Read more at: https://nextjs.org/docs/messages/sharp-missing-in-production` `Error: 'sharp' is required to be installed in standalone mode for the image optimization to function correctly. Read more at: https://nextjs.org/docs/messages/sharp-missing-in-production`
) )
throw new ImageError(500, 'Internal Server Error') throw new ImageError(500, 'Internal Server Error')
} }
// Show sharp warning in production once // Show sharp warning in production once
if (showSharpMissingWarning) { if (showSharpMissingWarning) {
console.warn( Log.warnOnce(
yellow(bold('Warning: ')) + `For production Image Optimization with Next.js, the optional 'sharp' package is strongly recommended. Run 'npm i sharp', and Next.js will use it automatically for Image Optimization.\n` +
`For production Image Optimization with Next.js, the optional 'sharp' package is strongly recommended. Run 'npm i sharp', and Next.js will use it automatically for Image Optimization.\n` +
'Read more: https://nextjs.org/docs/messages/sharp-missing-in-production' 'Read more: https://nextjs.org/docs/messages/sharp-missing-in-production'
) )
showSharpMissingWarning = false showSharpMissingWarning = false
...@@ -533,11 +537,7 @@ export async function imageOptimizer( ...@@ -533,11 +537,7 @@ export async function imageOptimizer(
const upstreamRes = await fetch(href) const upstreamRes = await fetch(href)
if (!upstreamRes.ok) { if (!upstreamRes.ok) {
console.error( Log.error('upstream image response failed for', href, upstreamRes.status)
'upstream image response failed for',
href,
upstreamRes.status
)
throw new ImageError( throw new ImageError(
upstreamRes.status, upstreamRes.status,
'"url" parameter is valid but upstream response is invalid' '"url" parameter is valid but upstream response is invalid'
...@@ -562,7 +562,7 @@ export async function imageOptimizer( ...@@ -562,7 +562,7 @@ export async function imageOptimizer(
await mocked.res.hasStreamed await mocked.res.hasStreamed
if (!mocked.res.statusCode) { if (!mocked.res.statusCode) {
console.error('image response failed for', href, mocked.res.statusCode) Log.error('image response failed for', href, mocked.res.statusCode)
throw new ImageError( throw new ImageError(
mocked.res.statusCode, mocked.res.statusCode,
'"url" parameter is valid but internal response is invalid' '"url" parameter is valid but internal response is invalid'
...@@ -576,7 +576,7 @@ export async function imageOptimizer( ...@@ -576,7 +576,7 @@ export async function imageOptimizer(
const cacheControl = mocked.res.getHeader('Cache-Control') const cacheControl = mocked.res.getHeader('Cache-Control')
maxAge = cacheControl ? getMaxAge(cacheControl) : 0 maxAge = cacheControl ? getMaxAge(cacheControl) : 0
} catch (err) { } catch (err) {
console.error('upstream image response failed for', href, err) Log.error('upstream image response failed for', href, err)
throw new ImageError( throw new ImageError(
500, 500,
'"url" parameter is valid but upstream response is invalid' '"url" parameter is valid but upstream response is invalid'
...@@ -591,7 +591,7 @@ export async function imageOptimizer( ...@@ -591,7 +591,7 @@ export async function imageOptimizer(
upstreamType.startsWith('image/svg') && upstreamType.startsWith('image/svg') &&
!nextConfig.images.dangerouslyAllowSVG !nextConfig.images.dangerouslyAllowSVG
) { ) {
console.error( Log.error(
`The requested resource "${href}" has type "${upstreamType}" but dangerouslyAllowSVG is disabled` `The requested resource "${href}" has type "${upstreamType}" but dangerouslyAllowSVG is disabled`
) )
throw new ImageError( throw new ImageError(
...@@ -607,7 +607,7 @@ export async function imageOptimizer( ...@@ -607,7 +607,7 @@ export async function imageOptimizer(
return { buffer: upstreamBuffer, contentType: upstreamType, maxAge } return { buffer: upstreamBuffer, contentType: upstreamType, maxAge }
} }
if (!upstreamType.startsWith('image/') || upstreamType.includes(',')) { if (!upstreamType.startsWith('image/') || upstreamType.includes(',')) {
console.error( Log.error(
"The requested resource isn't a valid image for", "The requested resource isn't a valid image for",
href, href,
'received', 'received',
......
...@@ -69,7 +69,7 @@ export type ImageConfigComplete = { ...@@ -69,7 +69,7 @@ export type ImageConfigComplete = {
loaderFile: string loaderFile: string
/** /**
* @see [Image domains configuration](https://nextjs.org/docs/api-reference/next/image#domains) * @deprecated Use `remotePatterns` instead.
*/ */
domains: string[] domains: string[]
......
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
module.exports = { module.exports = {
reactStrictMode: true,
images: { images: {
domains: ['res.cloudinary.com', 'avatars.githubusercontent.com'], domains: ['res.cloudinary.com', 'avatars.githubusercontent.com'],
}, },
......
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