Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Next.js Tutorial
  • Next.js Components
  • Next.js Functions
  • Next.js Deployment
  • Next.js Projects
  • Next.js Routing
  • Next.js Styles
  • Next.js Server-Side Rendering
  • Next.js Environment Variables
  • Next.js Middleware
  • Next.js Typescript
  • Next.js Image Optimization
  • Next.js Data Fetching
Open In App
Next Article:
Next.js Image Optimization
Next article icon

Next.js Image Optimization

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Next.js provides built-in support for image optimization to improve the performance of your web applications. By using the next/image component, you can automatically optimize images on-demand as the users request them, ensuring fast load times and better user experiences.

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

Table of Content

  • Core Web Vitals
  • Image Optimization
    • 1. Image load:
    • 2. Priority pro:
    • 3. Image Sizing:
    • 4. ObjectFit prop:
    • 5. Placeholder prop:
    • 6. Quality prop:
  • Conclusion

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.
Note: <Image/> is similar to HTML <img> element both accept src and alt.

Steps 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 

Project structure:

 

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

import Image from "next/image";

Image Optimization

The Image component in nextjs automatically optimize the images added in the application. But it also provide some properties to specificly optimize the Images.

PropertyTypeRequiredDescription
srcstringYesThe path or URL to the image.
altstringYesDescriptive text for the image, used for accessibility.
widthnumberYesThe width of the image in pixels.
heightnumberYesThe height of the image in pixels.
qualitynumber (1-100, default: 75) NoThe quality of the optimized image.
priorityboolean(default: false)NoIf true, the image will be considered high priority and preloaded.
placeholderblur, emptyNoSpecifies a placeholder while the image is loading.
blurDataURLstringNoA base64-encoded image used as a placeholder if placeholder="blur".
unoptimizedboolean (default: false)NoIf true, the image will not be optimized.
loaderfunctionNoA custom function for loading the image, allowing integration with a third-party image provider.
onLoadingCompletefunctionNoA callback function that is called when the image has finished loading.

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 pro:

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:

Conclusion

Next.js Image Optimization significantly improves web performance by optimizing images on demand, supporting responsive images, lazy loading, and the WebP format. This built-in feature ensures that your website loads faster and provides a better user experience with minimal configuration.


Next Article
Next.js Image Optimization

M

madhekaramar
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • ReactJS
  • Next.js

Similar Reads

    Next.js Bundle Optimization to improve Performance
    In this article, We will learn various ways to improve the performance of the NextJS bundle which results in increasing the performance of NextJS applications in Google PageSpeed Insights or Lighthouse. As per the documentation, NextJS is a React framework that gives you the building blocks to creat
    6 min read
    Next JS Image Optimization: Best Practices for Faster Loading
    Large and unoptimized images can impact a website's performance on loading time. Optimizing images is necessary to improve the performance of the website. Next.js provides built-in support for image optimization to automate the process, providing a balance between image quality and loading speed. Pr
    4 min read
    How to import image in Next.js ?
    Next.js is a full-stack React-based framework. Unlike a traditional react app, which loads and renders the entire application on the client, Next.js allows the first-page load to be rendered by the server, which is great for SEO and performance. Some of the key features of Next.js are:  Server-side
    4 min read
    How To Optimize Images in Vite Projects?
    Optimizing images is an important step in improving the performance of your web projects, and Vite, being a modern front-end build tool, makes it easy to simplify this process.Image optimization reduces file sizes, resulting in faster load times, better user experience, and improved SEO rankings. Th
    3 min read
    p5.js Image mask() Method
    The mask() method of p5.Image in p5.js library is used to apply the given mask to the image. This is done by using the alpha channel of the mask image as the alpha channel of this image. Syntax: mask( srcImage ) Parameters: This function accepts a single parameter as mentioned above and described be
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences