Simple Tutorial on Image Optimization in Next.js

Share with a friend:

Next.js, a popular React framework, comes with a powerful built-in component called next/image that streamlines image optimization for your web applications. In this tutorial, we’ll explore the benefits of using next/image and provide a step-by-step guide on how to integrate it into your Next.js project.



Introduction to Next Image Optimization

Images often constitute a substantial portion of a website’s page weight, impacting loading performance. Next.js addresses this issue by introducing the next/image component. This extension of the HTML <img> element offers several key benefits:

  • Faster Page Loads: Images are loaded only when they come into view.
  • Size Optimization: Automatically serves appropriately sized images based on the user’s device
  • Visual Stability: Prevents layout shifts during image loading.

To learn more about Next Image benefits visit here.

Next Image Features and Properties

The Next.js <Image> component offers powerful features for optimizing and displaying images in web applications. It provides a seamless way to enhance performance and accessibility while maintaining visual quality. The main properties of the <Image> component are:

  1. src: This property specifies the source of the image. It can be either a statically imported image file or a path string, which can be an absolute external URL or an internal path, depending on the loader prop.
  2. width: Determines the rendered width of the image in pixels.
  3. height: Specifies the rendered height of the image in pixels.
  4. alt: The alt property is crucial for accessibility, describing the image for screen readers and search engines. It also serves as fallback text if images are disabled or fail to load.
  5. loader: An optional custom function that resolves image URLs. It takes parameters like src, width, and quality to return a URL string for the image.
  6. fill: A boolean property that allows the image to fill its parent element, which is useful when the width and height are unknown.
  7. sizes: Similar to a media query, this property provides information about how wide the image will be at different breakpoints. It greatly affects performance, especially for images using fill or those styled for responsive sizes.
  8. quality: This property sets the quality of the optimized image as an integer between 1 and 100, with 100 being the best quality and resulting in a larger file size.
  9. priority: When set to true, the image is considered high priority and preloaded. This disables lazy loading and is particularly useful for optimizing Largest Contentful Paint (LCP) elements.
  10. placeholder: Defines the type of placeholder to use while the image is loading. Options include “blur” for a blurred placeholder and an empty string for no placeholder.

For the Next Image component, src, width, height and alt are all required props. That is to say, if you do not specify them, you will get an error. However, for the height and width props, there is an exception for statically imported images or images with the fill property.

These properties provide comprehensive control over how images are displayed, ensuring a seamless and optimized user experience. However, Next offers even more useful props for the Image component. You may find them on the official Next Image API page.

Using A Statically Imported Image

To incorporate a statically imported image or local image, start by importing it and next/image into your component.

import Image from 'next/image'
import catPic from '../public/cat.png'

Next, simply use the Next Image Component:

export default function MyPage() {
  return (
    <Image
      src={catPic}
      alt="Picture of my cat"
      // width={250} (automatically determined)
      // height={250} (automatically determined)
    />
  )
}

Using a Remote Image

When using a remote image, the src property should be a URL string. Since Next.js doesn’t have access to remote files during the build process, you’ll need to manually specify the width, height, and optional blurDataURL props.

import Image from 'next/image'

export default function MyPage() {
  return (
    <Image
      src="https://my-external-domain.com/cat.png"
      alt="Picture of my cat"
      width={500} // width must be provided
      height={500} // height must be provided
    />
  )
}

To securely optimize remote images, define a list of supported URL patterns in next.config.js by using remotePatterns.

module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'my-external-domain.com',
      },
    ],
  },
}

To learn more about remote patterns visit here.

Image Sizing Strategies

Improperly sized images can lead to a performance problem known as a Cumulative Layout Shift. Next.js addresses this issue by providing three sizing options:

  1. Automatic Sizing: Achieved through static import.
  2. Explicit Sizing: Specify width and height properties.
  3. Implicit Sizing: Use fill to expand the image to fill its parent element.

If you’re unsure about the image dimensions when retrieving images from an external source, consider using the fill property.

Priority Load Images

Adding the priority property to the image that will be the Largest Contentful Paint (LCP) element for each page is recommended. This prioritizes the image for loading, potentially leading to a significant boost in LCP.

export default function MyPage() {
  return (
    <Image
      src={catPic}
      alt="Picture of my cat"
      width={250} 
      height={250}
      priority
    />
  )
}

Styling Next Image

Styling the next/image component is similar to styling a regular <img> element. Use the className or style props.

Conclusion

Now that you have a comprehensive understanding of next/image, it’s time to start optimizing your images and delivering an exceptional user experience!

Share with a friend:

Rajae Robinson

Rajae Robinson is a young Software Developer with over 3 years of work experience building websites and mobile apps. He has extensive experience with React.js and Next.js.

Recent Posts