Image optimization is an essential 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 and build time. It takes care of resizing, optimizing, and serving images to browsers efficiently, regardless of the device type and screen size. The 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 next/image
, and you are all set to optimize images in your application.
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 in Next js
The src
is the location of the image. If my images are hosted on an external website, I can use the absolute URL of the externally hosted image with the src property.
To achieve this, I must add the external hostname
to the next.config.js file
.
If you don't have this file, you can create it at the root of your next application, at the same level as the package.json
file.
module.exports = {
images: {
domains: ['mystaticimagehost.com'],
},
}
If the image is hosted on a different domain, Next optimizes the image on demand. That happens at the time of the request.
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;
If I have multiple hosts for images, I must list them in the domains
property as a comma-seperated list.
module.exports = {
images: {
domains: ['mystaticimagehost.com', 'myotherstaticimagehost.com'],
},
}