Habilelabs-Logo
Blog

Next.js Automatic Image Optimization with next/image Component

October 26th, 2021 . 8 minutes read
Blog featured image

A picture is worth 1000 phrases, and images are a vital a part of the online platforms to connect with the users. Defining them in their maximum fundamental shape and finishing with the standard element is straightforward:

Ordinarily, we embed the source image, photo.jpg, into a web page, assuming the photo is inside the equal listing because of the HTML web page.

You may — and you have to — cross in addition to this canonical form of image definition by including an alternative textual content (alt) that describes if image cannot be loaded the alt render on browser:

But with images on the web, the fact that the web advanced, so did the need for image optimization, whether it’s for person or developer stories.

To make sure that we serve the users with the greatest photo available, it is important to address the elements like photograph length, internet formats, and responsiveness.


Fixing for the users’ need is practicable through the <img> element’s plethora of APIs for optimization, but they can emerge unwieldy to unpack. This is where automated photo optimization can benefit developers.

Next.js 10 Brings a New Automated Image Optimization Feature

Frameworks like Next.js introduce to resolve most common, complex tasks, mundane, and like routing, internalization, and photograph optimization.

According to the team, Next.js intends to improve two things: developer and person experiences. And even as most of the optimization makes a specialty of reducing the amount of JavaScript shipped to customers, there are other components like pics that need optimization as well.

Next.js 10 welcomed a photograph optimization API, next/image, as a canonical shape for native automated photo optimization, impart built integrated 5 bless.

  • Improved user experience: With optimized pictures having lazy loaded, by default, users can assume an overall performance enhancement in website load time, in the long run improving the general user experience.
  • Good developer experience: With Next picture’s simple-to-use API, developers have a progressed experience themselves with the capacity to outline a basic photograph, tweak it to their heart’s content material, or delve into superior configuration alternatives like caching and loaders.
  • Unaffected build times: Construct instances aren’t increased as a facet-impact of optimization because Next.js optimizes images on-demand as users request them, in place of at construct-time.
  • Modern image techniques and formats: Images are lazy-loaded by default and may be served in model formats like WebP in supported browsers.
  • Future-proof: Next.js also can mechanically adopt destiny image formats and serve them to browsers that help those formats.

Using the next/image API

The next/photo API is the candy spot of photograph optimization in next.js. It exposes an ‘Error! Filename not specified’ component as a conventional unmarred-supply of truth, this indicates you to discover ways to use one API to deal with picture optimization in Next.js.

In its maximum fundamental form, the issue ‘Error! Filename is not specified’ is fundamentally just like the HTML <img> detail because they both be given a src and alt characteristic/property:

The functionality of the <Image/> component can extend with a number of props available in it. Let’s take a look at them-

src prop

The src is the single source of truth for the <Image/> component. It must be one of the following, when used with the image:

  1. A course string as an inner route, just like the code snippet above, depending on the loader.
  2. A route string as an absolute outside URL with area options set in next.config.js
  3. A statically imported image file

In this case, we will import a static image file:

Width and height props

We measure the width of a photo in pixels, except for statically imported photos or images having prop format to fill:

Loader prop

The loader prop is a custom function that resolves URLs. Given the quality, width, and src parameters, it will return a URL string-

Sizes prop

The sizes prop specifies the size attribute of HTML img element.

Above code shows that if the viewport is less than 500px, use 1000px width for source. With the <Image/> component, you can specify the sizes like the following-

Do not forget to define sizes simplest when the usage of a responsive or fill layout.

Quality prop

The quality prop provides an integer range between 1 to 100 which defines the quality of the optimized image; 1 being the worst quality and one hundred being the best quality.

 It defaults to 75:

Priority prop

Images are not prioritized by default (due to the fact they are lazy-loaded), which means priority defaults to false. When priority is true, then image is considered high-priority and preloaded.

This need to only be used when the photo is visible above the fold-

Layout prop

The layout prop controls the layout behavior of the image according to size of the viewport changes. The value received is a string of intrinsic, fixed, responsive, or fill.

Each building value has its own nuances in:

  1. The generated srcSet and sizes
  2. Expected display or position value on the parent element for the corresponding <Image/> element on which they’re used
  3. Sometimes must pair with other props for proper behavior

Placeholder prop

When the image loads, the placeholder is used as a fallback image. The possible values for it are blur or empty.

Its default value is empty, that indicates no placeholder while the image is loading, only empty space.

However, when used blur, the blurDataURL property acts as the placeholder. It automatically populates when static import with the MIME-type, i.e., png, jpg, WebP, and blurDataURL.

ObjectFit prop

The objectFit prop is like an object-fit CSS property that determines how large an image should be in size to fit its container. It is used with layout=fill or an image with define width and height and its possible values are- cover, fill, none, and scale-down-

ObjectPosition prop

The objectPosition prop is like object-position CSS property that defines the position of an image in its container. This prop is used with layout=fill or an image with width and height and also with position value-

loading prop

The loading prop is like to the HTML img element’s loading attribute which are used for lazy loading. The likely value is a string of lazy or eager:

onLoadingComplete prop

The onLoadingComplete prop is a callback function that executes immediately after the image completely loads and the placeholder is removed:

blurDataURL prop

In others words, blurDataURL prop is placeholder image and one must remember that it will be a base64-encoded data URL image that only works when used  combination with  placeholder=“blur”:

When images imported statically, it will be automatically provided. When import dynamic or remote images, you should provide width, height, and blurDataURL manually.

lazyBoundary prop

The lazyBoundary prop acts as the marginal threshold for detecting intersections before triggering lazy loading. It defaults to 200px.

unoptimized prop

The unoptimized prop, when true, acts as a replacement for changing quality, size, or format-

Caveat with other properties

In addition to the properties listed above, other properties passed to the <Image/> component will transfer to the basic img object other than the following:

  1. Decoding is always “async”
  2. Use onLoadingComplete for ref
  3. For srcSet, use deviceSizes instead
  4. Use className for style

Conclusion

Image functionality in Next.js enhances the user experience with a traditional game-changing and easy-to-use and flexible API. This unintentionally solves the great need for Core Web Vitals and helps websites gain higher SEO rankings, all starting and ending next/image.

Thanks for reading!

Read More-

Author: Pushpendra Singh
Share: