Next.js Performance: Core Web Vitals and Load Speed
A Next.js application can be slow for reasons that have nothing to do with the framework's defaults. A 400 KB charting library imported at the top level of a client component, an unoptimized hero image served as a 3 MB PNG, or a font that blocks rendering for 800 ms can each undo every built-in optimization the App Router provides. Performance work in Next.js is therefore less about flipping switches and more about measuring what the user actually experiences, then removing the specific bottleneck the measurement reveals.
This lesson gives you a repeatable workflow: define the metrics that matter, instrument the app so you can see real-user numbers, fix the four most common bottlenecks in Next.js projects, and verify each change with evidence instead of intuition.
Prerequisites
- !Comfort with the App Router and Server vs Client Components
- !Experience with next/image and next/font at a basic level
- !A local Next.js project you can run and profile
What You'll Learn
- 1Explain what LCP, INP, and CLS measure and typical Next.js causes of each
- 2Configure next/image and next/font for fast first paint
- 3Lazy-load heavy client-only code with dynamic imports
- 4Run a bundle analysis pass and remove the largest avoidable dependencies
The metrics that actually gate your traffic
Google's Core Web Vitals are field metrics collected from real browsers, not lab scores from a single run. Largest Contentful Paint (LCP) measures when the biggest visible element — usually the hero image or headline — finishes rendering; the target is under 2.5 seconds. Interaction to Next Paint (INP) replaced FID in 2024 and measures how long the page takes to respond across the whole visit, with a target under 200 ms. Cumulative Layout Shift (CLS) quantifies unexpected movement of content, with a target under 0.1.
| Metric | What it measures | Common Next.js cause | Typical fix |
|---|---|---|---|
| LCP | When the main content paints | Hero image not prioritized, render-blocking font | priority prop, next/font, preload |
| INP | Delay between input and next paint | Large client bundle parsing on main thread | dynamic import, smaller deps, workers |
| CLS | Unexpected layout movement | Image without dimensions, late-loading ads | width and height props, reserved space |
| TTFB | Time to first byte | Dynamic rendering of a cacheable route | force-static, route caching, CDN |
TTFB is not a Core Web Vital by itself, but it underpins all three: if the server takes 900 ms to send the first byte of HTML, every downstream metric inherits that delay. When LCP is poor, check TTFB first — a slow origin makes client-side fixes pointless.
Measure before you touch anything
Lab tools like Lighthouse are useful for controlled comparisons, but they hide deployment-level problems. Real-user monitoring shows what your actual audience experiences on their actual devices. Vercel's Speed Insights package records field data with almost no setup, and you can also roll your own with the web-vitals library.
// app/layout.js
import { SpeedInsights } from '@vercel/speed-insights/next';
import { Analytics } from '@vercel/analytics/react';
export const metadata = {
title: 'Acme Store',
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{children}
<SpeedInsights />
<Analytics />
</body>
</html>
);
}
Record a baseline before optimizing: median LCP, INP, and CLS over a real week, plus the p75 values Google uses for ranking. Then after each change, compare the same window. One improvement at a time is slower in the short run but far more honest — batch three changes together and you will never know which one helped.
Image and font delivery
Images dominate LCP on most content sites, and the next/image component solves most of it when configured correctly. Serve modern formats, restrict remote hosts, and mark only the true above-the-fold image as priority so the browser's preload scanner fetches it immediately instead of competing with lazy-loaded media.
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
formats: ['image/avif', 'image/webp'],
remotePatterns: [
{ protocol: 'https', hostname: 'cdn.example.com' },
],
},
experimental: {
optimizePackageImports: ['lodash-es', 'date-fns'],
},
};
module.exports = nextConfig;
// components/Hero.js
import Image from 'next/image';
export function Hero() {
return (
<section className="hero">
<Image
src="/hero.webp"
alt="Team collaborating in an open office"
width={1920}
height={1080}
priority
sizes="100vw"
placeholder="blur"
blurDataURL="data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoBAAEAAwA0JaQAA3AA/vuUAAA="
/>
<h1>Ship faster, together</h1>
</section>
);
}
Fonts deserve the same scrutiny. next/font downloads the font files at build time, self-hosts them, and injects size-adjust metrics so the browser can render fallback text without shifting layout. Avoid loading four weights of a display font when the design only uses two.
Splitting client code the right way
Every component in a Server Component tree ships zero JavaScript to the browser. The moment a file contains 'use client', its entire import graph joins the client bundle — including libraries that are only needed behind a modal or an off-screen tab. dynamic imports defer that cost until the component is actually rendered.
// app/dashboard/page.js
import dynamic from 'next/dynamic';
const RevenueChart = dynamic(() => import('../../components/RevenueChart'), {
loading: () => <div className="skeleton skeleton-chart" aria-hidden="true" />,
ssr: false,
});
export default function DashboardPage() {
return (
<main>
<h1>Dashboard</h1>
<RevenueChart />
</main>
);
}
Use ssr: false sparingly. It disables server rendering for that subtree, which is correct for canvas or WebGL widgets that assume a browser environment, but it delays content for SEO-sensitive text. For a chart that appears below the fold, a plain dynamic import with the default SSR behavior is usually enough — the code splits out, the server still renders the shell, and the heavy library only downloads when the browser approaches it.
A related trap is the barrel file. A components/index.js that re-exports fifty components means importing one button pulls the entire index through the bundler's reach, and unless the bundler can prove the other exports are unused, they survive in the output. Importing directly from the component's own file sidesteps the analysis entirely. When a shared design system makes barrels unavoidable, verify with the analyzer that tree-shaking is actually removing the unused siblings; some packaging formats, particularly CommonJS, make that impossible and the fix has to happen in the library itself.
Prefetching and navigation latency
Perceived speed is not only about the first visit. The App Router prefetches linked routes when they enter the viewport, so by the time a user clicks, the layout and page payloads are often already in the Router Cache. That default behavior is one of the quiet advantages of the framework, but it has sharp edges. Prefetching a link to a personalized dashboard warms a payload that will be immediately discarded because the route is dynamic, wasting bandwidth your other resources needed. Conversely, removing prefetch from a heavy route the user will rarely click frees the initial page to load its own critical assets faster.
You control this per link with the prefetch attribute on the Link component. Setting it to false is appropriate for long lists where dozens of speculative fetches would pile up, or for links behind authentication where the prefetch would 401. The trade-off is a slower first navigation on click, so measure both sides before disabling it globally. A useful middle ground is viewport-conditional prefetching: let the default apply above the fold and disable it in dense tables far down the page.
Route groups also interact with navigation speed. A layout that fetches data for every child page pays that cost once per navigation into the group, which is correct, but a layout that reads cookies or headers forces every child route to be dynamic even if the child itself is cacheable. Keep shared layouts free of dynamic API calls so each page can decide its own caching posture independently.
Bundle analysis and dependency diet
You cannot fix what you cannot see. @next/bundle-analyzer produces a treemap of every module in the client bundle, which routinely reveals surprises: a date library pulling in every locale, an icon package importing the full set for one glyph, or a utility imported as a deep path that defeats tree-shaking.
npm install --save-dev @next/bundle-analyzer
// next.config.js with analyzer wrapper
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
module.exports = withBundleAnalyzer({
// your existing config
});
Run ANALYZE=true npm run build and open the generated report. Sort by size and attack the top three entries first. Common wins include replacing moment.js with date-fns or native Intl, importing lodash-es methods individually instead of the root package, and swapping a full charting suite for a lighter alternative when you only need sparklines. optimizePackageImports in the config can also rewrite barrel imports into efficient deep paths without changing application code.
Caching for the return visit
First visits are dominated by network and rendering cost; return visits are dominated by how much you can serve from cache. Route segment configuration lets you declare that a page is safely static, while fetch-level revalidation keeps its data fresh without a redeploy.
// app/catalog/page.js
export const revalidate = 300;
export default async function CatalogPage() {
const products = await fetch('https://api.example.com/products', {
next: { revalidate: 300, tags: ['products'] },
}).then((r) => r.json());
return (
<ul className="catalog">
{products.map((p) => (
<li key={p.id}>{p.name}</li>
))}
</ul>
);
}
Pair this with the lessons on the four caching layers so you know which cache is answering each request — a page that looks slow on every navigation is often bypassing the cache because a header read silently marked the route dynamic.
💡Debugging trick
Compare the Network panel waterfall with the build output route table. If a route you expected to be static shows up as dynamic, fix that before tuning images — the rendering cost dwarfs everything else.
Common Mistakes
Adding priority to every image on the page
Fix: Only one or two elements should preload; competing priority hints cancel the benefit and waste bandwidth.
Importing a heavy chart or editor library at the top of a client component
Fix: Wrap the import in next/dynamic so the library loads only when the component mounts.
Trusting Lighthouse scores instead of field data
Fix: Lab runs are useful for regressions, but ranking and user experience come from real-user p75 values.
Forgetting width and height on images in flow content
Fix: Always pass intrinsic dimensions so the browser can reserve space and CLS stays near zero.
Best Practices
- Record a field-data baseline before optimizing and compare the same window after each change
- Keep next/image and next/font as the only pipeline for media and typography
- Review the bundle-analyzer treemap after every dependency addition, not once a year
- Reserve priority for the single largest above-the-fold asset on each route
- Cache public data with both revalidate windows and tags so a purge failure never serves ancient content
Interview Questions
Q1: LCP is 4.1 seconds on your product page. Walk through your diagnosis.
Check TTFB first — if the server is slow, fix route caching or rendering cost. Then confirm the hero image uses next/image with priority, correct sizes, and modern formats, and that no render-blocking font delays first paint.
Q2: When is ssr: false the right choice for a dynamic import?
When the component depends on browser-only APIs such as canvas or window during render. For SEO-visible content, keep SSR enabled and let the import split the bundle without disabling server rendering.
Q3: How does optimizePackageImports help performance?
It rewrites barrel-style imports into deep paths at build time, so importing one function from a large library no longer pulls the entire package into the client bundle.
Key Takeaways
- Core Web Vitals are field metrics: measure real users at p75, not just a lab run.
- LCP is usually images and fonts, INP is usually main-thread JavaScript, CLS is usually missing dimensions.
- next/image with priority and next/font eliminate the most common LCP regressions with almost no code.
- dynamic imports keep heavy client libraries out of the initial bundle until they are needed.
- Bundle analysis plus dependency diet routinely beats micro-optimizations by an order of magnitude.