Next.js is built with performance as a core principle, especially with its App Router approach. Two important parts of making a website work well are making the images and fonts easy to see and read. Unoptimized images can make pages bigger and slower to load. Unoptimized fonts can lead to “Flash of Unstyled Text” (FOUT) or “Flash of Invisible Text” (FOIT). This can create a bad user experience.
The latest versions of Next.js, especially when using the App Router, offer strong, built-in ways to deal with these problems effectively.
Image Optimization
The Next.js next/image component is a useful addition to the standard HTML tag. It automatically optimizes images for performance and visual stability. In the App Router, it works perfectly and is highly recommended.
The Next.js component extends the HTML element to provide:
Responsive Images: Automatically serves correctly sized images for different device viewports and resolutions using modern image formats like WebP reducing file size without compromising quality.
Lazy Loading: Images are lazy-loaded by default, meaning they only load when they enter the viewport, improving initial page load times.
Prevent Layout Shift: Automatically adds width and height properties (or infers them from static imports), reserving space for the image before it loads to prevent layout shifts.
Example Usage:
Local Image: For images placed in your public directory, you can import them directly, and Next.js will handle the width and height automatically.
// public/image.jpg
export default function Page() {
return (
<Image
src={'/image.jpg'}
alt="Description of my image"
// width and height are automatically determined for static imports
// placeholder="…."
/>
);
}
Remote Image:
If the images are hosted on a different website (for example, if they come from a CDN or CMS), you need to manually set the width and height. This will prevent any changes to the layout. You also need to configure remotePatterns in next.config.js for security.
// app/page.js
import Image from 'next/image';
export default function MyPage() {
return (
<Image
src="https://example.com/image.png"
alt="Description"
width={800} // Actual width of the image
height={600} // Actual height of the image
priority // Optional: Use for LCP images (above the fold) to preload
/>
);
}
More in https://medium.com/@sehouli.hamza/image-and-font-optimization-in-next-js-app-router-a-deep-dive-with-examples-3c6fab942f5c-3c6fab942f5c
Top comments (0)