Step 5 of 21 (24% complete)
Image Loader for Next.js
Step Code
The code for this specific step can be found on the following branch:
Click on a link to view the code for this step on GitHub.
Why Use a CDN for Images
CDNs like Cloudinary improve your website by:
- Faster loading: Images are served from servers closer to your users
- Automatic optimization: Resize, compress, and convert formats on-the-fly
- Scalability: Handle traffic spikes without performance issues
- Reliability: Keep your images available even during server issues
Setting Up a Custom Image Loader
1. Configure Next.js
Add this to your next.config.ts
:
import type { NextConfig } from 'next' const nextConfig: NextConfig = { images: { domains: ['res.cloudinary.com'], loader: 'custom', loaderFile: './lib/image/loader.ts', } } export default nextConfig
This configuration sets up the custom image loader and defines the necessary security headers .
2. Create the Loader
// lib/image/loader.ts export default function cloudinaryLoader({ src, width, quality = 80 }: { src: string; width: number; quality?: number; }) { if (src.startsWith('https://res.cloudinary.com')) { // Skip if URL already has parameters if (src.includes('f_') || src.includes('c_')) { return src; } // Extract cloud name and image ID const cloudName = extractCloudName(src); const publicId = extractPublicId(src); // Don't transform SVGs const params = src.endsWith('.svg') ? '' : `/f_auto,c_limit,w_${width},q_${quality}/`; return `https://res.cloudinary.com/${cloudName}/image/upload${params}${publicId}`; } return src; } // Helper functions would be defined here
3. Use in Your Components
import Image from 'next/image'; function MyImage() { return ( <Image src="https://res.cloudinary.com/your-cloud-name/image/upload/your-image.jpg" alt="Description of the image" width={500} height={300} /> ); }
The loader automatically optimizes your Cloudinary images based on the width and quality you specify.
Key Benefits
- Automatic optimization: Images are resized and compressed on-the-fly
- Format conversion: Serves modern formats like WebP to supported browsers
- Reduced bandwidth: Only loads the size needed for each device
- Better performance: Faster page loads and improved Core Web Vitals
For more details, see the Next.js Image documentation.
Have questions? I'm here to help!