Largest Contentful Paint (LCP) in Next.js app router
August 6th 2024
1. Largest Contentful Paint (LCP): This is a key metric for measuring web performance. It marks the point in the page load timeline when the largest text block or image element is rendered on the screen. The faster this happens, the better the user experience.
2. Next.js and the Image Component: Next.js has a built-in <Image>
component designed for optimized image serving. It does things like lazy-loading (loading images as they’re about to enter the viewport) by default, which is great for performance.
3. The Warning Message: Next.js is telling you that the image at /path_to_image/
is the largest contentful paint on your page. However, because it’s not marked with priority
, it may not be loading as quickly as it could, potentially impacting user experience.
Why Does This Matter?
Performance: If your largest image loads slowly, it can delay the time it takes for your page to appear fully loaded, impacting user experience and SEO.
Priority Property: Adding
priority
to an image in Next.js tells the framework to preload this image so that it loads faster.
Finding and Fixing the Image
Identifying the Image: The warning gives you the path to the image, for example /_next/static/media/big_image.78fchghd.png
. This is a hashed version of the file name, which Next.js generates during the build process. To find the original image in your codebase, look for an image file named something like big_image.png
(the exact name might vary).
Locating the Image in Your Code: Search through your codebase for where this image is used. It’s likely within a <Image>
component from Next.js. If your project isn’t too large, a simple file search for the filename (without the hash and extension) should locate it.
Updating the Image Component: Once you find the image, add the priority
attribute.For example:
import { CSSProperties } from 'react';
import Image from 'next/image';
interface OptimizedImageProps {
src: string;
alt: string;
}
export default function OptimizedImage({ src, alt }: OptimizedImageProps) {
return (
<div style={containerStyle}>
<Image
src={src}
alt={alt}
fill
sizes="100vw"
priority
/>
</div>
);
}
const containerStyle: CSSProperties = {
position: 'relative',
width: '100%',
aspectRatio: '16 / 9',
};
// const imageStyle: CSSProperties = {
// objectFit: 'cover',
// };
4. Testing:
After making this change, run your app and monitor the performance. The warning should no longer appear, and the LCP should improve.
Remember, the priority
attribute should be used sparingly and only for critical, above-the-fold content, as preloading too many images can also harm performance.