NextJs Image Optimization With Examples

NextJs Image Optimization With Examples

Images play a significant role when it comes to web application development using any framework.

When developing a web application feature, like a JavaScript file uploader, these images should be optimized, as they greatly impact the user experience. Moreover, image optimization is crucial for the SEO rankings of your web app.

Next.js consists of a built-in image component that helps deliver high-performance images using its automatic image optimization features. In this article, we will dive deep into Next.js image optimization with some examples for better understanding.


What Are The Required Props Of The Next.js Image Component?

The Next.js image component has several required props, as well as some additional props which are optional. Following are the required properties of the <Image /> component.

What Are The Required Props Of The Next.js Image Component

SRC

You can pass two types of values to this image src prop. One is a local image file that you imported statically. The other is a path string that contains the URL of an absolute external image or a relative, internal image.

Width and Height

These two properties determine the size that the image appears on a web page. These properties are essential, except for locally imported images and images with the “fill” layout.

These width and height properties correspond to the original or rendered width and height of an image based on its layout.

The intrinsic or fill layout indicates the rendered width and height of an image. Thus, they will determine how large the image will be displayed.

On the other hand, the responsive or fill layout indicates the original dimensions of an image in pixels. Therefore, it will affect the aspect ratio of the image.

alt

The alt prop describes the image and acts as the fallback text of the image, in case it is not loaded due to some error or other reason. This alt text is also helpful for screen readers and search engines to identify the image.

alt


What Are The Optional Props Of Next.js Image Component?

Following are the most widely used optional props of the <Image/> component.

Loader

Loader is a custom function that helps to sort out image URLs. It combines the src, width, and quality prop values into a single URL string and provides the path for an external image. Following is an example of how to use the Loader function.

import Image from ‘next/image'

const exampleLoader = ({ src, width, quality }) => {

  return `https://example.com/${src}?w=${width}&q=${quality || 80}`

}

const ExternalImage = (props) => {

  return (

    <Image

      loader={exampleLoader}

      src=”cat.png”

      alt=”Image of a cat”

      width={350}

      height={350}

    />

  )

}

Fill

This prop accepts a boolean value and will fill the image to cover the parent element when set to “true”. The parent element should have a position relative, fixed, or absolute, while the underlying image element will automatically get the position absolute value.

Sizes

This prop value decides how large the image will be on various breakpoints. It allows users to specify a set of media conditions that tells the browser the size of the image to download when a certain media condition is met. The following code shows how to set the sizes property for a specific image.

import Image from ‘next/image'

const Example = () => (

  <div className=”image-box”>

    <Image

      src=”/nature.png”

      fill

      sizes=”(max-width: 768px) 100vw,

              (max-width: 1200px) 50vw,

              33vw”

    />

  </div>

)

Placeholder

This prop defines the placeholder image to display while the original image is loading. It can have two values, blur or empty, whereas the default value will be empty. When the value is “empty”, it will show an empty space until the actual image is loaded.

On the other hand, the blurDataURL property value will be used as the placeholder if it is set to “blur”. This blurDataURL property value will be automatically generated for locally imported images in .webp, .jpg, .png, and .avif formats.

However, you have to define this blurDataURL property for dynamic images manually.

Priority

When this prop is set to “true”, those images will be given high priority when it comes to loading and preloading.

This prop should be used only on images that are above the fold, and tells the browser to load those images first, as they are more important. Lazy loading will not work on images using this prop. The default value of this prop is set to “false”.

Apart from the above required and additional props, the Next.js image component also accepts some additional props such as style, onLoadingComplete,onLoad, onError, and loading to further enhance the performance of images.


What Are The Things To Consider For Getting A Highly Optimized Next.js Image?

What Are The Things To Consider For Getting A Highly Optimized Next.js Image

As discussed above, Next.js comes with out-of-the-box image optimization capabilities that result in great performance benefits.

However, many users simply use this Next.js image component (<Image/>) without configuring it further and expect a maximum level of optimization. While it will optimize images up to some extent, you can achieve better results by optimizing depending on various other factors.

How to Optimize Remote Images?

When utilizing remote images, you have to define the image URL as a string in the “src” attribute of the image. However, Next.js doesn’t have access to that image at the build time.

Thus, it doesn’t know the width and height properties of the image, and we need to define these image dimensions that the remote image should render.

const remoteImage = “remote-image-url”

<div>

  <Image

    src={remoteImageURL}

    alt=”image of beach”

    width={500}

    height={800}

  />

</div>


How to Handle Remote Images that Blur on Load?

Sometimes, you can see empty spaces on web pages before images are loaded on those areas. It leads to a negative user experience, and the situation gets worse when loading a large number of images simultaneously.

The placeholder and blurDataURL property help eliminate this issue and improve the webpage’s performance. You can set the placeholder property to “blur” to display a blur effect until the image is fully loaded.

Additionally, the blurDataURL property includes the URL of a base64-encoded image of the src image, and it will act as the placeholder until the actual image fully loads. This blurDataURL property only works when the placeholder property is set as “blur”.


Can I Use Local Images?

You can import your local images from the public folder, as shown below. Then Next.js will automatically specify the image dimensions at the build time based on the imported image file.

import localImage from “../public/mountains.jpg”;

import Image from “next/image”;

<div>

  <Image

    src={localImage}

    alt=”Mountain View”

  />

</div>

How to Control the Quality of Images?

How to Control the Quality of Images

The initial images captured through cameras can be of very high quality, resolution, and size as they are used for various purposes. However, when it comes to web development, high-quality images can cause performance issues by increasing the page loading time and thus deliver a bad user experience.

You can slightly reduce quality to optimize an image. In Next.js, you can define the required quality of the image using an integer between 1 to 100. The number 100 refers to the highest quality, whereas 1 refers to the lowest quality. The default value for quality will be 75.

<section>

   <div>

    <Image

      src={localImageurl}

      alt=”Snow Falling”

      width={1000}

      height={750}

      quality={85}

    />

  </div>

</section>


How to Choose the Right Layout Type?

Next.js image component has an optional property called “layout”. There are four main layout types for the images: intrinsic, fixed, responsive, and fill. The behavior of these layouts will change as the size of the viewport changes.

Therefore, the value of this layout property determines how the image appears in different viewport sizes.

The intrinsic layout will reduce the width and height of the images in smaller viewports while maintaining the original dimensions in larger viewports. It is the default value of the layout property.

The fixed layout will not change the image dimensions as the viewport size changes.

The responsive layout will allow the image to scale down as the viewport size reduces, and scale up when the viewport size increases.

However, you should ensure that the parent element of the image is styled as “display: block” to use the responsive layout.

Finally, the fill layout will stretch the image to fit the dimensions of its parent element. The position of the parent element should be set as “relative” and this layout matches well for images with unknown sizes.

Following the image optimization techniques mentioned above and considering the above factors will enable you to best utilize the Next.js image component.


Conclusion

The Next.js image component is an advancement of the native HTML <img> element. Yet, it comes with a wide range of built-in optimization techniques and support for almost all modern image formats.

The highly optimized images gained through Next.js optimization enable users to achieve excellent core web vitals and thus improve the SEO ranking of their apps.

Tag: File Uploader, Image Optimization, JavaScript, JavaScript File Uploader, Nextjs, Nextjs Image, Nextjs Image Uploader

Leave a Reply

Your email address will not be published. Required fields are marked *