Open In App

Next.js Image Optimization

Last Updated : 24 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

For image optimization, NextJS provides an image component which is extension of the HTML element <img>. NextJS provides some built-in optimization to achieve good Core Web Vitals

Let us first understand what Core Web Vitals is: It is a set of standardized metrics that help to measure user experience on the web. These metrics score how quickly the page content loads. 

There are three Core Web Vitals:

  1. Largest Contentful Paint (LCP)
  2. First Input Delay (FID)
  3. Cumulative Layout Shift (CLS)

1. Largest Contentful Paint (LCP): It measures the time in seconds and how quickly the web page’s primary content is loaded. Basically, it measures the time from when the page loads until the image is rendered. Lower the LCP better the result. We can improve the LCP by optimizing the rendering path, CSS, and images.

 

2. First Input Delay (FID): It measures the time from when you click on the link to when they respond. We can improve FID by reducing JavaScript execution time and the impact of third-party code.

 

3. Cumulative Layout Shift (CLS): CLS measures how many times a web page has shifted, basically, It is used to calculate the visual stability of a web page. We can improve CLS by including width and height attributes on your image.

 

Some built-in image optimization API(next/image) provided by NextJS include:

  1. Improved user experience: Load images lazily or eagerly which boosts the performance of website load time.
  2. Good developer experience: Provide options like Caching and loaders.
  3. Visual Stability: Prevent CLS automatically.
  4. Boosting LCP: NextJS provide priority property to the image for loading.
  5. Responsive: NextJS does it automatically if we set the responsive property in the layout.

Image Component in NextJS: <image/>is similar to HTML <img> element both accept src and alt.

Steps require to run NextJS and its Image component:

Step 1: NodeJS should be installed on your computer. To know how to install NodeJS click here.

Step 2: Create a new file and change the directory to the created file. Use the below command in the terminal:

cd file_name

Step 3: Create the Next app using the below command:

npx create-next-app app_name 

Step 4: Project structure should look like this:

 

Step 5: Import the image component in pages/index.js

import Image from "next/image";

Image Optimization:

1. Image load: We can specify the loading behavior of the image and when you scroll down the next image automatically loads. There are two types of loading:

  1. eager: Loads image immediately.
  2. lazy: By default in the image component. Loading until an image is visible. 

Example:

Javascript




import Image from "next/image";
 
const index = () => {
    return (
        <>
            <h1 style={{ color: 'green' }}>GeeksForGeeks</h1>
            <Image src="/gfgg.png" alt="Loading"
                width={500}
                height={550}
                loading="eager"
            />
        </>
    );
};
export default index;


Note: eager is not good for optimization use priority prop instead.

Step to run the application: Run your Next app using the following command:

npm run dev

Output:

 

2. Priority prop: Sometimes we need to preload the crucial images in advance using priority = {true} which leads to a boost in LCP.

Example:

Javascript




//Priority prop
import Image from "next/image";
 
const index = () => {
    return (
        <>
            <h1 style={{ color: 'green' }}>GeeksForGeeks</h1>
            <Image src="/gfgg.png" alt="Loading"
                width={500}
                height={550}
                priority={true}
            />
        </>
    );
};
export default index;


3. Image Sizing: As we have seen to improve CLS we need to include the width and height of the image. This allows the browser to preserve space for the image before it loads. If you don’t know the image size, you can use layout = “fill”. 

layout = “fill” responds to its parent dimensions

The layout provides four values:

  1. fill
  2. intrinsic
  3. responsive
  4. fixed

Example:

Javascript




import Image from "next/image";
 
const index = () => {
    return (
        <>
            <h1 style={{ color: 'green' }}>GeeksForGeeks</h1>
            <Image src="/gfgg.png" alt="Loading"
                layout="fill"
            />
        </>
    );
};
export default index;


Output:

 

4. ObjectFit prop: It is used with layout = “fill”. It sets how an image should resize to fit in the container.

Objectfit provides four values:

  1. contain
  2. cover
  3. fill
  4. none

Example:

Javascript




//ObjectFit
import Image from "next/image";
 
const index = () => {
    return (
        <>
            <h1 style={{ color: 'green' }}>GeeksForGeeks</h1>
            <Image src="/gfgg.png" alt="Loading"
 
                layout="fill"
                objectFit="contain"
 
            />
        </>
    );
};
export default index;


Output:

 

5. Placeholder prop: It is used as a fallback image when an image is loading. It is also called a temporary alternative or loading indicator. The placeholder indicates that the image is being loaded.

Placeholder provides two values:

  1. blur
  2. empty

Example:

Javascript




//Placeholder
import Image from "next/image";
 
const index = () => {
    return (
        <>
            <h1 style={{ color: 'green' }}>GeeksForGeeks</h1>
            <Image src="/gfgg.png" alt="Loading"
                width={600}
                height={450}
 
                placeholder="blur"
                blurDataURL="data:image/png;base64,[IMAGE_CODE_FROM_PNG_PIXEL]"
 
            />
        </>
    );
};
export default index;


Output:

 

6. Quality prop: We can define the quality of the image by providing values between 1 to 100. The default value is 75.

 

In the above image, we can see “http://localhost:3000/_next/image?url=/gfgg.png&w=640&q=75”

q= 75 which is the default value of quality.

We can adjust the value of quality by using the command like this:

quality="100"

Example:

Javascript




//Quality of the image
import Image from "next/image";
 
const index = () => {
    return (
        <>
            <h1 style={{ color: 'green' }}>GeeksForGeeks</h1>
            <Image src="/gfgg.png" alt="Loading"
                width={500}
                height={550}
                quality="100"
            />
        </>
    );
};
export default index;


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads