🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Performance Budgets and Core Web Vitals in Next.js

Next.js PerformanceđŸŸĸ Free Lesson

Performance Budgets and Core Web Vitals in Next.js

Performance work without a number attached to it is decoration. Teams ship lazy loading, defer a chart library, and declare victory, while the page a real visitor downloads on a mid-range phone over a congested connection is unchanged. A budget converts the argument from "is this faster" to "are we inside the limit we agreed on", which is a question a build can answer and a reviewer can enforce.

This lesson is about setting those numbers, measuring the four metrics that carry them, and choosing optimisations based on what the measurements say rather than what is fashionable.

Prerequisites

  • !React rendering and component trees
  • !What a JavaScript bundle is and how it loads
  • !A Next.js project you can build and profile locally

What You'll Learn

  • 1Write a budget with concrete numbers for each metric
  • 2Collect Core Web Vitals from real users in production
  • 3Split code where it changes the critical path, not merely the total
  • 4Fix the specific causes of poor LCP and layout shift

A budget is agreed before the feature

The useful form is small, explicit, and per-route: on the marketing landing page, no more than 120 kilobytes of JavaScript after compression, a largest contentful paint under 2.0 seconds at the 75th percentile, and a cumulative layout shift under 0.1. An authenticated dashboard may be allowed more, because its users are signed in and returning. What kills budgets is stating them as goals — "keep it fast" — because there is nothing to fail.

MetricWhat it measuresGoodBudget example
LCPWhen the main content paints≤ 2.5 s≤ 2.0 s on landing
INPResponse to the next interaction≤ 200 ms≤ 150 ms
CLSUnexpected layout movement≤ 0.1≤ 0.05
TTFBTime to first byte from the server≤ 800 ms≤ 400 ms
JS transferredCompressed script on first load—≤ 120 KB landing

The threshold column is not arbitrary: it mirrors the thresholds search engines use when they evaluate sites, so a page that passes your internal budget also passes the external one. Attaching a page type to each row matters more than the exact digits, because it tells a developer whether an addition is a regression or an acceptable trade.

Measuring what real users experience

Lab tools on a desktop machine will happily report your page as fast while a significant share of your actual visitors wait five seconds. Field data comes from the browser, is sampled, and is reported back with the connection and device context that a lab cannot reproduce.

// app/web-vitals.js
'use client';

import { useEffect } from 'react';

function report(metric) {
  const body = JSON.stringify({
    name: metric.name,
    value: metric.value,
    id: metric.id,
    rating: metric.rating,
    navigationType: metric.navigationType,
  });

  // keepalive lets the send survive a page unload.
  if (navigator.sendBeacon) {
    navigator.sendBeacon('/api/vitals', body);
  } else {
    fetch('/api/vitals', { method: 'POST', body, keepalive: true });
  }
}

export default function WebVitals() {
  useEffect(() => {
    import('web-vitals').then(({ onLCP, onINP, onCLS, onTTFB }) => {
      onLCP(report);
      onINP(report);
      onCLS(report);
      onTTFB(report);
    });
  }, []);

  return null;
}

Two choices in that snippet are deliberate. The library is dynamically imported so it never sits on the critical path of the very page it is measuring, and keepalive ensures the beacon is still sent when a user navigates away mid-measurement — precisely the sessions where the worst values live. Aggregate by percentile rather than by average; a mean hides the tenth of users for whom the page is unusable.

Splitting code where it changes the critical path

Code splitting is not an optimisation by itself. Moving a module out of the initial bundle helps only if that module was not needed for the first paint, and it can hurt if the split introduces a second round trip for something the page needed immediately. The measurement that matters is what loads before the user can read and interact, not the total weight of the application.

// app/reporting/page.js — heavy chart stays out of the initial load
import dynamic from 'next/dynamic';
import { Suspense } from 'react';

const QuarterlyChart = dynamic(() => import('@/components/quarterly-chart'), {
  loading: () => <div className="h-64 animate-pulse rounded bg-slate-100" />,
  ssr: false,
});

export default function ReportingPage({ summary }) {
  return (
    <main>
      <h1>Quarterly reporting</h1>
      {/* Summary is in the HTML; the chart arrives afterwards. */}
      <StatGrid stats={summary.stats} />
      <Suspense fallback={<div className="h-64 animate-pulse rounded bg-slate-100" />}>
        <QuarterlyChart series={summary.series} />
      </Suspense>
    </main>
  );
}

The pattern to look for is a dependency that is expensive but not needed to understand the page: a charting library, a rich text editor, a date picker, a markdown renderer. Each one you move out of the initial route is weight that never competes with the first paint. Conversely, anything rendered above the fold belongs in the initial bundle — splitting it only delays the content you were trying to protect.

optimizePackageImports in the Next config achieves the same effect for libraries with deep import trees, since it compiles them the way a hand-written barrel would instead of pulling every file through the module graph.

Fixing the largest contentful paint element specifically

LCP is a single element, so the work is diagnostic rather than general. Identify the element in a trace, then ask which of four delays it suffered. If it is an image, the usual culprits are a missing width and height, a priority hint absent so the browser discovers it late, or a hero image that sits below a large empty div. If it is a font, invisible text while the webfont loads pushes the paint — use next/font, which preloads and gives the fallback metrics needed to avoid a reflow. If it is server-rendered text, the delay is TTFB: streaming, caching, or a slow query upstream. If it is a client-rendered block, the data was fetched in the browser when it could have been awaited on the server.

// Prioritising the hero image and keeping dimensions stable
import Image from 'next/image';

export function Hero({ src, alt }) {
  return (
    <Image
      src={src}
      alt={alt}
      width={1600}
      height={900}
      priority
      sizes="(max-width: 768px) 100vw, 1200px"
      fetchPriority="high"
    />
  );
}

priority preloads the image and marks it high priority; sizes tells the browser which variant to fetch so a phone does not download a desktop asset. Both remove a decision the browser would otherwise make too late.

Layout shift comes from things that move

Cumulative layout shift penalises content that appears after the browser has already drawn around it. Every cause has the same shape — space was not reserved — so the fixes are variations on one theme. Media needs explicit dimensions. Ad slots, embedded widgets, and async banners need a minimum height until they resolve. Web fonts need a fallback whose metrics are close, or a font-display strategy that does not swap to a much wider face. And content injected above existing elements — a cookie banner, a promotional strip, a late-loading notification — needs to occupy space from the first paint or be positioned so it overlays rather than pushes.

A useful test is to load the page with network throttled and watch what jumps. Anything that jumps after the initial paint is a candidate for reserved space, and none of the fixes require an optimisation library.

Making the budget enforceable

A number nobody checks decays within a sprint. The cheapest enforcement is a size check on the production bundle, run in continuous integration, that fails the build when a threshold is crossed.

javascript
// size-limit.config.mjs — measured after next build, gzip size
export default [
  {
    path: '.next/static/chunks/pages/index-*.js',
    limit: '120 KB',
    name: 'Landing page first load',
  },
  {
    path: '.next/static/chunks/pages/dashboard-*.js',
    limit: '250 KB',
    name: 'Dashboard first load',
  },
  {
    path: '.next/static/chunks/**/*.js',
    limit: '400 KB',
    name: 'Total client JavaScript',
  },
];

Pair the hard limit with a report that shows the delta per pull request, because a failure with no explanation produces a fight rather than a fix. For the field metrics, dashboards cannot gate a build — the data arrives after release — so they need a different ritual: a weekly read of the 75th percentile per template, with a named owner for any template that has crossed its threshold for two consecutive weeks. The two mechanisms complement each other. The build check stops obvious regressions from shipping; the field review catches the ones that only appear on real devices and real networks.

Keep the thresholds honest by measuring the artefact users receive, not the source. Compression, tree shaking, and route-level splitting all mean that the number in your repository is not the number on the wire.

Common Mistakes

Treating total bundle size as the goal

Fix: Budget what loads before first interaction; a smaller bundle that arrives after the content is not a win.

Optimising from lab scores alone

Fix: Collect field data at percentiles so slow devices and connections are visible in the numbers you act on.

Lazy-loading above-the-fold content

Fix: Split only what is needed after first paint; hero text and images belong in the initial load.

Adding a client-side fetch for data the server already has

Fix: Await it in the Server Component so LCP measures rendered content rather than a round trip.

Best Practices

  • Write budgets per route type and fail the build when a threshold is exceeded
  • Report field metrics with a beacon and review percentiles, not averages
  • Name the LCP element before choosing an optimisation for it
  • Reserve space for everything asynchronous — images, fonts, embeds, banners

Interview Questions

Q1: Why do percentiles matter more than averages for Core Web Vitals?

Field data is long-tailed: a subset of users on slow devices dominates the tail, and an average hides the fact that those users fail the threshold while the mean still looks healthy.

Q2: When does code splitting make performance worse?

When the split module was needed for first paint, adding a network round trip to the critical path, or when it fragments a shared dependency and duplicates it across chunks.

Q3: What are the four typical causes of a slow LCP element?

A late-discovered or oversized image, a web font delaying text render, a slow server response, or content rendered only after a client-side data fetch.

Key Takeaways

  • A budget needs numbers, a page type, and a way to fail — otherwise it is an opinion.
  • Measure real users at the 75th percentile; lab scores miss the devices that suffer.
  • Split only what is not needed for first paint, and prioritise what is.
  • LCP is diagnostic: identify the element, then name which of four delays hit it.
  • Layout shift is almost always unreserved space — dimensions for media, metrics for fonts, height for embeds.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement