Unverified Commit 4cc7f11d authored by Steven's avatar Steven Committed by GitHub

Update to stable: `next/future/image`, `remotePatterns`, `unoptimized` (#40142)

This PR updates a few features from experimental to stable status:

- `next/future/image` component
- `remotePatterns` configuration
- `unoptimized` configuration
parent 643447ed
---
description: Try the latest Image Optimization with the experimental `next/future/image` component.
description: Try the latest Image Optimization with the new `next/future/image` component.
---
# next/future/image
......@@ -7,29 +7,17 @@ description: Try the latest Image Optimization with the experimental `next/futur
<details>
<summary><b>Version History</b></summary>
| Version | Changes |
| --------- | -------------------------------------------- |
| `v12.3.0` | Changed `alt` property to required. |
| `v12.2.4` | Support for `fill` property added. |
| `v12.2.0` | Experimental `next/future/image` introduced. |
| Version | Changes |
| --------- | --------------------------------------------------------------------------------------------------------------------------- |
| `v12.3.0` | `next/future/image` component stable. `remotePatterns` config stable. `unoptimized` config stable. `alt` property required. |
| `v12.2.4` | `fill` property added. |
| `v12.2.0` | Experimental `next/future/image` component introduced. |
</details>
The `next/future/image` component is an experiment to improve both the performance and developer experience of `next/image` by using the native `<img>` element with better default behavior.
The `next/future/image` component improves both the performance and developer experience of `next/image` by using the native `<img>` element with better default behavior.
This new component is considered experimental and therefore not covered by semver, and may cause unexpected or broken application behavior. This component uses browser native [lazy loading](https://caniuse.com/loading-lazy-attr), which may fallback to eager loading for older browsers before Safari 15.4. When using the blur-up placeholder, older browsers before Safari 12 will fallback to empty placeholder. When using styles with `width`/`height` of `auto`, it is possible to cause [Layout Shift](https://web.dev/cls/) on older browsers before Safari 15 that don't [preserve the aspect ratio](https://caniuse.com/mdn-html_elements_img_aspect_ratio_computed_from_attributes). For more details, see [this MDN video](https://www.youtube.com/watch?v=4-d_SoCHeWE).
To use `next/future/image`, add the following to your `next.config.js` file:
```js
module.exports = {
experimental: {
images: {
allowFutureImage: true,
},
},
}
```
This component uses browser native [lazy loading](https://caniuse.com/loading-lazy-attr), which may fallback to eager loading for older browsers before Safari 15.4. When using the blur-up placeholder, older browsers before Safari 12 will fallback to empty placeholder. When using styles with `width`/`height` of `auto`, it is possible to cause [Layout Shift](https://web.dev/cls/) on older browsers before Safari 15 that don't [preserve the aspect ratio](https://caniuse.com/mdn-html_elements_img_aspect_ratio_computed_from_attributes). For more details, see [this MDN video](https://www.youtube.com/watch?v=4-d_SoCHeWE).
## Comparison
......@@ -374,14 +362,12 @@ You can also [generate a solid color Data URL](https://png-pixel.com) to match t
When true, the source image will be served as-is instead of changing quality,
size, or format. Defaults to `false`.
This prop can be assigned to all images by updating `next.config.js` with the following experimental configuration:
This prop can be assigned to all images by updating `next.config.js` with the following configuration:
```js
module.exports = {
experimental: {
images: {
unoptimized: true,
},
images: {
unoptimized: true,
},
}
```
......@@ -399,23 +385,19 @@ Other properties on the `<Image />` component will be passed to the underlying
### Remote Patterns
> Note: The `remotePatterns` configuration is currently **experimental** and subject to change. Please use [`domains`](#domains) for production use cases.
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
module.exports = {
experimental: {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
port: '',
pathname: '/account123/**',
},
],
},
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
port: '',
pathname: '/account123/**',
},
],
},
}
```
......@@ -426,15 +408,13 @@ Below is another example of the `remotePatterns` property in the `next.config.js
```js
module.exports = {
experimental: {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '**.example.com',
},
],
},
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '**.example.com',
},
],
},
}
```
......
......@@ -16,6 +16,7 @@ description: Enable Image Optimization with the built-in Image component.
| Version | Changes |
| --------- | --------------------------------------------------------------------------------------------------------- |
| `v12.3.0` | `remotePatterns` and `unoptimized` configuration is stable. |
| `v12.2.0` | Experimental `remotePatterns` and experimental `unoptimized` configuration added. `layout="raw"` removed. |
| `v12.1.1` | `style` prop added. Experimental[\*](#experimental-raw-layout-mode) support for `layout="raw"` added. |
| `v12.1.0` | `dangerouslyAllowSVG` and `contentSecurityPolicy` configuration added. |
......@@ -93,8 +94,6 @@ The layout behavior of the image as the viewport changes size.
- When `fill`, the image will stretch both width and height to the dimensions of the parent element, provided the parent element is relative.
- This is usually paired with the [`objectFit`](#objectFit) property.
- Ensure the parent element has `position: relative` in their stylesheet.
- When `raw`[\*](#experimental-raw-layout-mode), the image will be rendered as a single image element with no wrappers, sizers or other responsive behavior.
- If your image styling will change the size of a `raw` image, you should include the `sizes` property for proper image serving. Otherwise your image will be requested as though it has fixed width and height.
- [Demo background image](https://image-component.nextjs.gallery/background)
### loader
......@@ -324,14 +323,12 @@ const Example = () => {
When true, the source image will be served as-is instead of changing quality,
size, or format. Defaults to `false`.
This prop can be assigned to all images by updating `next.config.js` with the following experimental configuration:
This prop can be assigned to all images by updating `next.config.js` with the following configuration:
```js
module.exports = {
experimental: {
images: {
unoptimized: true,
},
images: {
unoptimized: true,
},
}
```
......@@ -351,23 +348,19 @@ Other properties on the `<Image />` component will be passed to the underlying
### Remote Patterns
> Note: The `remotePatterns` configuration is currently **experimental** and subject to change. Please use [`domains`](#domains) for production use cases.
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
module.exports = {
experimental: {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
port: '',
pathname: '/account123/**',
},
],
},
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
port: '',
pathname: '/account123/**',
},
],
},
}
```
......@@ -378,15 +371,13 @@ Below is another example of the `remotePatterns` property in the `next.config.js
```js
module.exports = {
experimental: {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '**.example.com',
},
],
},
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '**.example.com',
},
],
},
}
```
......
......@@ -427,7 +427,7 @@
}
},
{
"title": "next/future/image (experimental)",
"title": "next/future/image",
"path": "/docs/api-reference/next/future/image.md"
},
{
......
......@@ -31,17 +31,10 @@ module.exports = {
dangerouslyAllowSVG: false,
// set the Content-Security-Policy header
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
// the following are experimental features, and may cause breaking changes
},
experimental: {
images: {
// limit of 50 objects
remotePatterns: [],
// when true, every image will be unoptimized
unoptimized: false,
// when true, allow `next/future/image` to be imported
allowFutureImage: false,
},
// limit of 50 objects
remotePatterns: [],
// when true, every image will be unoptimized
unoptimized: false,
},
}
```
......
/** @type {import('next').NextConfig} */
module.exports = {
experimental: {
images: {
allowFutureImage: true,
},
},
images: {
domains: ['cdn.sanity.io', 'source.unsplash.com'],
remotePatterns: [
{ hostname: 'cdn.sanity.io' },
{ hostname: 'source.unsplash.com' },
],
},
}
......@@ -2405,7 +2405,7 @@ export default async function build(
const { deviceSizes, imageSizes } = images
;(images as any).sizes = [...deviceSizes, ...imageSizes]
;(images as any).remotePatterns = (
config?.experimental?.images?.remotePatterns || []
config?.images?.remotePatterns || []
).map((p: RemotePattern) => ({
// Should be the same as matchRemotePattern()
protocol: p.protocol,
......
......@@ -196,14 +196,12 @@ export function getDefineEnv({
path: config.images.path,
loader: config.images.loader,
dangerouslyAllowSVG: config.images.dangerouslyAllowSVG,
experimentalUnoptimized: config?.experimental?.images?.unoptimized,
experimentalFuture: config.experimental?.images?.allowFutureImage,
unoptimized: config?.images?.unoptimized,
...(dev
? {
// pass domains in development to allow validating on the client
domains: config.images.domains,
experimentalRemotePatterns:
config.experimental?.images?.remotePatterns,
remotePatterns: config.images?.remotePatterns,
}
: {}),
}),
......
......@@ -15,11 +15,6 @@ import {
import { ImageConfigContext } from '../../shared/lib/image-config-context'
import { warnOnce } from '../../shared/lib/utils'
const {
experimentalFuture = false,
experimentalRemotePatterns = [],
experimentalUnoptimized,
} = (process.env.__NEXT_IMAGE_OPTS as any) || {}
const configEnv = process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete
const allImgs = new Map<
string,
......@@ -475,10 +470,7 @@ function defaultLoader({
)
}
if (
!src.startsWith('/') &&
(config.domains || experimentalRemotePatterns)
) {
if (!src.startsWith('/') && (config.domains || config.remotePatterns)) {
let parsedSrc: URL
try {
parsedSrc = new URL(src)
......@@ -492,7 +484,7 @@ function defaultLoader({
if (process.env.NODE_ENV !== 'test') {
// We use dynamic require because this should only error in development
const { hasMatch } = require('../../shared/lib/match-remote-pattern')
if (!hasMatch(config.domains, experimentalRemotePatterns, parsedSrc)) {
if (!hasMatch(config.domains, config.remotePatterns, parsedSrc)) {
throw new Error(
`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` +
`See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`
......@@ -530,11 +522,6 @@ export default function Image({
blurDataURL,
...all
}: ImageProps) {
if (!experimentalFuture && process.env.NODE_ENV !== 'test') {
throw new Error(
`The "next/future/image" component is experimental and may be subject to breaking changes. To enable this experiment, please include \`experimental: { images: { allowFutureImage: true } }\` in your next.config.js file.`
)
}
const configContext = useContext(ImageConfigContext)
const config: ImageConfig = useMemo(() => {
const c = configEnv || configContext || imageConfigDefault
......@@ -600,7 +587,7 @@ export default function Image({
unoptimized = true
isLazy = false
}
if (experimentalUnoptimized) {
if (config.unoptimized) {
unoptimized = true
}
......
......@@ -22,8 +22,6 @@ function normalizeSrc(src: string): string {
return src[0] === '/' ? src.slice(1) : src
}
const { experimentalRemotePatterns = [], experimentalUnoptimized } =
(process.env.__NEXT_IMAGE_OPTS as any) || {}
const configEnv = process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete
const loadedImageURLs = new Set<string>()
const allImgs = new Map<
......@@ -137,10 +135,7 @@ function defaultLoader({
)
}
if (
!src.startsWith('/') &&
(config.domains || experimentalRemotePatterns)
) {
if (!src.startsWith('/') && (config.domains || config.remotePatterns)) {
let parsedSrc: URL
try {
parsedSrc = new URL(src)
......@@ -154,7 +149,7 @@ function defaultLoader({
if (process.env.NODE_ENV !== 'test') {
// We use dynamic require because this should only error in development
const { hasMatch } = require('../shared/lib/match-remote-pattern')
if (!hasMatch(config.domains, experimentalRemotePatterns, parsedSrc)) {
if (!hasMatch(config.domains, config.remotePatterns, parsedSrc)) {
throw new Error(
`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` +
`See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`
......@@ -673,7 +668,7 @@ export default function Image({
if (typeof window !== 'undefined' && loadedImageURLs.has(src)) {
isLazy = false
}
if (experimentalUnoptimized) {
if (config.unoptimized) {
unoptimized = true
}
......
......@@ -321,8 +321,7 @@ export default async function exportApp(
const {
i18n,
images: { loader = 'default' },
experimental,
images: { loader = 'default', unoptimized },
} = nextConfig
if (i18n && !options.buildExport) {
......@@ -344,7 +343,7 @@ export default async function exportApp(
if (
isNextImageImported &&
loader === 'default' &&
!experimental?.images?.unoptimized &&
!unoptimized &&
!hasNextSupport
) {
throw new Error(
......
......@@ -270,44 +270,6 @@ const configSchema = {
gzipSize: {
type: 'boolean',
},
images: {
additionalProperties: false,
properties: {
allowFutureImage: {
type: 'boolean',
},
remotePatterns: {
items: {
additionalProperties: false,
properties: {
hostname: {
minLength: 1,
type: 'string',
},
pathname: {
minLength: 1,
type: 'string',
},
port: {
minLength: 1,
type: 'string',
},
protocol: {
// automatic typing doesn't like enum
enum: ['http', 'https'] as any,
type: 'string',
},
},
type: 'object',
},
type: 'array',
},
unoptimized: {
type: 'boolean',
},
},
type: 'object',
},
incrementalCacheHandlerPath: {
type: 'string',
},
......@@ -487,6 +449,35 @@ const configSchema = {
images: {
additionalProperties: false,
properties: {
remotePatterns: {
items: {
additionalProperties: false,
properties: {
hostname: {
minLength: 1,
type: 'string',
},
pathname: {
minLength: 1,
type: 'string',
},
port: {
minLength: 1,
type: 'string',
},
protocol: {
// automatic typing doesn't like enum
enum: ['http', 'https'] as any,
type: 'string',
},
},
type: 'object',
},
type: 'array',
},
unoptimized: {
type: 'boolean',
},
contentSecurityPolicy: {
minLength: 1,
type: 'string',
......
......@@ -5,7 +5,6 @@ import {
ImageConfig,
ImageConfigComplete,
imageConfigDefault,
RemotePattern,
} from '../shared/lib/image-config'
import { ServerRuntime } from 'next/types'
......@@ -117,11 +116,6 @@ export interface ExperimentalConfig {
fullySpecified?: boolean
urlImports?: NonNullable<webpack.Configuration['experiments']>['buildHttp']
outputFileTracingRoot?: string
images?: {
remotePatterns?: RemotePattern[]
unoptimized?: boolean
allowFutureImage?: boolean
}
modularizeImports?: Record<
string,
{
......@@ -572,9 +566,6 @@ export const defaultConfig: NextConfig = {
serverComponents: false,
fullySpecified: false,
outputFileTracingRoot: process.env.NEXT_PRIVATE_OUTPUT_TRACE_ROOT || '',
images: {
remotePatterns: [],
},
swcTraceProfiling: false,
forceSwcTransforms: false,
swcPlugins: undefined,
......
......@@ -256,7 +256,7 @@ function assignDefaults(userConfig: { [key: string]: any }) {
}
}
const remotePatterns = result.experimental?.images?.remotePatterns
const remotePatterns = result?.images?.remotePatterns
if (remotePatterns) {
if (!Array.isArray(remotePatterns)) {
throw new Error(
......@@ -437,7 +437,7 @@ function assignDefaults(userConfig: { [key: string]: any }) {
)
}
const unoptimized = result.experimental?.images?.unoptimized
const unoptimized = result?.images?.unoptimized
if (
typeof unoptimized !== 'undefined' &&
typeof unoptimized !== 'boolean'
......
......@@ -161,7 +161,7 @@ export class ImageOptimizerCache {
minimumCacheTTL = 60,
formats = ['image/webp'],
} = imageData
const remotePatterns = nextConfig.experimental.images?.remotePatterns || []
const remotePatterns = nextConfig.images?.remotePatterns || []
const { url, w, q } = query
let href: string
......
......@@ -74,6 +74,12 @@ export type ImageConfigComplete = {
/** @see [Dangerously Allow SVG](https://nextjs.org/docs/api-reference/next/image#dangerously-allow-svg) */
contentSecurityPolicy: string
/** @see [Remote Patterns](https://nextjs.org/docs/api-reference/next/image#remote-patterns) */
remotePatterns: RemotePattern[]
/** @see [Unoptimized](https://nextjs.org/docs/api-reference/next/image#unoptimized) */
unoptimized: boolean
}
export type ImageConfig = Partial<ImageConfigComplete>
......@@ -89,4 +95,6 @@ export const imageConfigDefault: ImageConfigComplete = {
formats: ['image/webp'],
dangerouslyAllowSVG: false,
contentSecurityPolicy: `script-src 'none'; frame-src 'none'; sandbox;`,
remotePatterns: [],
unoptimized: false,
}
......@@ -81,7 +81,7 @@ export function eventCliSession(
return []
}
const { images, i18n, experimental } = nextConfig || {}
const { images, i18n } = nextConfig || {}
const payload: EventCliSessionStarted = {
nextVersion: process.env.__NEXT_VERSION,
......@@ -95,15 +95,15 @@ export function eventCliSession(
hasWebpackConfig: typeof nextConfig?.webpack === 'function',
hasBabelConfig: hasBabelConfig(dir),
imageEnabled: !!images,
imageFutureEnabled: !!experimental.images?.allowFutureImage,
imageFutureEnabled: !!images,
basePathEnabled: !!nextConfig?.basePath,
i18nEnabled: !!i18n,
locales: i18n?.locales ? i18n.locales.join(',') : null,
localeDomainsCount: i18n?.domains ? i18n.domains.length : null,
localeDetectionEnabled: !i18n ? null : i18n.localeDetection !== false,
imageDomainsCount: images?.domains ? images.domains.length : null,
imageRemotePatternsCount: experimental?.images?.remotePatterns
? experimental.images.remotePatterns.length
imageRemotePatternsCount: images?.remotePatterns
? images.remotePatterns.length
: null,
imageSizes: images?.imageSizes ? images.imageSizes.join(',') : null,
imageLoader: images?.loader,
......
......@@ -87,10 +87,8 @@ describe('Export with unoptimized next/image component', () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
experimental: {
images: {
unoptimized: true,
},
images: {
unoptimized: true,
},
})
)
......
module.exports = {
experimental: {
images: {
remotePatterns: [{ hostname: 'image-optimization-test.vercel.app' }],
},
images: {
remotePatterns: [{ hostname: 'image-optimization-test.vercel.app' }],
},
}
module.exports = {
experimental: {
images: {
unoptimized: true,
},
images: {
unoptimized: true,
},
}
module.exports = {
assetPrefix: 'https://example.vercel.sh/pre',
// Intentionally omit `domains` and `remotePatterns`
experimental: {
images: {
allowFutureImage: true,
},
},
}
module.exports = {
basePath: '/docs',
experimental: {
images: {
allowFutureImage: true,
},
},
}
module.exports = {
experimental: {
images: {
allowFutureImage: true,
},
},
}
......@@ -2,9 +2,4 @@ module.exports = {
images: {
domains: ['i.imgur.com'],
},
experimental: {
images: {
allowFutureImage: true,
},
},
}
module.exports = {
experimental: {
images: {
allowFutureImage: true,
},
},
}
......@@ -10,9 +10,4 @@ module.exports = {
return config
},
experimental: {
images: {
allowFutureImage: true,
},
},
}
module.exports = {
trailingSlash: true,
experimental: {
images: {
allowFutureImage: true,
},
},
}
......@@ -3,9 +3,4 @@ module.exports = {
domains: ['image-optimization-test.vercel.app'],
// disableStaticImages: true,
},
experimental: {
images: {
allowFutureImage: true,
},
},
}
module.exports = {
experimental: {
images: {
remotePatterns: [{ hostname: 'image-optimization-test.vercel.app' }],
allowFutureImage: true,
},
images: {
remotePatterns: [{ hostname: 'image-optimization-test.vercel.app' }],
},
}
module.exports = {
experimental: {
images: {
unoptimized: true,
allowFutureImage: true,
},
images: {
unoptimized: true,
},
}
......@@ -52,12 +52,10 @@ describe('Image Optimizer', () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
experimental: {
images: {
remotePatterns: Array.from({ length: 51 }).map((_) => ({
hostname: 'example.com',
})),
},
images: {
remotePatterns: Array.from({ length: 51 }).map((_) => ({
hostname: 'example.com',
})),
},
})
)
......@@ -81,10 +79,8 @@ describe('Image Optimizer', () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
experimental: {
images: {
remotePatterns: [{ hostname: 'example.com', foo: 'bar' }],
},
images: {
remotePatterns: [{ hostname: 'example.com', foo: 'bar' }],
},
})
)
......@@ -108,10 +104,8 @@ describe('Image Optimizer', () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
experimental: {
images: {
remotePatterns: [{ protocol: 'https' }],
},
images: {
remotePatterns: [{ protocol: 'https' }],
},
})
)
......
......@@ -4,11 +4,7 @@ module.exports = phase => {
formats: ['image/avif', 'image/webp'],
imageSizes: [64, 128, 256, 512, 1024],
domains: ['example.com', 'another.com'],
},
experimental: {
images: {
remotePatterns: [{ protocol: 'https', hostname: '**.example.com' }],
},
remotePatterns: [{ protocol: 'https', hostname: '**.example.com' }],
},
i18n: {
locales: ['en','nl','fr'],
......
......@@ -503,7 +503,7 @@ describe('Telemetry CLI', () => {
expect(event1).toMatch(/"localeDomainsCount": 2/)
expect(event1).toMatch(/"localeDetectionEnabled": true/)
expect(event1).toMatch(/"imageEnabled": true/)
expect(event1).toMatch(/"imageFutureEnabled": false/)
expect(event1).toMatch(/"imageFutureEnabled": true/)
expect(event1).toMatch(/"imageDomainsCount": 2/)
expect(event1).toMatch(/"imageRemotePatternsCount": 1/)
expect(event1).toMatch(/"imageSizes": "64,128,256,512,1024"/)
......
......@@ -2,10 +2,8 @@
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
images: {
allowFutureImage: true,
},
images: {
dangerouslyAllowSVG: true,
},
}
......
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