Skip to content

Exploring the Hidden Gems of the Next Image Component: What You Might Be Overlooking

Exploring the Hidden Gems of the Next Image Component: What You Might Be Overlooking

Welcome to a journey of discovery where we'll explore the often-overlooked capabilities of the Next.js Image component. At first glance, this component might seem like a straightforward tool, merely enhancing performance compared to a regular img tag. However, there's more to it than meets the eye. In this blog post, we'll uncover the magic of some features of the Next.js Image component. It's easy to use, yes, but it also packs a punch with features that go beyond simple image rendering. These hidden features can significantly impact your project, and missing them could mean not fully utilizing the component's potential. Let's dive into this exploration, unraveling the subtle yet powerful aspects of the Next.js Image component that are easy to overlook. So, without further delay, let's get started!

Size

First up, let's chat about width and height. These are rules for how big your image shows on the screen. You gotta use them most of the time. But hey, if you're pulling in an image directly into your code (that's what we call 'static importing') or you want your image to just fill up whatever space it's in (using the 'fill' prop), then you can skip these rules. Neat, right? But that's not all there's to it. You see, when Next.js fetches the image from the server, it does something behind the scenes. It doesn’t just grab any size of the image. Instead, Next.js is smart and picks the best size that fits the spot on your webpage. This means your images load faster and look just right, whether on a big desktop screen or a small phone screen. It's like having a personal assistant for your images, making sure they are always looking their best and not slowing down your site. Here's a part that's easy to miss: Next.js uses a feature called 'srcset' to decide which image size to download from the server. By default, Next.js uses the following default:

module.exports = {
images: {
	imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
}

So, imagine you have an image that's 75 pixels wide. Next.js will look at this list and pick the closest size. In our case, with these default settings, it would download the 96-pixel version. This occurs because Next.js selects the smallest available size from the list that exceeds the original's width, ensuring the image remains clear on all devices; even if your image is a bit smaller or larger, Next.js picks the nearest size from this list.

This is important to know because if you are looking to get the most performant image possible, you should be aware of these size values. By understanding how Next.js selects the image size, you can better tailor your images to match these presets. This way, you ensure that your site is not only loading the appropriate image size for different devices but also optimizing for speed and efficiency. Keeping an eye on these sizes helps you balance between image quality and fast loading times, which is key for a great user experience on your site.

Quality

Now, let's highlight something about image quality. It's often overlooked, but by default, Next.js sets the image quality to 75. Sure, you can tweak this with the quality prop, but here's the catch: bumping up the quality to 100 will significantly increase the image's file size. This means your images will look super sharp, but they'll also take longer to load. It's all about finding that sweet spot where your images look great without slowing down your website. Remember, a faster site often means a better experience for your visitors.

My advice is to always check what is better for you in each situation. Ask yourself: Consider whether it's more beneficial to opt for larger images at a slightly reduced quality, in alignment with the “srcset” configurations we explored, or if it's preferable to enhance the image quality, even if it means working with smaller dimensions? It's a balancing act. Usually, cranking up the quality to 100 isn't the best move because it makes the image file really big, which can slow down your site. It's all about making smart choices. Go for a quality that makes your images look good without burdening your site's load time. Sometimes, a slightly lower quality image, but well optimized, can be way more effective than a perfect but sluggish, high-quality image.

Loader

The loader prop in Next.js is a key player. It's not just about fetching images; it’s about fetching them smartly and securely. When using images from different places, like a CMS or your server, the loader prop helps you manage them efficiently and safely.

For instance, say you have images on Contentful. Next.js doesn't automatically know the best way to fetch these, but with a custom loader, you can define this process. This loader optimizes your images, selecting the right format, width, and quality. Your images not only look great but load faster, too.

Remember, when fetching images from external sources, it's crucial to use remotePatterns (inside your next.config file) for security reasons. This ensures your site stays safe while handling images from outside.

This approach is scalable and saves time. You set up the loader once, and it works for all your images, making your site efficient and your code neat.

Here’s an example:

// Here's our custom loader for Contentful images
export function contentfulLoader({ src, width, quality }) {
  // We prepare the URL for Contentful
  const normalizedSrc = `https://${src.substring(
    src.indexOf("images.ctfassets.net/"),
  )}`;
  const url = new URL(normalizedSrc);
  // Setting format, width, and quality
  url.searchParams.set("fm", "webp");
  url.searchParams.set("w", width.toString());
  url.searchParams.set("q", (quality || 75).toString());
  return url.href;
}

// And this is our overall custom image loader
export default function customImageLoader({ src, width, quality }) {
  // It decides which loader to use based on the image source
  if (src?.includes("images.ctfassets.net/")) {
    return contentfulLoader({ src, width, quality });
  }
  // If it's not a Contentful image, just return the source
  return src;
}
// next.config.js file

module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "images.ctfassets.net",
      },
    ],
    formats: ["image/avif", "image/webp"],
    loader: "custom",
    loaderFile: "./src/loaders/imageLoader.js",
  },

}

Placeholder Prop

A little-known yet impactful feature of the Next.js Image component is the placeholder prop. It's all about improving the user experience while your images are loading. Imagine visiting a website and waiting for images to load – it can be a bit dull, right? The placeholder prop can make this wait a lot more pleasant. You can use this prop to display a blur effect or a solid color before the image fully loads. This creates a smoother visual experience. The blur placeholder is particularly popular because it gives a sneak peek of the image without revealing all the details. It's like a teaser, building anticipation for what's to come. Here’s how you can use it:

<Image
  src="your-image.jpg"
  alt="Description"
  placeholder="blur"
  blurDataURL="data:image/..." // a small preview of your image
/>

In this example, blurDataURL is a small, low-quality version of your image that loads much faster. Once the actual image is ready, it seamlessly replaces the blur. This approach significantly enhances the perceived loading speed and keeps your users engaged.

Incorporating the placeholder prop can make a big difference in how professional and polished your site feels, especially on slower connections where image load times are noticeable.

Conclusion

The Next.js Image component is a powerful tool that goes beyond simple image rendering. By understanding its hidden features and capabilities, you can optimize your project for performance and user experience. From utilizing the 'width' and 'height' properties to ensuring the right image quality and using the 'loader' prop for efficient image fetching, there are several aspects to consider. Additionally, the 'placeholder' prop can enhance the user experience by displaying a blur effect or solid color while images load. By exploring these often-overlooked features, you can unlock the full potential of the Next.js Image component and create a more engaging and optimized website.

This Dot is a consultancy dedicated to guiding companies through their modernization and digital transformation journeys. Specializing in replatforming, modernizing, and launching new initiatives, we stand out by taking true ownership of your engineering projects.

We love helping teams with projects that have missed their deadlines or helping keep your strategic digital initiatives on course. Check out our case studies and our clients that trust us with their engineering.

Let's innovate together!

We're ready to be your trusted technical partners in your digital innovation journey.

Whether it's modernization or custom software solutions, our team of experts can guide you through best practices and how to build scalable, performant software that lasts.

Prefer email? hi@thisdot.co