Image optimization is an important factor in SEO. Optimized images ensure your website visitors have optimal performance and user experience, especially on mobile devices. They help to load your site faster on slow devices and preserve bandwidth.
The image component in next.js can optimize images on-demand as well as build time. It takes care of resizing, optimizing, and serving images to browsers in the most efficient manner regardless of the device type and screen size. Image component also eliminates the Cumulative Layout Shift, a Core Web Vital that google plan to factor in.
It is overly simple to use the Image tag. Just import
import Image from 'next/image'
function Post() {
return (
<>
<h1>How to optimize images</h1>
<Image src="/photo.jpg" alt="Nextjs optimized image" width={240} height={400} />
</>
)
}
export default Post;
Referring to cross-domain images
The
module.exports = {
images: {
domains: ['mystaticimagehost.com'],
},
}
When the image is hosted on a different domain, Next optimizes the image on demand at the request time. It is important to note that the above entry in the next.config.js is required to use cross-domain images in your Nextjs image component.
import Image from 'next/image'
function Post() {
return (
<>
<h1>How to optimize images</h1>
<Image src="https://www.mystaticimagehost.com/photo.jpg" alt="Nextjs optimized image" width={240} height={400} />
</>
)
}
export default Post;