Blog>
Snippets

Caching Images with Next.js for Faster Load Times

Implement caching strategies for images in Next.js by setting appropriate Cache-Control headers to reduce the number of image requests.
import { useRouter } from 'next/router';
import Image from 'next/image';

export default function MyImageComponent({ src, alt }) {
  const router = useRouter();

  return (
    <Image
      src={src}
      alt={alt}
      width={500} // Adjust the size accordingly
      height={300} // Adjust the size accordingly
      quality={75} // Lower quality images load faster
      loader={({ src, width, quality }) => {
        return `${src}?w=${width}&q=${quality || 75}&FM=jpg`;
      }}
    />
  );
}
This Next.js component uses the 'next/image' component for optimized image serving. The custom loader function appends query parameters to the image request, which can be used to control the format and quality of the image served, enabling cache efficiency at the CDN or browser level.
module.exports = {
  images: {
    domains: ['your-image-domain.com'],
    deviceSizes: [640, 768, 1024, 1280, 1600],
    imageSizes: [16, 32, 48, 64, 96],
    path: '/_next/image',
    loader: 'default'
  },
  async headers() {
    return [
      {
        // Apply these headers to all routes in your application.
        source: '/(.*)',
        headers: [
          {
            key: 'Cache-Control',
            value: 'public, max-age=31536000, immutable',
          },
        ],
      },
    ];
  },
};
This snippet is the Next.js configuration in 'next.config.js' for setting the Cache-Control headers to a long max-age. This tells the browser and CDNs to cache the images for a long time, reducing the load times for repeat visits.