Image Component
The Next.js Image component extends the HTML<img> element for automatic image optimization.
import Imagefrom'next/image'exportdefaultfunctionPage() {return ( <Imagesrc="/profile.png"width={500}height={500}alt="Picture of the author" /> )}Reference
Props
The following props are available:
| Prop | Example | Type | Status |
|---|---|---|---|
src | src="/profile.png" | String | Required |
alt | alt="Picture of the author" | String | Required |
width | width={500} | Integer (px) | - |
height | height={500} | Integer (px) | - |
fill | fill={true} | Boolean | - |
loader | loader={imageLoader} | Function | - |
sizes | sizes="(max-width: 768px) 100vw, 33vw" | String | - |
quality | quality={80} | Integer (1-100) | - |
preload | preload={true} | Boolean | - |
placeholder | placeholder="blur" | String | - |
style | style={{objectFit: "contain"}} | Object | - |
onLoadingComplete | onLoadingComplete={img => done())} | Function | Deprecated |
onLoad | onLoad={event => done())} | Function | - |
onError | onError(event => fail()} | Function | - |
loading | loading="lazy" | String | - |
blurDataURL | blurDataURL="data:image/jpeg..." | String | - |
unoptimized | unoptimized={true} | Boolean | - |
overrideSrc | overrideSrc="/seo.png" | String | - |
decoding | decoding="async" | String | - |
src
The source of the image. Can be one of the following:
An internal path string.
<Imagesrc="/profile.png" />An absolute external URL (must be configured withremotePatterns).
<Imagesrc="https://example.com/profile.png" />A static import.
import profilefrom'./profile.png'exportdefaultfunctionPage() {return <Imagesrc={profile} />}Good to know: For security reasons, the Image Optimization API using the defaultloader willnot forward headers when fetching the
srcimage.If thesrcimage requires authentication, consider using theunoptimized property to disable Image Optimization.
alt
Thealt 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 imagewithout changing the meaning of the page. 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 ispurely decorative ornot intended for the user, thealt property should be an empty string (alt="").
Learn more aboutimage accessibility guidelines.
width andheight
Thewidth andheight properties represent theintrinsic image size in pixels. This property is used to infer the correctaspect ratio used by browsers to reserve space for the image and avoid layout shift during loading. It does not determine therendered size of the image, which is controlled by CSS.
<Imagesrc="/profile.png"width={500}height={500} />Youmust set bothwidth andheight properties unless:
- The image is statically imported.
- The image has the
fillproperty
If the height and width are unknown, we recommend using thefill property.
fill
A boolean that causes the image to expand to the size of the parent element.
<Imagesrc="/profile.png"fill={true} />Positioning:
- The parent elementmust assign
position: "relative","fixed","absolute". - By default, the
<img>element usesposition: "absolute".
Object Fit:
If no styles are applied to the image, the image will stretch to fit the container. You can useobjectFit 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
positionandobject-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:
'use client'import Imagefrom'next/image'constimageLoader= ({ src, width, quality })=> {return`https://example.com/${src}?w=${width}&q=${quality||75}`}exportdefaultfunctionPage() {return ( <Imageloader={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 usingClient Components to serialize the provided function.
Alternatively, you can use theloaderFile configuration innext.config.js to configure every instance ofnext/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 generatedsrcset.
import Imagefrom'next/image'exportdefaultfunctionPage() {return ( <divclassName="grid-element"> <Imagefillsrc="/example.png"sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw" /> </div> )}sizes should be used when:
- The image is using the
fillprop - CSS is used to make the image responsive
Ifsizes 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 howsrcset is generated:
- Without
sizes: Next.js generates a limitedsrcset(e.g. 1x, 2x), suitable for fixed-size images. - With
sizes: Next.js generates a fullsrcset(e.g. 640w, 750w, etc.), optimized for responsive layouts.
quality
An integer between1 and100 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.
// Default quality is 75<Imagequality={75} />If you’ve configuredqualities innext.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.
constimageStyle= { borderRadius:'50%', border:'1px solid #fff', width:'100px', height:'auto',}exportdefaultfunctionProfileImage() {return <Imagesrc="..."style={imageStyle} />}Good to know: If you’re using the
styleprop to set a custom width, be sure to also setheight: 'auto'to preserve the image’s aspect ratio.
preload
A boolean that indicates if the image should be preloaded.
// Default preload is false<Imagepreload={false} />true:Preloads the image by inserting a<link>in the<head>.false: Does not preload the image.
When to use it:
- The image is theLargest Contentful Paint (LCP) element.
- The image is above the fold, typically the hero image.
- You want to begin loading the image in the
<head>, before its discovered later in the<body>.
When not to use it:
- When you have multiple images that could be considered theLargest Contentful Paint (LCP) element depending on the viewport.
- When the
loadingproperty is used. - When the
fetchPriorityproperty is used.
In most cases, you should useloading="eager" orfetchPriority="high" instead ofpreload.
priority
Starting with Next.js 16, thepriority property has been deprecated in favor of thepreload property in order to make the behavior clear.
loading
Controls when the image should start loading.
// Defaults to lazy<Imageloading="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.
Useeager only when you want to ensure the image is loaded immediately.
Learn more about the
loadingattribute.
placeholder
Specifies a placeholder to use while the image is loading, improving the perceived loading performance.
// defaults to empty<Imageplaceholder="empty" />empty: No placeholder while the image is loading.blur: Use a blurred version of the image as a placeholder. Must be used with theblurDataURLproperty.data:image/...: Uses theData URL as the placeholder.
Examples:
Learn more about the
placeholderattribute.
blurDataURL
AData URL tobe used as a placeholder image before the image successfully loads. Can be automatically set or used with theplaceholder="blur" property.
<Imageplaceholder="blur"blurDataURL="..." />The image is automatically enlarged and blurred, so a very small image (10px or less) is recommended.
Automatic
Ifsrc is a static import of ajpg,png,webp, oravif file,blurDataURL is added automatically—unless the image is animated.
Manually set
If the image is dynamic or remote, you must provideblurDataURL yourself. To generate one, you can use:
A large blurDataURL may hurt performance. Keep it small and simple.
Examples:
onLoad
A callback function that is invoked once the image is completely loaded and theplaceholder has been removed.
<ImageonLoad={(e)=>console.log(e.target.naturalWidth)} />The callback function will be called with one argument, the event which has atarget that references the underlying<img> element.
Good to know: Using props like
onLoad, which accept a function, requires usingClient Components to serialize the provided function.
onError
A callback function that is invoked if the image fails to load.
<ImageonError={(e)=>console.error(e.target.id)} />Good to know: Using props like
onError, which accept a function, requires usingClient Components to serialize the provided function.
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).
import Imagefrom'next/image'constUnoptimizedImage= (props)=> {// Default is falsereturn <Image {...props}unoptimized />}true: The source image will be served as-is from thesrcinstead 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 updatingnext.config.js with the following configuration:
module.exports= { images: { unoptimized:true, },}overrideSrc
When providing thesrc prop to the<Image> component, both thesrcset andsrc attributes are generated automatically for the resulting<img>.
<Imagesrc="/profile.jpg" /><imgsrcset=" /_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 thesrc attribute generated and you may wish to override it using theoverrideSrc prop.
For example, when upgrading an existing website from<img> to<Image>, you may wish to maintain the samesrc attribute for SEO purposes such as image ranking or avoiding recrawl.
<Imagesrc="/profile.jpg"overrideSrc="/override.jpg" /><imgsrcset=" /_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.
// Default is async<Imagedecoding="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
decodingattribute.
Other Props
Other properties on the<Image /> component will be passed to the underlyingimg element with the exception of the following:
srcSet: UseDevice Sizes instead.
Deprecated props
onLoadingComplete
Warning: Deprecated in Next.js 14, use
onLoadinstead.
A callback function that is invoked once the image is completely loaded and theplaceholder has been removed.
The callback function will be called with one argument, a reference to the underlying<img> element.
'use client'<ImageonLoadingComplete={(img)=>console.log(img.naturalWidth)} />Good to know: Using props like
onLoadingComplete, which accept a function, requires usingClient Components to serialize the provided function.
Configuration options
You can configure the Image Component innext.config.js. The following options are available:
localPatterns
UselocalPatterns in yournext.config.js file to allow images from specific local paths to be optimized and block all others.
module.exports= { images: { localPatterns: [ { pathname:'/assets/images/**', search:'', }, ], },}The example above will ensure thesrc property ofnext/image must start with/assets/images/ and must not have a query string. Attempting to optimize any other path will respond with400 Bad Request error.
Good to know: Omitting the
searchproperty allows all search parameters which could allow malicious actors to optimize URLs you did not intend. Try using a specific value likesearch: '?v=2'to ensure an exact match.
remotePatterns
UseremotePatterns in yournext.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.
module.exports= { images: { remotePatterns: [newURL('https://example.com/account123/**')], },}You can also configureremotePatterns using the object:
module.exports= { images: { remotePatterns: [ { protocol:'https', hostname:'example.com', port:'', pathname:'/account123/**', search:'', }, ], },}The example above will ensure thesrc property ofnext/image must start withhttps://example.com/account123/ and must not have a query string. Any other protocol, hostname, port, or unmatched path will respond with400 Bad Request.
Wildcard Patterns:
Wildcard patterns can be used for bothpathname andhostname 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.
module.exports= { images: { remotePatterns: [ { protocol:'https', hostname:'**.example.com', port:'', search:'', }, ], },}This allows subdomains likeimage.example.com. Query strings and custom ports are still blocked.
Good to know: When omitting
protocol,port,pathname, orsearchthen 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 thesearch property:
module.exports= { images: { remotePatterns: [ { protocol:'https', hostname:'assets.example.com', search:'?v=1727111025337', }, ], },}The example above will ensure thesrc property ofnext/image must start withhttps://assets.example.com and must have the exact query string?v=1727111025337. Any other protocol or query string will respond with400 Bad Request.
loaderFile
loaderFiles allows you to use a custom image optimization service instead of Next.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:
'use client'exportdefaultfunctionmyImageLoader({ src, width, quality }) {return`https://example.com/${src}?w=${width}&q=${quality||75}`}Example:
Alternatively, you can use the
loaderprop to configure each instance ofnext/image.
path
If you want to change or prefix the default path for the Image Optimization API, you can do so with thepath property. The default value forpath is/_next/image.
module.exports= { images: { path:'/my-prefix/_next/image', },}deviceSizes
deviceSizes allows you to specify a list of device width breakpoints. These widths are used when thenext/image component usessizes prop to ensure the correct image is served for the user's device.
If no configuration is provided, the default below is used:
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 ofdevice sizes to form the full array of sizes used to generate imagesrcset.
If no configuration is provided, the default below is used:
module.exports= { images: { imageSizes: [32,48,64,96,128,256,384], },}imageSizes is only used for images which provide asizes prop, which indicates that the image is less than the full width of the screen. Therefore, the sizes inimageSizes should all be smaller than the smallest size indeviceSizes.
qualities
qualities allows you to specify a list of image quality values.
If not configuration is provided, the default below is used:
module.exports= { images: { qualities: [75], },}Good to know: This field is required starting with Next.js 16 because unrestricted access could allow malicious actors to optimize more qualities than you intended.
You can add more image qualities to the allowlist, such as the following:
module.exports= { images: { qualities: [25,50,75,100], },}In the example above, only four qualities are allowed: 25, 50, 75, and 100.
If thequality prop does not match a value in this array, the closest allowed value will be used.
If the REST API is visited directly with a quality that does not match a value in this array, the server will return a 400 Bad Request response.
formats
formats allows you to specify a list of image formats to be used.
module.exports= { images: {// Default formats: ['image/webp'], },}Next.js automatically detects the browser's supported image formats via the request'sAccept header in order to determine the best output format.
If theAccept 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 browserdoes not support AVIF:
module.exports= { images: { formats: ['image/avif'], },}You can also enable both AVIF and WebP formats together. AVIF will be preferred for browsers that support it, with WebP as a fallback:
module.exports= { images: { formats: ['image/avif','image/webp'], },}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.
- When using multiple formats, Next.js will cache each format separately. This means increased storage requirements compared to using a single format, as both AVIF and WebP versions of images will be stored for different browser support.
- If you self-host with a Proxy/CDN in front of Next.js, you must configure the Proxy to forward the
Acceptheader.
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 aStatic Image Import which will automatically hash the file contents and cache the image forever with aCache-Control header ofimmutable.
If no configuration is provided, the default below is used.
module.exports= { images: { minimumCacheTTL:14400,// 4 hours },}You can increase the TTL to reduce the number of revalidations and potentially lower cost:
module.exports= { images: { minimumCacheTTL:2678400,// 31 days },}The expiration (or rather Max Age) of the optimized image is defined by either theminimumCacheTTL or the upstream imageCache-Control header, whichever is larger.
If you need to change the caching behavior per image, you can configureheaders to set theCache-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 keepminimumCacheTTL low. Otherwise you may need to manually change thesrc 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 asimport icon from './icon.png' and then pass that to thesrc 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 yournext.config.js:
module.exports= { images: { disableStaticImages:true, },}maximumRedirects
The default image optimization loader will follow HTTP redirects when fetching remote images up to 3 times.
module.exports= { images: { maximumRedirects:3, },}You can configure the number of redirects to follow when fetching remote images. Setting the value to0 will disable following redirects.
module.exports= { images: { maximumRedirects:0, },}dangerouslyAllowLocalIP
In rare cases when self-hosting Next.js on a private network, you may want to allow optimizing images from local IP addresses on the same network. This is not recommended for most users because it could allow malicious users to access content on your internal network.
By default, the value is false.
module.exports= { images: { dangerouslyAllowLocalIP:false, },}If you need to optimize remote images hosted elsewhere in your local network, you can set the value to true.
module.exports= { images: { dangerouslyAllowLocalIP:true, },}dangerouslyAllowSVG
dangerouslyAllowSVG allows you to serve SVG images.
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 properContent Security Policy (CSP) headers.
We recommend using theunoptimized prop when thesrc prop is known to be SVG. This happens automatically whensrc ends with".svg".
<Imagesrc="/my-image.svg"unoptimized />In addition, it is strongly recommended to also setcontentDispositionType to force the browser to download the image, as well ascontentSecurityPolicy to prevent scripts embedded in the image from executing.
module.exports= { images: { dangerouslyAllowSVG:true, contentDispositionType:'attachment', contentSecurityPolicy:"default-src 'self'; script-src 'none'; sandbox;", },}contentDispositionType
contentDispositionType allows you to configure theContent-Disposition header.
module.exports= { images: { contentDispositionType:'inline', },}contentSecurityPolicy
contentSecurityPolicy allows you to configure theContent-Security-Policy header for images. This is particularly important when usingdangerouslyAllowSVG to prevent scripts embedded in the image from executing.
module.exports= { images: { contentSecurityPolicy:"default-src 'self'; script-src 'none'; sandbox;", },}By default, theloader sets theContent-Disposition header toattachment for added protection since the API can serve arbitrary remote images.
The default value isattachment which forces the browser to download the image when visiting directly. This is particularly important whendangerouslyAllowSVG is true.
You can optionally configureinline 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
remotePatternsin order to protect your application from malicious users.
Similar toremotePatterns, thedomains configuration can be used to provide a list of allowed hostnames for external images. However, thedomains configuration does not support wildcard pattern matching and it cannot restrict protocol, port, or pathname.
Since most remote image servers are shared between multiple tenants, it's safer to useremotePatterns to ensure only the intended images are optimized.
Below is an example of thedomains property in thenext.config.js file:
module.exports= { images: { domains: ['assets.acme.com'], },}Functions
getImageProps
ThegetImageProps 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.
import { getImageProps }from'next/image'const {props }=getImageProps({ src:'https://example.com/image.jpg', alt:'A scenic mountain view', width:1200, height:800,})functionImageWithCaption() {return ( <figure> <img {...props} /> <figcaption>A scenic mountain view</figcaption> </figure> )}This also avoid calling ReactuseState() so it can lead to better performance, but it cannot be used with theplaceholder prop because the placeholder will never be removed.
Known browser bugs
Thisnext/image component uses browser nativelazy loading, 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 withwidth/height ofauto, it is possible to causeLayout Shift on older browsers before Safari 15 that don'tpreserve the aspect ratio. For more details, seethis MDN video.
- Safari 15 - 16.3 display a gray border while loading. Safari 16.4fixed this issue. Possible solutions:
- Use CSS
@supports (font: -apple-system-body) and (-webkit-appearance: none) { img[loading="lazy"] { clip-path: inset(0.6px) } } - Use
loading="eager"if the image is above the fold
- Use CSS
- Firefox 67+ displays a white background while loading. Possible solutions:
- EnableAVIF
formats - Use
placeholder
- EnableAVIF
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:
UseclassName orstyle, notstyled-jsx. In most cases, we recommend using theclassName prop. This can be an importedCSS Module, aglobal stylesheet, etc.
import stylesfrom'./styles.module.css'exportdefaultfunctionMyImage() {return <ImageclassName={styles.image}src="/my-image.png"alt="My Image" />}You can also use thestyle prop to assign inline styles.
exportdefaultfunctionMyImage() {return ( <Imagestyle={{ borderRadius:'8px' }}src="/my-image.png"alt="My Image" /> )}When usingfill, the parent element must haveposition: relative ordisplay: block. This is necessary for the proper rendering of the image element in that layout mode.
<divstyle={{ position:'relative' }}> <Imagefillsrc="/my-image.png"alt="My Image" /></div>You cannot usestyled-jsx because it's scoped to the current component (unless you mark the style asglobal).
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:


import Imagefrom'next/image'import mountainsfrom'../public/mountains.jpg'exportdefaultfunctionResponsive() {return ( <divstyle={{ display:'flex', flexDirection:'column' }}> <Imagealt="Mountains"// Importing an image will// automatically set the width and heightsrc={mountains}sizes="100vw"// Make the image display full width// and preserve its aspect ratiostyle={{ 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:
import Imagefrom'next/image'exportdefaultfunctionPage({ photoUrl }) {return ( <Imagesrc={photoUrl}alt="Picture of the author"sizes="100vw"style={{ width:'100%', height:'auto', }}width={500}height={300} /> )}Try it out:
Responsive image withfill
If you don't know the aspect ratio of the image, you can add thefill prop with theobjectFit prop set tocover. This will make the image fill the full width of its parent container.


import Imagefrom'next/image'import mountainsfrom'../public/mountains.jpg'exportdefaultfunctionFill() {return ( <divstyle={{ display:'grid', gridGap:'8px', gridTemplateColumns:'repeat(auto-fit, minmax(400px, auto))', }} > <divstyle={{ position:'relative', width:'400px' }}> <Imagealt="Mountains"src={mountains}fillsizes="(min-width: 808px) 50vw, 100vw"style={{ objectFit:'cover',// cover, contain, none }} /> </div> {/* And more images in the grid... */} </div> )}Background Image
Use thefill prop to make the image cover the entire screen area:


import Imagefrom'next/image'import mountainsfrom'../public/mountains.jpg'exportdefaultfunctionBackground() {return ( <Imagealt="Mountains"src={mountains}placeholder="blur"quality={100}fillsizes="100vw"style={{ objectFit:'cover', }} /> )}For examples of the Image component used with the various styles, see theImage Component Demo.
Remote images
To use a remote image, thesrc property should be a URL string.
import Imagefrom'next/image'exportdefaultfunctionPage() {return ( <Imagesrc="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 thewidth,height and optionalblurDataURL props manually.
Thewidth andheight attributes are used to infer the correct aspect ratio of image and avoid layout shift from the image loading in. Thewidth andheight donot determine the rendered size of the image file.
To safely allow optimizing images, define a list of supported URL patterns innext.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:
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.
.imgDark {display:none;}@media (prefers-color-scheme: dark) {.imgLight {display:none; }.imgDark {display:unset; }}import stylesfrom'./theme-image.module.css'import Image, { ImageProps }from'next/image'typeProps=Omit<ImageProps,'src'|'preload'|'loading'>& { srcLight:string srcDark:string}constThemeImage= (props:Props)=> {const {srcLight,srcDark,...rest }= propsreturn ( <> <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 usepreloadorloading="eager"because that would cause both images to load. Instead, you can usefetchPriority="high".
Try it out:
Art direction
If you want to display a different image for mobile and desktop, sometimes calledArt Direction, you can provide differentsrc,width,height, andquality props togetImageProps().
import { getImageProps }from'next/image'exportdefaultfunctionHome() {constcommon= { 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> <sourcemedia="(min-width: 1000px)"srcSet={desktop} /> <sourcemedia="(min-width: 500px)"srcSet={mobile} /> <img {...rest}style={{ width:'100%', height:'auto' }} /> </picture> )}Background CSS
You can even convert thesrcSet string to theimage-set() CSS function to optimize a background image.
import { getImageProps }from'next/image'functiongetBackgroundImage(srcSet='') {constimageSet= srcSet.split(', ').map((str)=> {const [url,dpi]=str.split(' ')return`url("${url}")${dpi}` }).join(', ')return`image-set(${imageSet})`}exportdefaultfunctionHome() {const { props: {srcSet }, }=getImageProps({ alt:'', width:128, height:128, src:'/img.png' })constbackgroundImage=getBackgroundImage(srcSet)conststyle= { height:'100vh', width:'100vw', backgroundImage }return ( <mainstyle={style}> <h1>Hello World</h1> </main> )}Version History
| Version | Changes |
|---|---|
v16.0.0 | qualities default configuration changed to[75],preload prop added,priority prop deprecated,dangerouslyAllowLocalIP config added,maximumRedirects config added. |
v15.3.0 | remotePatterns added support for array ofURL objects. |
v15.0.0 | contentDispositionType configuration default changed toattachment. |
v14.2.23 | qualities configuration added. |
v14.2.15 | decoding prop added andlocalPatterns 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 anddomains config deprecated. |
v13.4.14 | placeholder prop support fordata:/image... |
v13.2.0 | contentDispositionType configuration added. |
v13.0.6 | ref prop added. |
v13.0.0 | Thenext/image import was renamed tonext/legacy/image. Thenext/future/image import was renamed tonext/image. Acodemod is available to safely and automatically rename your imports.<span> wrapper removed.layout,objectFit,objectPosition,lazyBoundary,lazyRoot props removed.alt is required.onLoadingComplete receives reference toimg element. Built-in loader config removed. |
v12.3.0 | remotePatterns andunoptimized configuration is stable. |
v12.2.0 | ExperimentalremotePatterns and experimentalunoptimized configuration added.layout="raw" removed. |
v12.1.1 | style prop added. Experimental support forlayout="raw" added. |
v12.1.0 | dangerouslyAllowSVG andcontentSecurityPolicy configuration added. |
v12.0.9 | lazyRoot prop added. |
v12.0.0 | formats configuration added.AVIF support added. Wrapper <div> changed to<span>. |
v11.1.0 | onLoadingComplete andlazyBoundary props added. |
v11.0.0 | src prop support for static import.placeholder prop added.blurDataURL prop added. |
v10.0.5 | loader prop added. |
v10.0.1 | layout prop added. |
v10.0.0 | next/image introduced. |
Was this helpful?