Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Image (Legacy)

This is a legacy API and no longer recommended. It's still supported for backward compatibility.
Last updated November 21, 2025

Starting with Next.js 13, thenext/image component was rewritten to improve both the performance and developer experience. In order to provide a backwards compatible upgrade solution, the oldnext/image was renamed tonext/legacy/image.

Warning:next/legacy/image is deprecated and will be removed in a future version of Next.js. Please usenext/image instead.

Comparison

Compared tonext/legacy/image, the newnext/image component has the following changes:

  • Removes<span> wrapper around<img> in favor ofnative computed aspect ratio
  • Adds support for canonicalstyle prop
    • Removeslayout prop in favor ofstyle orclassName
    • RemovesobjectFit prop in favor ofstyle orclassName
    • RemovesobjectPosition prop in favor ofstyle orclassName
  • RemovesIntersectionObserver implementation in favor ofnative lazy loading
    • RemoveslazyBoundary prop since there is no native equivalent
    • RemoveslazyRoot prop since there is no native equivalent
  • Removesloader config in favor ofloader prop
  • Changedalt prop from optional to required
  • ChangedonLoadingComplete callback to receive reference to<img> element

Required Props

The<Image /> component requires the following properties.

src

Must be one of the following:

When using the defaultloader, also consider the following for source images:

  • When src is an external URL, you must also configureremotePatterns
  • When src isanimated or not a known format (JPEG, PNG, WebP, AVIF, GIF, TIFF) the image will be served as-is
  • When src is SVG format, it will be blocked unlessunoptimized ordangerouslyAllowSVG is enabled

width

Thewidth property can represent either therendered width ororiginal width in pixels, depending on thelayout andsizes properties.

When usinglayout="intrinsic" orlayout="fixed" thewidth property represents therendered width in pixels, so it will affect how large the image appears.

When usinglayout="responsive",layout="fill", thewidth property represents theoriginal width in pixels, so it will only affect the aspect ratio.

Thewidth property is required, except forstatically imported images, or those withlayout="fill".

height

Theheight property can represent either therendered height ororiginal height in pixels, depending on thelayout andsizes properties.

When usinglayout="intrinsic" orlayout="fixed" theheight property represents therendered height in pixels, so it will affect how large the image appears.

When usinglayout="responsive",layout="fill", theheight property represents theoriginal height in pixels, so it will only affect the aspect ratio.

Theheight property is required, except forstatically imported images, or those withlayout="fill".

Optional Props

The<Image /> component accepts a number of additional properties beyond those which are required. This section describes the most commonly-used properties of the Image component. Find details about more rarely-used properties in theAdvanced Props section.

layout

The layout behavior of the image as the viewport changes size.

layoutBehaviorsrcSetsizesHas wrapper and sizer
intrinsic (default)Scaledown to fit width of container, up to image size1x,2x (based onimageSizes)N/Ayes
fixedSized towidth andheight exactly1x,2x (based onimageSizes)N/Ayes
responsiveScale to fit width of container640w,750w, ...2048w,3840w (based onimageSizes anddeviceSizes)100vwyes
fillGrow in both X and Y axes to fill container640w,750w, ...2048w,3840w (based onimageSizes anddeviceSizes)100vwyes
  • Demo theintrinsic layout (default)
    • Whenintrinsic, the image will scale the dimensions down for smaller viewports, but maintain the original dimensions for larger viewports.
  • Demo thefixed layout
    • Whenfixed, the image dimensions will not change as the viewport changes (no responsiveness) similar to the nativeimg element.
  • Demo theresponsive layout
    • Whenresponsive, the image will scale the dimensions down for smaller viewports and scale up for larger viewports.
    • Ensure the parent element usesdisplay: block in their stylesheet.
  • Demo thefill layout
    • Whenfill, 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 theobjectFit property.
    • Ensure the parent element hasposition: relative in their stylesheet.
  • Demo background image

loader

A custom function used to resolve URLs. Setting the loader as a prop on the Image component overrides the default loader defined in theimages section ofnext.config.js.

Aloader is a function returning a URL string for the image, given the following parameters:

Here is an example of using a custom loader:

import Imagefrom'next/legacy/image'constmyLoader= ({ src, width, quality })=> {return`https://example.com/${src}?w=${width}&q=${quality||75}`}constMyImage= (props)=> {return (    <Imageloader={myLoader}src="me.png"alt="Picture of the author"width={500}height={500}    />  )}

sizes

A string that provides information about how wide the image will be at different breakpoints. The value ofsizes will greatly affect performance for images usinglayout="responsive" orlayout="fill". It will be ignored for images usinglayout="intrinsic" orlayout="fixed".

Thesizes property serves two important purposes related to image performance:

First, the value ofsizes is used by the browser to determine which size of the image to download, fromnext/legacy/image's automatically-generated source set. When the browser chooses, it does not yet know the size of the image on the page, so it selects an image that is the same size or larger than the viewport. Thesizes property allows you to tell the browser that the image will actually be smaller than full screen. If you don't specify asizes value, a default value of100vw (full screen width) is used.

Second, thesizes value is parsed and used to trim the values in the automatically-created source set. If thesizes property includes sizes such as50vw, which represent a percentage of the viewport width, then the source set is trimmed to not include any values which are too small to ever be necessary.

For example, if you know your styling will cause an image to be full-width on mobile devices, in a 2-column layout on tablets, and a 3-column layout on desktop displays, you should include a sizes property such as the following:

import Imagefrom'next/legacy/image'constExample= ()=> (  <divclassName="grid-element">    <Imagesrc="/example.png"layout="fill"sizes="(max-width: 768px) 100vw,              (max-width: 1200px) 50vw,              33vw"    />  </div>)

This examplesizes could have a dramatic effect on performance metrics. Without the33vw sizes, the image selected from the server would be 3 times as wide as it needs to be. Because file size is proportional to the square of the width, withoutsizes the user would download an image that's 9 times larger than necessary.

Learn more aboutsrcset andsizes:

quality

The quality of the optimized image, an integer between1 and100 where100 is the best quality. Defaults to75.

priority

When true, the image will be considered high priority andpreload. Lazy loading is automatically disabled for images usingpriority.

You should use thepriority property on any image detected as theLargest Contentful Paint (LCP) element. It may be appropriate to have multiple priority images, as different images may be the LCP element for different viewport sizes.

Should only be used when the image is visible above the fold. Defaults tofalse.

placeholder

A placeholder to use while the image is loading. Possible values areblur orempty. Defaults toempty.

Whenblur, theblurDataURL property will be used as the placeholder. Ifsrc is an object from astatic import and the imported image is.jpg,.png,.webp, or.avif, thenblurDataURL will be automatically populated.

For dynamic images, you must provide theblurDataURL property. Solutions such asPlaiceholder can help withbase64 generation.

Whenempty, there will be no placeholder while the image is loading, only empty space.

Try it out:

Advanced Props

In some cases, you may need more advanced usage. The<Image /> component optionally accepts the following advanced properties.

style

Allowspassing CSS styles to the underlying image element.

Note that alllayout modes apply their own styles to the image element, and these automatic styles take precedence over thestyle prop.

Also keep in mind that the requiredwidth andheight props can interact with your styling. If you use styling to modify an image'swidth, you must set theheight="auto" style as well, or your image will be distorted.

objectFit

Defines how the image will fit into its parent container when usinglayout="fill".

This value is passed to theobject-fit CSS property for thesrc image.

objectPosition

Defines how the image is positioned within its parent element when usinglayout="fill".

This value is passed to theobject-position CSS property applied to the image.

onLoadingComplete

A callback function that is invoked once the image is completely loaded and theplaceholder has been removed.

TheonLoadingComplete function accepts one parameter, an object with the following properties:

loading

The loading behavior of the image. Defaults tolazy.

Whenlazy, defer loading the image until it reaches a calculated distance fromthe viewport.

Wheneager, load the image immediately.

Learn more

blurDataURL

AData URL tobe used as a placeholder image before thesrc image successfully loads. Only takes effect when combinedwithplaceholder="blur".

Must be a base64-encoded image. It will be enlarged and blurred, so a very small image (10px orless) is recommended. Including larger images as placeholders may harm your application performance.

Try it out:

You can alsogenerate a solid color Data URL to match the image.

lazyBoundary

A string (with similar syntax to the margin property) that acts as the bounding box used to detect the intersection of the viewport with the image and trigger lazyloading. Defaults to"200px".

If the image is nested in a scrollable parent element other than the root document, you will also need to assign thelazyRoot prop.

Learn more

lazyRoot

A ReactRef pointing to the scrollable parent element. Defaults tonull (the document viewport).

The Ref must point to a DOM element or a React component thatforwards the Ref to the underlying DOM element.

Example pointing to a DOM element

import Imagefrom'next/legacy/image'import Reactfrom'react'constExample= ()=> {constlazyRoot=React.useRef(null)return (    <divref={lazyRoot}style={{ overflowX:'scroll', width:'500px' }}>      <ImagelazyRoot={lazyRoot}src="/one.jpg"width="500"height="500" />      <ImagelazyRoot={lazyRoot}src="/two.jpg"width="500"height="500" />    </div>  )}

Example pointing to a React component

import Imagefrom'next/legacy/image'import Reactfrom'react'constContainer=React.forwardRef((props, ref)=> {return (    <divref={ref}style={{ overflowX:'scroll', width:'500px' }}>      {props.children}    </div>  )})constExample= ()=> {constlazyRoot=React.useRef(null)return (    <Containerref={lazyRoot}>      <ImagelazyRoot={lazyRoot}src="/one.jpg"width="500"height="500" />      <ImagelazyRoot={lazyRoot}src="/two.jpg"width="500"height="500" />    </Container>  )}

Learn more

unoptimized

When true, the source image will be served as-is from thesrc instead of changing quality, size, or format. Defaults tofalse.

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)=> {return <Image {...props}unoptimized />}

Since Next.js 12.3.0, this prop can be assigned to all images by updatingnext.config.js with the following configuration:

next.config.js
module.exports= {  images: {    unoptimized:true,  },}

Other Props

Other properties on the<Image /> component will be passed to the underlyingimg element with the exception of the following:

Configuration Options

Remote Patterns

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 theremotePatterns property in yournext.config.js file, as shown below:

next.config.js
module.exports= {  images: {    remotePatterns: [      {        protocol:'https',        hostname:'example.com',        port:'',        pathname:'/account123/**',        search:'',      },    ],  },}

Good to know: The example above will ensure thesrc property ofnext/legacy/image must start withhttps://example.com/account123/ and must not have a query string. Any other protocol, hostname, port, or unmatched path will respond with 400 Bad Request.

Below is an example of theremotePatterns property in thenext.config.js file using a wildcard pattern in thehostname:

next.config.js
module.exports= {  images: {    remotePatterns: [      {        protocol:'https',        hostname:'**.example.com',        port:'',        search:'',      },    ],  },}

Good to know: The example above will ensure thesrc property ofnext/legacy/image must start withhttps://img1.example.com orhttps://me.avatar.example.com or any number of subdomains. It cannot have a port or query string. Any other protocol or unmatched hostname will respond with 400 Bad Request.

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

The** syntax does not work in the middle of the pattern.

Good to know: When omittingprotocol,port,pathname, orsearch then the wildcard** is implied. This is not recommended because it may allow malicious actors to optimize urls you did not intend.

Below is an example of theremotePatterns property in thenext.config.js file usingsearch:

next.config.js
module.exports= {  images: {    remotePatterns: [      {        protocol:'https',        hostname:'assets.example.com',        search:'?v=1727111025337',      },    ],  },}

Good to know: The example above will ensure thesrc property ofnext/legacy/image must start withhttps://assets.example.com and must have the exact query string?v=1727111025337. Any other protocol or query string will respond with 400 Bad Request.

Domains

Warning: Deprecated since Next.js 14 in favor of strictremotePatterns in order to protect your application from malicious users. Only usedomains if you own all the content served from the domain.

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.

Below is an example of thedomains property in thenext.config.js file:

next.config.js
module.exports= {  images: {    domains: ['assets.acme.com'],  },}

Loader Configuration

If you want to use a cloud provider to optimize images instead of using the Next.js built-in Image Optimization API, you can configure theloader andpath prefix in yournext.config.js file. This allows you to use relative URLs for the Imagesrc and automatically generate the correct absolute URL for your provider.

next.config.js
module.exports= {  images: {    loader:'imgix',    path:'https://example.com/myaccount/',  },}

Customizing the Built-in Image Path

If you want to change or prefix the default path for the built-in Next.js image optimization, you can do so with thepath property. The default value forpath is/_next/image.

next.config.js
module.exports= {  images: {    path:'/my-prefix/_next/image',  },}

Built-in Loaders

The following Image Optimization cloud providers are included:

  • Default: Works automatically withnext dev,next start, or a custom server
  • Vercel: Works automatically when you deploy on Vercel, no configuration necessary.Learn more
  • Imgix:loader: 'imgix'
  • Cloudinary:loader: 'cloudinary'
  • Akamai:loader: 'akamai'
  • Custom:loader: 'custom' use a custom cloud provider by implementing theloader prop on thenext/legacy/image component

If you need a different provider, you can use theloader prop withnext/legacy/image.

Images can not be optimized at build time usingoutput: 'export', only on-demand. To usenext/legacy/image withoutput: 'export', you will need to use a different loader than the default.Read more in the discussion.

Advanced

