Before moving forward, we recommend you to read Image Optimization first.
Image Optimization can be enabled via the Image
component exported by next/image
.
For an example, consider a project with the following files:
pages/index.js
public/me.png
We can serve an optimized image like so:
import Image from 'next/image'
function Home() {
return (
<>
<h1>My Homepage</h1>
<Image
src="/me.png"
alt="Picture of the author"
width={500}
height={500}
/>
<p>Welcome to my homepage!</p>
</>
)
}
export default Home
The Image
component requires the following properties.
The path or URL to the source image. This is required.
When using an external URL, you must add it to domains in next.config.js
.
The width of the image, in pixels. Must be an integer without a unit.
Required unless layout="fill"`.
The height of the image, in pixels. Must be an integer without a unit.
Required unless layout="fill"`.
The Image
component optionally accepts the following properties.
The layout behavior of the image as the viewport changes size. Defaults to intrinsic
.
When fixed
, the image dimensions will not change as the viewport changes (no responsiveness) similar to the native img
element.
When intrinsic
, the image will scale the dimensions down for smaller viewports but maintain the original dimensions for larger viewports.
When responsive
, the image will scale the dimensions down for smaller viewports and scale up for larger viewports.
When fill
, the image will stretch both width and height to the dimensions of the parent element, usually paired with object-fit.
Try it out:
fixed
layoutintrinsic
layoutresponsive
layoutfill
layoutA string mapping media queries to device sizes. Defaults to Device Sizes.
The quality of the optimized image, an integer between 1 and 100 where 100 is the best quality. Defaults to 75.
When true, the image will be considered high priority and preload.
Should only be used when the image is visible above the fold. Defaults to false.
In some cases, you may need more advanced usage. The Image
component optionally accepts the following advanced properties.
The image fit when using layout="fill"
.
The image position when using layout="fill"
.
The loading behavior of the image. Defaults to lazy
.
When lazy
, defer loading the image until it reaches a calculated distance from the viewport.
When eager
, load the image immediately.
When true, the source image will be served as-is instead of changing quality, size, or format. Defaults to false.
Other properties on the Image
component will be passed to the underlying img
element with the exception of the following:
style
. Use className
instead.srcSet
. Use Device Sizes instead.decoding
. It is always "async"
.For more information on what to do next, we recommend the following sections: