File size: 53,517 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 |
---
title: Image Component
description: Optimize Images in your Next.js Application using the built-in `next/image` Component.
---
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
The Next.js Image component extends the HTML `<img>` element for automatic image optimization.
```jsx filename="app/page.js"
import Image from 'next/image'
export default function Page() {
return (
<Image
src="/profile.png"
width={500}
height={500}
alt="Picture of the author"
/>
)
}
```
<PagesOnly>
> **Good to know**: If you are using a version of Next.js prior to 13, you'll want to use the [next/legacy/image](/docs/pages/api-reference/components/image-legacy) documentation since the component was renamed.
</PagesOnly>
## Reference
### Props
The following props are available:
<div style={{ overflowX: 'auto', width: '100%' }}>
| Prop | Example | Type | Status |
| ----------------------------------------- | ---------------------------------------- | --------------- | ---------- |
| [`src`](#src) | `src="/profile.png"` | String | Required |
| [`alt`](#alt) | `alt="Picture of the author"` | String | Required |
| [`width`](#width-and-height) | `width={500}` | Integer (px) | - |
| [`height`](#width-and-height) | `height={500}` | Integer (px) | - |
| [`fill`](#fill) | `fill={true}` | Boolean | - |
| [`loader`](#loader) | `loader={imageLoader}` | Function | - |
| [`sizes`](#sizes) | `sizes="(max-width: 768px) 100vw, 33vw"` | String | - |
| [`quality`](#quality) | `quality={80}` | Integer (1-100) | - |
| [`priority`](#priority) | `priority={true}` | Boolean | - |
| [`placeholder`](#placeholder) | `placeholder="blur"` | String | - |
| [`style`](#style) | `style={{objectFit: "contain"}}` | Object | - |
| [`onLoadingComplete`](#onloadingcomplete) | `onLoadingComplete={img => done())}` | Function | Deprecated |
| [`onLoad`](#onload) | `onLoad={event => done())}` | Function | - |
| [`onError`](#onerror) | `onError(event => fail()}` | Function | - |
| [`loading`](#loading) | `loading="lazy"` | String | - |
| [`blurDataURL`](#blurdataurl) | `blurDataURL="data:image/jpeg..."` | String | - |
| [`overrideSrc`](#overridesrc) | `overrideSrc="/seo.png"` | String | - |
</div>
#### `src`
The source of the image. Can be one of the following:
An internal path string.
```jsx
<Image src="/profile.png" />
```
An absolute external URL (must be configured with [remotePatterns](#remotepatterns)).
```jsx
<Image src="https://example.com/profile.png" />
```
A static import.
```jsx
import profile from './profile.png'
export default function Page() {
return <Image src={profile} />
}
```
#### `alt`
The `alt` property is used to describe the image for screen readers and search engines. It is also the fallback text if images have been disabled or an error occurs while loading the image.
It should contain text that could replace the image [without changing the meaning of the page](https://html.spec.whatwg.org/multipage/images.html#general-guidelines). It is not meant to supplement the image and should not repeat information that is already provided in the captions above or below the image.
If the image is [purely decorative](https://html.spec.whatwg.org/multipage/images.html#a-purely-decorative-image-that-doesn't-add-any-information) or [not intended for the user](https://html.spec.whatwg.org/multipage/images.html#an-image-not-intended-for-the-user), the `alt` property should be an empty string (`alt=""`).
> Learn more about [image accessibility guidelines](https://html.spec.whatwg.org/multipage/images.html#alt).
#### `width` and `height`
The `width` and `height` properties represent the [intrinsic](https://developer.mozilla.org/en-US/docs/Glossary/Intrinsic_Size) image size in pixels. This property is used to infer the correct **aspect ratio** used by browsers to reserve space for the image and avoid layout shift during loading. It does not determine the _rendered size_ of the image, which is controlled by CSS.
```jsx
<Image src="/profile.png" width={500} height={500} />
```
You **must** set both `width` and `height` properties unless:
- The image is statically imported.
- The image has the [`fill` property](#fill)
If the height and width are unknown, we recommend using the [`fill` property](#fill).
#### `fill`
A boolean that causes the image to expand to the size of the parent element.
```js
<Image src="/profile.png" fill={true} />
```
**Positioning**:
- The parent element **must** assign `position: "relative"`, `"fixed"`, `"absolute"`.
- By default, the `<img>` element uses `position: "absolute"`.
**Object Fit**:
If no styles are applied to the image, the image will stretch to fit the container. You can use `objectFit` to control cropping and scaling.
- `"contain"`: The image will be scaled down to fit the container and preserve aspect ratio.
- `"cover"`: The image will fill the container and be cropped.
> Learn more about [`position`](https://developer.mozilla.org/en-US/docs/Web/CSS/position) and [`object-fit`](https://developer.mozilla.org/docs/Web/CSS/object-fit).
#### `loader`
A custom function used to generate the image URL. The function receives the following parameters, and returns a URL string for the image:
- [`src`](#src)
- [`width`](#width-and-height)
- [`quality`](#quality)
<AppOnly>
```js
'use client'
import Image from 'next/image'
const imageLoader = ({ src, width, quality }) => {
return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}
export default function Page() {
return (
<Image
loader={imageLoader}
src="me.png"
alt="Picture of the author"
width={500}
height={500}
/>
)
}
```
> **Good to know**: Using props like `onLoad`, which accept a function, requires using [Client Components](https://react.dev/reference/rsc/use-client) to serialize the provided function.
</AppOnly>
<PagesOnly>
```js
import Image from 'next/image'
const imageLoader = ({ src, width, quality }) => {
return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}
export default function Page() {
return (
<Image
loader={imageLoader}
src="me.png"
alt="Picture of the author"
width={500}
height={500}
/>
)
}
```
</PagesOnly>
Alternatively, you can use the [loaderFile](#loaderfile) configuration in `next.config.js` to configure every instance of `next/image` in your application, without passing a prop.
#### `sizes`
Define the sizes of the image at different breakpoints. Used by the browser to choose the most appropriate size from the generated `srcset`.
```jsx
import Image from 'next/image'
export default function Page() {
return (
<div className="grid-element">
<Image
fill
src="/example.png"
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
/>
</div>
)
}
```
`sizes` should be used when:
- The image is using the [`fill`](#fill) prop
- CSS is used to make the image responsive
If `sizes` is missing, the browser assumes the image will be as wide as the viewport (`100vw`). This can cause unnecessarily large images to be downloaded.
In addition, `sizes` affects how `srcset` is generated:
- Without `sizes`: Next.js generates a limited `srcset` (e.g. 1x, 2x), suitable for fixed-size images.
- With `sizes`: Next.js generates a full `srcset` (e.g. 640w, 750w, etc.), optimized for responsive layouts.
> Learn more about `srcset` and `sizes` on [web.dev](https://web.dev/learn/design/responsive-images/#sizes) and [mdn](https://developer.mozilla.org/docs/Web/HTML/Element/img#sizes).
#### `quality`
An integer between `1` and `100` that sets the quality of the optimized image. Higher values increase file size and visual fidelity. Lower values reduce file size but may affect sharpness.
```jsx
// Default quality is 75
<Image quality={75} />
```
If you’ve configured [qualities](#qualities) in `next.config.js`, the value must match one of the allowed entries.
> **Good to know**: If the original image is already low quality, setting a high quality value will increase the file size without improving appearance.
#### `style`
Allows passing CSS styles to the underlying image element.
```jsx
const imageStyle = {
borderRadius: '50%',
border: '1px solid #fff',
width: '100px',
height: 'auto',
}
export default function ProfileImage() {
return <Image src="..." style={imageStyle} />
}
```
> **Good to know**: If you’re using the `style` prop to set a custom width, be sure to also set `height: 'auto'` to preserve the image’s aspect ratio.
#### `priority`
A boolean that indicates if the image should be preloaded.
```jsx
// Default priority is false
<Image priority={false} />
```
- `true`: [Preloads](https://web.dev/preload-responsive-images/) the image. Disables lazy loading.
- `false`: Lazy loads the image.
**When to use it:**
- The image is above the fold.
- The image is the [Largest Contentful Paint (LCP)](https://nextjs.org/learn/seo/web-performance/lcp) element.
- You want to improve the initial loading performance of your page.
**When not to use it:**
- When the `loading` prop isused (will trigger warnings).
#### `loading`
Controls when the image should start loading.
```jsx
// Defaults to lazy
<Image loading="lazy" />
```
- `lazy`: Defer loading the image until it reaches a calculated distance from the viewport.
- `eager`: Load the image immediately, regardless of its position in the page.
Use `eager` only when you want to ensure the image is loaded immediately.
> Learn more about the [`loading` attribute](https://developer.mozilla.org/docs/Web/HTML/Element/img#loading).
#### `placeholder`
Specifies a placeholder to use while the image is loading, improving the perceived loading performance.
```jsx
// defaults to empty
<Image placeholder="empty" />
```
- `empty`: No placeholder while the image is loading.
- `blur`: Use a blurred version of the image as a placeholder. Must be used with the [`blurDataURL`](#blurdataurl) property.
- `data:image/...`: Uses the [Data URL](https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) as the placeholder.
**Examples:**
- [`blur` placeholder](https://image-component.nextjs.gallery/placeholder)
- [Shimmer effect with data URL `placeholder` prop](https://image-component.nextjs.gallery/shimmer)
- [Color effect with `blurDataURL` prop](https://image-component.nextjs.gallery/color)
> Learn more about the [`placeholder` attribute](https://developer.mozilla.org/docs/Web/HTML/Element/img#placeholder).
#### `blurDataURL`
A [Data URL](https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) to
be used as a placeholder image before the image successfully loads. Can be automatically set or used with the [`placeholder="blur"`](#placeholder) property.
```jsx
<Image placeholder="blur" blurDataURL="..." />
```
The image is automatically enlarged and blurred, so a very small image (10px or less) is recommended.
**Automatic**
If `src` is a static import of a `jpg`, `png`, `webp`, or `avif` file, `blurDataURL` is added automatically—unless the image is animated.
**Manually set**
If the image is dynamic or remote, you must provide `blurDataURL` yourself. To generate one, you can use:
- [A online tool like png-pixel.com](https://png-pixel.com)
- [A library like Plaiceholder](https://github.com/joe-bell/plaiceholder)
A large blurDataURL may hurt performance. Keep it small and simple.
**Examples:**
- [Default `blurDataURL` prop](https://image-component.nextjs.gallery/placeholder)
- [Color effect with `blurDataURL` prop](https://image-component.nextjs.gallery/color)
#### `onLoad`
A callback function that is invoked once the image is completely loaded and the [placeholder](#placeholder) has been removed.
```jsx
<Image onLoad={(e) => console.log(e.target.naturalWidth)} />
```
The callback function will be called with one argument, the event which has a `target` that references the underlying `<img>` element.
<AppOnly>
> **Good to know**: Using props like `onLoad`, which accept a function, requires using [Client Components](https://react.dev/reference/rsc/use-client) to serialize the provided function.
</AppOnly>
#### `onError`
A callback function that is invoked if the image fails to load.
```jsx
<Image onError={(e) => console.error(e.target.id)} />
```
<AppOnly>
> **Good to know**: Using props like `onError`, which accept a function, requires using [Client Components](https://react.dev/reference/rsc/use-client) to serialize the provided function.
</AppOnly>
#### `unoptimized`
A boolean that indicates if the image should be optimized. This is useful for images that do not benefit from optimization such as small images (less than 1KB), vector images (SVG), or animated images (GIF).
```js
import Image from 'next/image'
const UnoptimizedImage = (props) => {
// Default is false
return <Image {...props} unoptimized />
}
```
- `true`: The source image will be served as-is from the `src` instead of changing quality, size, or format.
- `false`: The source image will be optimized.
Since Next.js 12.3.0, this prop can be assigned to all images by updating `next.config.js` with the following configuration:
```js filename="next.config.js"
module.exports = {
images: {
unoptimized: true,
},
}
```
#### `overrideSrc`
When providing the `src` prop to the `<Image>` component, both the `srcset` and `src` attributes are generated automatically for the resulting `<img>`.
```jsx filename="input.js"
<Image src="/profile.jpg" />
```
```html filename="output.html"
<img
srcset="
/_next/image?url=%2Fprofile.jpg&w=640&q=75 1x,
/_next/image?url=%2Fprofile.jpg&w=828&q=75 2x
"
src="/_next/image?url=%2Fprofile.jpg&w=828&q=75"
/>
```
In some cases, it is not desirable to have the `src` attribute generated and you may wish to override it using the `overrideSrc` prop.
For example, when upgrading an existing website from `<img>` to `<Image>`, you may wish to maintain the same `src` attribute for SEO purposes such as image ranking or avoiding recrawl.
```jsx filename="input.js"
<Image src="/profile.jpg" overrideSrc="/override.jpg" />
```
```html filename="output.html"
<img
srcset="
/_next/image?url=%2Fprofile.jpg&w=640&q=75 1x,
/_next/image?url=%2Fprofile.jpg&w=828&q=75 2x
"
src="/override.jpg"
/>
```
#### `decoding`
A hint to the browser indicating if it should wait for the image to be decoded before presenting other content updates or not.
```jsx
// Default is async
<Image decoding="async" />
```
- `async`: Asynchronously decode the image and allow other content to be rendered before it completes.
- `sync`: Synchronously decode the image for atomic presentation with other content.
- `auto`: No preference. The browser chooses the best approach.
> Learn more about the [`decoding` attribute](https://developer.mozilla.org/docs/Web/HTML/Element/img#decoding).
### Other Props
Other properties on the `<Image />` component will be passed to the underlying `img` element with the exception of the following:
- `srcSet`: Use [Device Sizes](#devicesizes) instead.
### Deprecated props
#### `onLoadingComplete`
> **Warning**: Deprecated in Next.js 14, use [`onLoad`](#onload) instead.
A callback function that is invoked once the image is completely loaded and the [placeholder](#placeholder) has been removed.
The callback function will be called with one argument, a reference to the underlying `<img>` element.
<AppOnly>
```jsx
'use client'
<Image onLoadingComplete={(img) => console.log(img.naturalWidth)} />
```
</AppOnly>
<PagesOnly>
```jsx
<Image onLoadingComplete={(img) => console.log(img.naturalWidth)} />
```
</PagesOnly>
<AppOnly>
> **Good to know**: Using props like `onLoadingComplete`, which accept a function, requires using [Client Components](https://react.dev/reference/rsc/use-client) to serialize the provided function.
</AppOnly>
### Configuration options
You can configure the Image Component in `next.config.js`. The following options are available:
#### `localPatterns`
Use `localPatterns` in your `next.config.js` file to allow images from specific local paths to be optimized and block all others.
```js filename="next.config.js"
module.exports = {
images: {
localPatterns: [
{
pathname: '/assets/images/**',
search: '',
},
],
},
}
```
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.
#### `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.
```js filename="next.config.js"
module.exports = {
images: {
remotePatterns: [new URL('https://example.com/account123/**')],
},
}
```
If using a version prior to 15.3.0, you can configure `remotePatterns` using the object:
```js filename="next.config.js"
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
port: '',
pathname: '/account123/**',
search: '',
},
],
},
}
```
The example above will ensure the `src` property of `next/image` must start with `https://example.com/account123/` and must not have a query string. Any other protocol, hostname, port, or unmatched path will respond with `400` Bad Request.
**Wildcard Patterns:**
Wildcard patterns can be used for both `pathname` and `hostname` and have the following syntax:
- `*` match a single path segment or subdomain
- `**` match any number of path segments at the end or subdomains at the beginning. This syntax does not work in the middle of the pattern.
```js filename="next.config.js"
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '**.example.com',
port: '',
search: '',
},
],
},
}
```
This allows subdomains like `image.example.com`. Query strings and custom ports are still blocked.
> **Good to know**: When omitting `protocol`, `port`, `pathname`, or `search` then the wildcard `**` is implied. This is not recommended because it may allow malicious actors to optimize urls you did not intend.
**Query Strings**:
You can also restrict query strings using the `search` property:
```js filename="next.config.js"
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'assets.example.com',
search: '?v=1727111025337',
},
],
},
}
```
The example above will ensure the `src` property of `next/image` must start with `https://assets.example.com` and must have the exact query string `?v=1727111025337`. Any other protocol or query string will respond with `400` Bad Request.
#### `loaderFile`
`loaderFiles` allows you to use a custom image optimization service instead of Next.js.
```js filename="next.config.js"
module.exports = {
images: {
loader: 'custom',
loaderFile: './my/image/loader.js',
},
}
```
The path must be relative to the project root. The file must export a default function that returns a URL string:
<AppOnly>
```js filename="my/image/loader.js"
'use client'
export default function myImageLoader({ src, width, quality }) {
return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}
```
</AppOnly>
<PagesOnly>
```js filename="my/image/loader.js"
export default function myImageLoader({ src, width, quality }) {
return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}
```
</PagesOnly>
**Example:**
- [Custom Image Loader Configuration](/docs/app/api-reference/config/next-config-js/images#example-loader-configuration)
> Alternatively, you can use the [`loader` prop](#loader) to configure each instance of `next/image`.
#### `deviceSizes`
`deviceSizes` allows you to specify a list of device width breakpoints. These widths are used when the `next/image` component uses [`sizes`](#sizes) prop to ensure the correct image is served for the user's device.
If no configuration is provided, the default below is used:
```js filename="next.config.js"
module.exports = {
images: {
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
},
}
```
#### `imageSizes`
`imageSizes` allows you to specify a list of image widths. These widths are concatenated with the array of [device sizes](#devicesizes) to form the full array of sizes used to generate image [srcset](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/srcset).
If no configuration is provided, the default below is used:
```js filename="next.config.js"
module.exports = {
images: {
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
},
}
```
`imageSizes` is only used for images which provide a [`sizes`](#sizes) prop, which indicates that the image is less than the full width of the screen. Therefore, the sizes in `imageSizes` should all be smaller than the smallest size in `deviceSizes`.
#### `qualities`
`qualities` allows you to specify a list of image quality values.
```js filename="next.config.js"
module.exports = {
images: {
qualities: [25, 50, 75],
},
}
```
In the example above, only three qualities are allowed: 25, 50, and 75. If the [`quality`](#quality) prop does not match a value in this array, the image will fail with a `400` Bad Request.
#### `formats`
`formats` allows you to specify a list of image formats to be used.
```js filename="next.config.js"
module.exports = {
images: {
// Default
formats: ['image/webp'],
},
}
```
Next.js automatically detects the browser's supported image formats via the request's `Accept` header in order to determine the best output format.
If the `Accept` header matches more than one of the configured formats, the first match in the array is used. Therefore, the array order matters. If there is no match (or the source image is animated), it will use the original image's format.
You can enable AVIF support, which will fallback to the original format of the src image if the browser [does not support AVIF](https://caniuse.com/avif):
```js filename="next.config.js"
module.exports = {
images: {
formats: ['image/avif'],
},
}
```
> **Good to know**:
>
> - We still recommend using WebP for most use cases.
> - AVIF generally takes 50% longer to encode but it compresses 20% smaller compared to WebP. This means that the first time an image is requested, it will typically be slower, but subsequent requests that are cached will be faster.
> - If you self-host with a Proxy/CDN in front of Next.js, you must configure the Proxy to forward the `Accept` header.
#### `minimumCacheTTL`
`minimumCacheTTL` allows you to configure the Time to Live (TTL) in seconds for cached optimized images. In many cases, it's better to use a [Static Image Import](/docs/app/getting-started/images#local-images) which will automatically hash the file contents and cache the image forever with a `Cache-Control` header of `immutable`.
If no configuration is provided, the default below is used.
```js filename="next.config.js"
module.exports = {
images: {
minimumCacheTTL: 60, // 1 minute
},
}
```
You can increase the TTL to reduce the number of revalidations and potentionally lower cost:
```js filename="next.config.js"
module.exports = {
images: {
minimumCacheTTL: 2678400, // 31 days
},
}
```
The expiration (or rather Max Age) of the optimized image is defined by either the `minimumCacheTTL` or the upstream image `Cache-Control` header, whichever is larger.
If you need to change the caching behavior per image, you can configure [`headers`](/docs/app/api-reference/config/next-config-js/headers) to set the `Cache-Control` header on the upstream image (e.g. `/some-asset.jpg`, not `/_next/image` itself).
There is no mechanism to invalidate the cache at this time, so its best to keep `minimumCacheTTL` low. Otherwise you may need to manually change the [`src`](#src) prop or delete the cached file `<distDir>/cache/images`.
#### `disableStaticImages`
`disableStaticImages` allows you to disable static image imports.
The default behavior allows you to import static files such as `import icon from './icon.png'` and then pass that to the `src` property. In some cases, you may wish to disable this feature if it conflicts with other plugins that expect the import to behave differently.
You can disable static image imports inside your `next.config.js`:
```js filename="next.config.js"
module.exports = {
images: {
disableStaticImages: true,
},
}
```
#### `dangerouslyAllowSVG`
`dangerouslyAllowSVG` allows you to serve SVG images.
```js filename="next.config.js"
module.exports = {
images: {
dangerouslyAllowSVG: true,
},
}
```
By default, Next.js does not optimize SVG images for a few reasons:
- SVG is a vector format meaning it can be resized losslessly.
- SVG has many of the same features as HTML/CSS, which can lead to vulnerabilities without proper [Content Security Policy (CSP) headers](/docs/app/api-reference/config/next-config-js/headers#content-security-policy).
We recommend using the [`unoptimized`](#unoptimized) prop when the [`src`](#src) prop is known to be SVG. This happens automatically when `src` ends with `".svg"`.
```jsx
<Image src="/my-image.svg" unoptimized />
```
In addition, it is strongly recommended to also set `contentDispositionType` to force the browser to download the image, as well as `contentSecurityPolicy` to prevent scripts embedded in the image from executing.
```js filename="next.config.js"
module.exports = {
images: {
dangerouslyAllowSVG: true,
contentDispositionType: 'attachment',
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
},
}
```
#### `contentDispositionType`
`contentDispositionType` allows you to configure the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#as_a_response_header_for_the_main_body) header.
```js filename="next.config.js"
module.exports = {
images: {
contentDispositionType: 'inline',
},
}
```
#### `contentSecurityPolicy`
`contentSecurityPolicy` allows you to configure the [`Content-Security-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP) header for images. This is particularly important when using [`dangerouslyAllowSVG`](#dangerouslyallowsvg) to prevent scripts embedded in the image from executing.
```js filename="next.config.js"
module.exports = {
images: {
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
},
}
```
By default, the [loader](#loader) sets the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#as_a_response_header_for_the_main_body) header to `attachment` for added protection since the API can serve arbitrary remote images.
The default value is `attachment` which forces the browser to download the image when visiting directly. This is particularly important when [`dangerouslyAllowSVG`](#dangerouslyallowsvg) is true.
You can optionally configure `inline` to allow the browser to render the image when visiting directly, without downloading it.
### Deprecated configuration options
#### `domains`
> **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. However, the `domains` configuration does not support wildcard pattern matching and it cannot restrict protocol, port, or pathname.
Below is an example of the `domains` property in the `next.config.js` file:
```js filename="next.config.js"
module.exports = {
images: {
domains: ['assets.acme.com'],
},
}
```
## Functions
### `getImageProps`
The `getImageProps` function can be used to get the props that would be passed to the underlying `<img>` element, and instead pass them to another component, style, canvas, etc.
```jsx
import { getImageProps } from 'next/image'
const props = getImageProps({
src: 'https://example.com/image.jpg',
alt: 'A scenic mountain view',
width: 1200,
height: 800,
})
function ImageWithCaption() {
return (
<figure>
<img {...props} />
<figcaption>A scenic mountain view</figcaption>
</figure>
)
}
```
This also avoid calling React `useState()` so it can lead to better performance, but it cannot be used with the [`placeholder`](#placeholder) prop because the placeholder will never be removed.
## Known browser bugs
This `next/image` 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).
- [Safari 15 - 16.3](https://bugs.webkit.org/show_bug.cgi?id=243601) display a gray border while loading. Safari 16.4 [fixed this issue](https://webkit.org/blog/13966/webkit-features-in-safari-16-4/#:~:text=Now%20in%20Safari%2016.4%2C%20a%20gray%20line%20no%20longer%20appears%20to%20mark%20the%20space%20where%20a%20lazy%2Dloaded%20image%20will%20appear%20once%20it%E2%80%99s%20been%20loaded.). Possible solutions:
- Use CSS `@supports (font: -apple-system-body) and (-webkit-appearance: none) { img[loading="lazy"] { clip-path: inset(0.6px) } }`
- Use [`priority`](#priority) if the image is above the fold
- [Firefox 67+](https://bugzilla.mozilla.org/show_bug.cgi?id=1556156) displays a white background while loading. Possible solutions:
- Enable [AVIF `formats`](#formats)
- Use [`placeholder`](#placeholder)
## Examples
### Styling images
Styling the Image component is similar to styling a normal `<img>` element, but there are a few guidelines to keep in mind:
Use `className` or `style`, not `styled-jsx`. In most cases, we recommend using the `className` prop. This can be an imported [CSS Module](/docs/app/getting-started/css), a [global stylesheet](/docs/app/getting-started/css#global-css), etc.
```jsx
import styles from './styles.module.css'
export default function MyImage() {
return <Image className={styles.image} src="/my-image.png" alt="My Image" />
}
```
You can also use the `style` prop to assign inline styles.
```jsx
export default function MyImage() {
return (
<Image style={{ borderRadius: '8px' }} src="/my-image.png" alt="My Image" />
)
}
```
When using `fill`, the parent element must have `position: relative` or `display: block`. This is necessary for the proper rendering of the image element in that layout mode.
```jsx
<div style={{ position: 'relative' }}>
<Image fill src="/my-image.png" alt="My Image" />
</div>
```
You cannot use [styled-jsx](/docs/app/guides/css-in-js) because it's scoped to the current component (unless you mark the style as `global`).
### Responsive images with a static export
When you import a static image, Next.js automatically sets its width and height based on the file. You can make the image responsive by setting the style:
<Image
alt="Responsive image filling the width and height of its parent container"
srcLight="/docs/light/responsive-image.png"
srcDark="/docs/dark/responsive-image.png"
width="1600"
height="629"
/>
```jsx
import Image from 'next/image'
import mountains from '../public/mountains.jpg'
export default function Responsive() {
return (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<Image
alt="Mountains"
// Importing an image will
// automatically set the width and height
src={mountains}
sizes="100vw"
// Make the image display full width
// and preserve its aspect ratio
style={{
width: '100%',
height: 'auto',
}}
/>
</div>
)
}
```
### Responsive images with a remote URL
If the source image is a dynamic or a remote URL, you must provide the width and height props so Next.js can calculate the aspect ratio:
```jsx filename="components/page.js"
import Image from 'next/image'
export default function Page({ photoUrl }) {
return (
<Image
src={photoUrl}
alt="Picture of the author"
sizes="100vw"
style={{
width: '100%',
height: 'auto',
}}
width={500}
height={300}
/>
)
}
```
Try it out:
- [Demo the image responsive to viewport](https://image-component.nextjs.gallery/responsive)
### Responsive image with `fill`
If you don't know the aspect ratio of the image, you can add the [`fill` prop](#fill) with the `objectFit` prop set to `cover`. This will make the image fill the full width of its parent container.
<Image
alt="Grid of images filling parent container width"
srcLight="/docs/light/fill-container.png"
srcDark="/docs/dark/fill-container.png"
width="1600"
height="529"
/>
```jsx
import Image from 'next/image'
import mountains from '../public/mountains.jpg'
export default function Fill() {
return (
<div
style={{
display: 'grid',
gridGap: '8px',
gridTemplateColumns: 'repeat(auto-fit, minmax(400px, auto))',
}}
>
<div style={{ position: 'relative', width: '400px' }}>
<Image
alt="Mountains"
src={mountains}
fill
sizes="(min-width: 808px) 50vw, 100vw"
style={{
objectFit: 'cover', // cover, contain, none
}}
/>
</div>
{/* And more images in the grid... */}
</div>
)
}
```
### Background Image
Use the `fill` prop to make the image cover the entire screen area:
<Image
alt="Background image taking full width and height of page"
srcLight="/docs/light/background-image.png"
srcDark="/docs/dark/background-image.png"
width="1600"
height="427"
/>
```jsx
import Image from 'next/image'
import mountains from '../public/mountains.jpg'
export default function Background() {
return (
<Image
alt="Mountains"
src={mountains}
placeholder="blur"
quality={100}
fill
sizes="100vw"
style={{
objectFit: 'cover',
}}
/>
)
}
```
For examples of the Image component used with the various styles, see the [Image Component Demo](https://image-component.nextjs.gallery).
### Remote images
To use a remote image, the `src` property should be a URL string.
```jsx filename="app/page.js"
import Image from 'next/image'
export default function Page() {
return (
<Image
src="https://s3.amazonaws.com/my-bucket/profile.png"
alt="Picture of the author"
width={500}
height={500}
/>
)
}
```
Since Next.js does not have access to remote files during the build process, you'll need to provide the [`width`](/docs/app/api-reference/components/image#width-and-height), [`height`](/docs/app/api-reference/components/image#width-and-height) and optional [`blurDataURL`](/docs/app/api-reference/components/image#blurdataurl) props manually.
The `width` and `height` attributes are used to infer the correct aspect ratio of image and avoid layout shift from the image loading in. The `width` and `height` do _not_ determine the rendered size of the image file.
To safely allow optimizing images, define a list of supported URL patterns in `next.config.js`. Be as specific as possible to prevent malicious usage. For example, the following configuration will only allow images from a specific AWS S3 bucket:
```js filename="next.config.js"
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 's3.amazonaws.com',
port: '',
pathname: '/my-bucket/**',
search: '',
},
],
},
}
```
### Theme detection
If you want to display a different image for light and dark mode, you can create a new component that wraps two `<Image>` components and reveals the correct one based on a CSS media query.
```css filename="components/theme-image.module.css"
.imgDark {
display: none;
}
@media (prefers-color-scheme: dark) {
.imgLight {
display: none;
}
.imgDark {
display: unset;
}
}
```
```tsx filename="components/theme-image.tsx" switcher
import styles from './theme-image.module.css'
import Image, { ImageProps } from 'next/image'
type Props = Omit<ImageProps, 'src' | 'priority' | 'loading'> & {
srcLight: string
srcDark: string
}
const ThemeImage = (props: Props) => {
const { srcLight, srcDark, ...rest } = props
return (
<>
<Image {...rest} src={srcLight} className={styles.imgLight} />
<Image {...rest} src={srcDark} className={styles.imgDark} />
</>
)
}
```
```jsx filename="components/theme-image.js" switcher
import styles from './theme-image.module.css'
import Image from 'next/image'
const ThemeImage = (props) => {
const { srcLight, srcDark, ...rest } = props
return (
<>
<Image {...rest} src={srcLight} className={styles.imgLight} />
<Image {...rest} src={srcDark} className={styles.imgDark} />
</>
)
}
```
> **Good to know**: The default behavior of `loading="lazy"` ensures that only the correct image is loaded. You cannot use `priority` or `loading="eager"` because that would cause both images to load. Instead, you can use [`fetchPriority="high"`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/fetchPriority).
Try it out:
- [Demo light/dark mode theme detection](https://image-component.nextjs.gallery/theme)
### Art direction
If you want to display a different image for mobile and desktop, sometimes called [Art Direction](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#art_direction), you can provide different `src`, `width`, `height`, and `quality` props to `getImageProps()`.
```jsx filename="app/page.js"
import { getImageProps } from 'next/image'
export default function Home() {
const common = { alt: 'Art Direction Example', sizes: '100vw' }
const {
props: { srcSet: desktop },
} = getImageProps({
...common,
width: 1440,
height: 875,
quality: 80,
src: '/desktop.jpg',
})
const {
props: { srcSet: mobile, ...rest },
} = getImageProps({
...common,
width: 750,
height: 1334,
quality: 70,
src: '/mobile.jpg',
})
return (
<picture>
<source media="(min-width: 1000px)" srcSet={desktop} />
<source media="(min-width: 500px)" srcSet={mobile} />
<img {...rest} style={{ width: '100%', height: 'auto' }} />
</picture>
)
}
```
### Background CSS
You can even convert the `srcSet` string to the [`image-set()`](https://developer.mozilla.org/en-US/docs/Web/CSS/image/image-set) CSS function to optimize a background image.
```jsx filename="app/page.js"
import { getImageProps } from 'next/image'
function getBackgroundImage(srcSet = '') {
const imageSet = srcSet
.split(', ')
.map((str) => {
const [url, dpi] = str.split(' ')
return `url("${url}") ${dpi}`
})
.join(', ')
return `image-set(${imageSet})`
}
export default function Home() {
const {
props: { srcSet },
} = getImageProps({ alt: '', width: 128, height: 128, src: '/img.png' })
const backgroundImage = getBackgroundImage(srcSet)
const style = { height: '100vh', width: '100vw', backgroundImage }
return (
<main style={style}>
<h1>Hello World</h1>
</main>
)
}
```
## Version History
| Version | Changes |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `v15.3.0` | `remotePatterns` added support for array of `URL` objects. |
| `v15.0.0` | `contentDispositionType` configuration default changed to `attachment`. |
| `v14.2.23` | `qualities` configuration added. |
| `v14.2.15` | `decoding` prop added and `localPatterns` configuration added. |
| `v14.2.14` | `remotePatterns.search` prop added. |
| `v14.2.0` | `overrideSrc` prop added. |
| `v14.1.0` | `getImageProps()` is stable. |
| `v14.0.0` | `onLoadingComplete` prop and `domains` config deprecated. |
| `v13.4.14` | `placeholder` prop support for `data:/image...` |
| `v13.2.0` | `contentDispositionType` configuration added. |
| `v13.0.6` | `ref` prop added. |
| `v13.0.0` | The `next/image` import was renamed to `next/legacy/image`. The `next/future/image` import was renamed to `next/image`. A [codemod is available](/docs/app/guides/upgrading/codemods#next-image-to-legacy-image) to safely and automatically rename your imports. `<span>` wrapper removed. `layout`, `objectFit`, `objectPosition`, `lazyBoundary`, `lazyRoot` props removed. `alt` is required. `onLoadingComplete` receives reference to `img` element. Built-in loader config removed. |
| `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 support for `layout="raw"` added. |
| `v12.1.0` | `dangerouslyAllowSVG` and `contentSecurityPolicy` configuration added. |
| `v12.0.9` | `lazyRoot` prop added. |
| `v12.0.0` | `formats` configuration added.<br/>AVIF support added.<br/>Wrapper `<div>` changed to `<span>`. |
| `v11.1.0` | `onLoadingComplete` and `lazyBoundary` props added. |
| `v11.0.0` | `src` prop support for static import.<br/>`placeholder` prop added.<br/>`blurDataURL` prop added. |
| `v10.0.5` | `loader` prop added. |
| `v10.0.1` | `layout` prop added. |
| `v10.0.0` | `next/image` introduced. |
|