The following configuration is for advanced use cases and is usually not necessary. If you choose to configure the properties below, you will override any changes to the Next.js defaults in future updates.

Device Sizes

If you know the expected device widths of your users, you can specify a list of device width breakpoints using thedeviceSizes property innext.config.js. These widths are used when thenext/legacy/image component useslayout="responsive" orlayout="fill" to ensure the correct image is served for user's device.

If no configuration is provided, the default below is used.

next.config.js
module.exports= {  images: {    deviceSizes: [640,750,828,1080,1200,1920,2048,3840],  },}

Image Sizes

You can specify a list of image widths using theimages.imageSizes property in yournext.config.js file. These widths are concatenated with the array ofdevice sizes to form the full array of sizes used to generate imagesrcsets.

The reason there are two separate lists is that 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 in imageSizes should all be smaller than the smallest size in deviceSizes.

If no configuration is provided, the default below is used.

next.config.js
module.exports= {  images: {    imageSizes: [32,48,64,96,128,256,384],  },}

Acceptable Formats

The defaultImage Optimization API will automatically detect 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 isanimated), the Image Optimization API will fallback to the original image's format.

If no configuration is provided, the default below is used.

next.config.js
module.exports= {  images: {    formats: ['image/webp'],  },}

You can enable AVIF support, which will fallback to the original format of the src image if the browserdoes not support AVIF:

next.config.js
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:

next.config.js
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 and then 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 theAccept header.

Caching Behavior

The following describes the caching algorithm for the defaultloader. For all other loaders, please refer to your cloud provider's documentation.

Images are optimized dynamically upon request and stored in the<distDir>/cache/images directory. The optimized image file will be served for subsequent requests until the expiration is reached. When a request is made that matches a cached but expired file, the expired image is served stale immediately. Then the image is optimized again in the background (also called revalidation) and saved to the cache with the new expiration date.

The cache status of an image can be determined by reading the value of thex-nextjs-cache (x-vercel-cache when deployed on Vercel) response header. The possible values are the following:

  • MISS - the path is not in the cache (occurs at most once, on the first visit)
  • STALE - the path is in the cache but exceeded the revalidate time so it will be updated in the background
  • HIT - the path is in the cache and has not exceeded the revalidate time

The expiration (or rather Max Age) is defined by either theminimumCacheTTL configuration or the upstream imageCache-Control header, whichever is larger. Specifically, themax-age value of theCache-Control header is used. If boths-maxage andmax-age are found, thens-maxage is preferred. Themax-age is also passed-through to any downstream clients including CDNs and browsers.

  • You can configureminimumCacheTTL to increase the cache duration when the upstream image does not includeCache-Control header or the value is very low.
  • You can configuredeviceSizes andimageSizes to reduce the total number of possible generated images.
  • You can configureformats to disable multiple formats in favor of a single image format.

Minimum Cache TTL

You can 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.

next.config.js
module.exports= {  images: {    minimumCacheTTL:14400,// 4 hours  },}

You can increase the TTL to reduce the number of revalidations and potentially lower cost:

next.config.js
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<distDir>/cache/images.

Disable Static 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:

next.config.js
module.exports= {  images: {    disableStaticImages:true,  },}

Dangerously Allow SVG

The defaultloader does not optimize SVG images for a few reasons. First, SVG is a vector format meaning it can be resized losslessly. Second, SVG has many of the same features as HTML/CSS, which can lead to vulnerabilities without properContent Security Policy (CSP) headers.

Therefore, we recommended using theunoptimized prop when thesrc prop is known to be SVG. This happens automatically whensrc ends with".svg".

However, if you need to serve SVG images with the default Image Optimization API, you can setdangerouslyAllowSVG inside yournext.config.js:

next.config.js
module.exports= {  images: {    dangerouslyAllowSVG:true,    contentDispositionType:'attachment',    contentSecurityPolicy:"default-src 'self'; script-src 'none'; sandbox;",  },}

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.

contentDispositionType

The defaultloader 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.

next.config.js
module.exports= {  images: {    contentDispositionType:'inline',  },}

Animated Images

The defaultloader will automatically bypass Image Optimization for animated images and serve the image as-is.

Auto-detection for animated files is best-effort and supports GIF, APNG, and WebP. If you want to explicitly bypass Image Optimization for a given animated image, use theunoptimized prop.

Version History

VersionChanges
v16.0.0next/legacy/image deprecated and will be removed in a future version of Next.js. Please usenext/image instead.
v13.0.0next/image renamed tonext/legacy/image

Was this helpful?

supported.

[8]ページ先頭

©2009-2026 Movatter.jp