Optimize, Enhance, Boost! 🚀 Exploring Next/Image in Next.js for better Web Performance!

Written by
Dwi Nugroho
Dwi Nugroho
Published on
Comments
Optimize, Enhance, Boost! 🚀 Exploring Next/Image in Next.js for better Web Performance!

👋 Recently, I unleashed my personal website – krafan.com, showcasing my musings and an assortment of projects in the form of a portfolio. Imagine my surprise when I decided to put my website through the paces using the nifty tool at pagespeed and found my website performance score at 82.

pagespeed score
pagespeed score

Digging into the diagnostics provided by pagespeed, the main culprit unveiled itself – the images on my website were larger than necessary.

diagnostic
diagnostic

Picture this: a user visiting your site on their mobile device expecting an image of 400px × 200px, and you hit them with a whopping 2000px × 1000px image. That's a colossal 5x larger than what your users really need. So, let's dive into the realm of supercharging image optimization on your Next.js website using the incredible power of next/image.

Images take up 50% of the total bytes on web pages.- Next.js

Unleashing the Power of next/image! 🚀

So, what's the buzz about next/image, and why should you care? Well, next/image is a built-in component in Next.js, making its grand entrance with the release of Next.js version 10.0.0 in October 2020. Why is it a game-changer for your Next.js website? Simple – images often pose a significant challenge to a website's performance, and the existing solutions are either costly, complex, or both. Now, let's dive into the wonders that next/image brings to the table!

Lazy Loading 🎩

By default, next/image embraces lazy loading, meaning your images will only be loaded when they are about to enter the user's viewport. It's like magic – optimizing load times and user experience.

Preloading 🚀

Even though lazy loading is the default, you can elevate the priority of certain images by using the priority prop. This ensures that crucial images are preloaded before the browser tackles other rendering tasks.

Automatic Image Resizing 📏

Say goodbye to the hassle of manual resizing! With next/image, images can automatically adjust to smaller sizes based on the user's screen. It's a seamless way to enhance performance without sacrificing quality.

Format Transformation for Modern Browsers 🔄

This one's a game-changer! next/image automatically transforms JPEG, PNG, or another format files into the more modern WebP format, potentially reducing image sizes by around 30% for users whose browsers support WebP.

Implementation Unveiled! 🛠️

Now, let's get our hands dirty and explore how we can seamlessly implement the Next.js Image Component. Brace yourself for an exhilarating journey into the realm of developer experience!

Getting Started

Before the advent of next/image, we'd handle images like this:

<img src="/image.jpg" width="160" height="160" alt="your image title">

Now, with the magic of next/image, it's as easy as importing the component and transforming your HTML <img> element:

import Image from 'next/image'
 
export default MyComponent() {
  return (
    <Image
      src="/image.jpg"
      width={160}
      height={160}
      alt="your image title"
    >
  )
}
 

Pro Tips 🚀

If you prefer fixed-size images, the approach above works like a charm. But what if you're into responsive images? Fear not, here's a slick method for you:

import Image from 'next/image'
 
export default MyComponent() {
  return (
    <div className="w-full aspect-square relative">
      <Image
        src="/image.jpg"
        fill
        sizes="100%"
        className="relative w-full h-full object-cover"
        alt="your image title"
      >
    </div>
  )
}

In this example, I've thrown in some TailwindCSS for good measure. Take note that the parent element must have a relative position and a fixed aspect ratio. This ensures that the loaded image adheres to the parent's dimensions.

⚠️ Caution: Image Format Magic Ahead!

If you desire to load your images in modern formats like WebP, a bit of magic needs to happen in your next.config.js. Add the following snippet:

module.exports = {
  images: {
    formats: ['image/avif', 'image/webp'],
  },
}

Incorporate this wisdom, and watch your images dazzle in the world of modern formats.

The Behind-the-Scenes of next/image! 🎬

So, what's the magic happening behind the curtain when you unleash the next/image Component? Let's peel back the layers and uncover the captivating process!

In a nutshell, the Next.js Image Component shoots a request back to the Next.js backend, armed with the values from the src prop and other essential tidbits. The backend then flexes its muscles with some image processing wizardry – we're talking format transformations, size tweaks, quality adjustments, and more.

This enchanting image processing dance is choreographed by none other than the Sharp module. It's the behind-the-scenes maestro that orchestrates the visual symphony.

Once the backend has worked its magic, the transformed image is handed back to the client, ready to make its grand debut on the user's screen. And there you have it – the seamless, behind-the-scenes spectacle of the Next.js Image Component in action! 🌈✨

The Power of Optimization! 💪

Now, the moment of truth! After diving into the world of image optimization with next/image, let's unveil the dazzling results of this performance overhaul.

result
result

Surprisingly, my website's performance score skyrocketed to a solid 95 points! 🚀 Just imagine the impact – from a decent 82 to a stellar 95. These numbers speak volumes about the significance of how we handle image loading on our websites. Witnessing this leap in performance, it's crystal clear – the way we load images plays a pivotal role in shaping the user experience.

🚀 Conclusion: Elevating Your Next.js Image Game!

In the dynamic world of web development, optimizing images is not just a good practice; it's a game-changer for performance. 🌐✨ After delving into the intricacies of Next.js Image Component, the results are nothing short of spectacular.

  1. Performance Soars: Witnessing my website's performance score soar from 82 to a staggering 95 was like watching a rocket launch! 🚀🌟
  2. Seamless Implementation: Implementing the Next.js Image Component was a breeze, revolutionizing the way images are handled on my site. 🛠️🖼️
  3. Format Magic: Unleashing the magic of WebP format through the next.config.js snippet added a modern twist to image loading. 🎩✨
  4. Behind-the-Scenes Wizardry: The Sharp module's behind-the-scenes wizardry in image processing brought a visual symphony to my website. 🎬🔍

🌐 Sources

Edit on GitHub
Gradient background
Gradient background
Gradient background