Table of contents
1.
Introduction
2.
Using Next/Image API for image optimization in next.js
2.1.
Src
2.2.
Width, height
2.3.
Loader
2.4.
Quality
2.5.
Priority
2.6.
Layouts
2.7.
Placeholder
2.8.
objectFit
2.9.
objectPosition 
2.10.
Unoptimized 
3.
Configuration for the next/image API
4.
Caching in Next/image API
5.
Frequently Asked Questions
6.
Key Takeaway
Last Updated: Mar 27, 2024

Image Optimization using next.js

Author Aditya Kumar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Images are a prominent part of any web application. As the web grows and becomes more competitive, applications require more features like reduced page load time, responsiveness etc., to be able to scale. Developers at Next.js decided to preconfigure such things. We will look at Next/Image API (Application Programming Interface) and see how it handles automatic image optimization in next.js.

Using Next/Image API for image optimization in next.js

“next/image” exports <Image/> component which one can use just like an <img/> tag in HTML. It will automatically handle image optimization in next.js. Let’s look at the below example.

//importing from "next/image"
import Image from 'next/image 
<Image src={temp.jpeg} alt={"similar to <img/>"}/> // rendering an image
You can also try this code with Online Javascript Compiler
Run Code

Let’s discuss some of its props.

Src

In the ‘src’ prop, we can write the source of the image in multiple ways. First is just writing the path string, secondly by statically importing images from the file like below. We can also configure content delivery in the next.config.js file and write the absolute path string in this src prop.

<Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
import VercelImg from './vercel.svg'
<Image src={VercelImg} alt={"similar to <img/>"}/>

Width, height

We can configure the width and height of the image in pixels.

<Image src="/vercel.svg" alt="width and height in pixels" width={72} height={16} />

Loader

It is a function responsible for resolving the URL. Refer to the below example:

const loader = ({ src, width, quality =50}) => {
   return `https://cdn.cloudinary.com/${src}?w=${width}&q=${quality}`
 }
  function LoaderExample() {
   return (
     <Image
       loader={loader}
       src="image"
       height={250}
       width={250}
       quality={100}
     />
   )
 }

Quality

we can define the optimization aspect of the image on a scale of 1 to 100. 

<Image
   src="image"
   alt="alt text"
   width={500}
   height={300}
   quality=50
 />

Priority

This prop is to indicate the preloading of the image. By default, images will get lazily loaded if this tag is not used.

<Image
   src="image"
   alt="alt text"
   width={500}
   height={300}
   priority
 />

Layouts

There can be four options to layout an image:

  • Intrinsic: It automatically scales the image dimensions when viewport sizes reduce but maintains original dimensions in larger viewport sizes.
  • Fixed: The image dimensions will remain fixed even if the viewport size is reduced.
  • Responsive: The image dimensions can scale up with larger viewport sizes and scale down with the reduction in viewport size. It is not limited to the original dimension of the image when scaling up. The parent element must have displayed: block to scale up in dimension.
  • Fill layout: This makes the dimension correspondingly change with the parent’s dimension only when a parent is relatively positioned. Object-fit property is used with fill layout mainly.

Placeholder

This prop is used as a fallback for the duration of image load. It has two properties, namely blur and empty. Empty is specified by default. If we use the blur property, we must select the “blurDataURL” property, used as a placeholder in the original image.

objectFit

It has four values, namely: ‘contain’, ‘cover’, ‘fill’, ‘none’ and ‘scale-down’. It is mostly used with an image whose dimensions are set, or layout=’fill’ property is set.

<Image
   src="image-src"
   alt="image-alt-text"
   layout="fill"
   objectFit="contain"
/>

objectPosition 

It positions the image in the container with a defined width and height, or layout=” fill” is used.

<Image
   src="image-src"
   alt="alt-text"
   layout="fill"
   objectPosition="top left"
/>

Unoptimized 

This prop serves the image without going through any optimization

<Image
   src="image"
   alt="alt text"
   width={500}
   height={300}
   unoptimized
 />

Configuration for the next/image API

Loading images from CDN requires you to set up config in next.config file. Otherwise, it will show an error if you mention the URL to the image in place. One can explicitly mention several domains , device sizes and formats.

module.exports = {
 images: {
   domains: ["picture.com"],
   deviceSizes: [640, 750, 828, 1080, 1440, 3840],
    imageSizes: [16, 32, 128, 256, 384],
   formats: ["image/png", "image/jpeg"],
 },
};

Caching in Next/image API

Images are optimized on load and stored in dist/cache/images. The optimized images will be served until a new cache is generated. We can set the expiration in the minimum cache TTL. If the file we are asking for requests one of the cached files. The old one will be deleted and the new file will be cached to serve in subsequent requests.

One can configure “minimumCacheTTL”, device sizes and images sizes in the next.config file for further optimization.

Image Sampling

Frequently Asked Questions

1.Discuss some features of next/image?

Ans: Features of next/image are:

  • Lazy loading of images resulting in faster page loads
  • Can accept any type of file format and even adopt newer ones coming in the future.
  • The developer needs to just put in the image, and the image optimization in next.js will be automatic, reducing the hassle for him and configuring any way he wants.

2.What is CDN?

Ans: CDN refers to the content delivery network. It is used to serve static assets such as files, videos, images. The link provided in the CDN refers to the nearest servers hosting the data. CDN provides optimisations in images just like image optimization in next.js, performance-boosting to the application. We can also configure CDN like below in the next.config.js

images:{
loader: ‘cloudinary’,
path: ‘https://cdn.com’
}
You can also try this code with Online Javascript Compiler
Run Code

Key Takeaway

Congratulations on getting through this article; we looked at how next.js came up with the problem of image optimization in next.js. This update brought in more developer friendliness and increased SEO rankings to a great extent. Now you will be able to quickly implement and configure the images used in your application.

If you want to learn more about next.js, you can check here Introduction to Next.js.

Happy Learning!

Live masterclass