Home > References > SEO

Next js image optimization with image component

Last updated : February 17, 2021

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 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

The src is the location of the image. If your images are hosted on an external website, you can use the absolute URL of the externally hosted image with src property. To achieve this, you need to add the external hostname to the next.config.js file. If you don't have this file, you can create it in the root of your next application, at the same level as the package.json file.

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;
Lance
By: Lance
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Leave a comment

No Comments