Part 56: Optimizing Product Images with Next.js: A Guide

[Pages] Responsive Design and Image Optimisation

[Pages] Responsive Design and Image Optimisation

In our quest to improve the performance and user experience of our application, we're turning our attention to how we display product images. Previously, we used standard HTML img elements to render these images. While functional, this approach isn't optimal; it downloads images at their original size, which is often larger than necessary. Plus, all images load immediately when the page is loaded, even if they're not visible on the screen yet. This can slow down our site, especially when dealing with a large number of images.

Thankfully, Next.js offers a robust solution through its Image Optimization features. Let's explore how we can leverage these features to enhance our product image rendering.

Introducing the Next.js Image Component

Next.js provides an Image component that automatically optimizes images. This component resizes images to fit the specified dimensions, converts them to efficient formats like WebP, and implements lazy loading, which defers loading images until they are visible on the screen.

Step 1: Replacing the Standard HTML img Element

First, let's replace the standard img element in our ProductCard component with the Next.js Image component. This component is part of the next/image module.

// components/ProductCard.js

import Image from 'next/image';
import Link from 'next/link';

function ProductCard({ product }) {
  return (
    <div className="border w-80 shadow hover:shadow-xl">
      <Link href={`/products/${product.id}`}>
        <Image src={product.pictureUrl} alt={product.title} width={320} height={240} />
        <div className="p-2 flex justify-between items-baseline">
          <h2 className="text-lg font-bold">
            {product.title}
          </h2>
          <span>
            {product.price}
          </span>
        </div>
      </Link>
    </div>
  );
}

export default ProductCard;

By specifying the width and height as numbers, we inform the Next.js server how to resize these images.

Step 2: Configuring Image Domains

Upon saving, you might encounter an error indicating that the hostname is not configured. This is a security measure, requiring us to specify which domains our server can fetch images from. We configure this in the next.config.js file.

// next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  images: {
    domains: ['localhost'], // Add your image source domain(s) here
  },
};

module.exports = nextConfig;

Make sure to replace 'localhost' with the domain where your images are hosted, if different.

Step 3: Restarting the Development Server

After updating the configuration, remember to restart your development server. The configuration changes won't take effect until you do so.

The Benefits of Using Next.js Image Component

Once implemented, the Next.js Image component brings several advantages:

  1. Optimized Sizes: Images are resized on-demand to fit the dimensions specified, reducing download times. On high-resolution displays, such as Retina, images are served at double the specified size to maintain quality.

  2. Modern Formats: Images are converted to efficient formats like WebP, which reduces file size compared to traditional formats like JPEG.

  3. Lazy Loading: Only images visible on the screen are loaded initially. As users scroll down, additional images are loaded dynamically, improving initial page load speed.

  4. Caching: Resized images are cached by the Next.js server, meaning subsequent requests for the same image are served from the cache, further improving performance.

Conclusion

By utilizing the Next.js Image component, we've significantly enhanced our application’s efficiency in handling product images. This not only speeds up load times but also provides a seamless user experience, especially on pages with numerous images. Simply swapping out the img element for the Next.js Image component allows us to leverage these optimizations with minimal effort.

Last updated