Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 72 ยท Optimization and SEO

Bundle Size and Core Web Vitals

Cut JavaScript with next/dynamic and lazy loading, find heavy code with a bundle analyzer, and improve LCP, CLS and INP in a Next.js app. Includes the React Compiler option.

A fast page is mostly a matter of doing less work in the browser. Every kilobyte of JavaScript must be downloaded, parsed and run before it helps anyone, and the browser has only one main thread to do all of it. The App Router already helps: Server Components send no JavaScript for their own code, so the bundle only contains your Client Components and the libraries they import. This lesson is about the rest: keeping that bundle small, loading heavy pieces only when needed, and measuring the result with the numbers search engines use.

You will learn the three Core Web Vitals, the tools Next.js gives you for lazy loading and bundle analysis, the React Compiler option, and how to read your own page's numbers. Next.js code and configuration are read-only on this site. Two stand-ins run live: a React example of loading a component on demand, and a Node program that computes a layout shift score so you can see why reserving space matters.

The three vitals

LCP How fast the main content shows. Good is 2.5 s or less.
CLS How much the page jumps. Good is 0.1 or less.
INP How fast the page reacts to input. Good is 200 ms or less.

Judged on real visitors, at the 75th percentile.

1 / 2

The three Core Web Vitals

Core Web Vitals are three user-centered metrics. Google uses them as part of its page-experience signals, and they are a good proxy for how a page feels.

  • Largest Contentful Paint (LCP) is the time until the largest piece of content in the viewport (often a hero image or a headline) is painted. Good is 2.5 seconds or less; above 4 seconds is poor.
  • Cumulative Layout Shift (CLS) adds up unexpected movement of content. The score has no unit. Good is 0.1 or less; above 0.25 is poor.
  • Interaction to Next Paint (INP) measures how long the page takes to show a visual response after a click, tap or key press, worst cases included. Good is 200 milliseconds or less; above 500 is poor.

The thresholds are judged on field data: the 75th percentile of real visits, so one slow phone matters. Lab data from tools such as Lighthouse is a controlled test on a simulated device, useful while developing but only an estimate.

Fixing LCP

LCP is usually an image or a block of text, and it is slow for four reasons: the server answered late, the resource was discovered late, it was big, or something blocked rendering. In a Next.js app:

Fixing CLS

Layout shift happens when something appears or changes size after the browser has already placed what is around it. The cures are simple: always give images width and height (or use fill inside a sized box), use next/font so the fallback matches the real font, and reserve space for things that arrive late, such as ads, embeds and banners.

Run the program below to see how the score is computed. A browser reports, for each shift, an impact fraction (how much of the viewport was affected) multiplied by a distance fraction (how far things moved compared with the larger viewport dimension). This stand-in handles the simple case of full-width blocks that move vertically.

Node.js Computing a layout shift score

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first case scores 0.156, above the "good" limit, because a large block moved a long way. The second is zero because nothing moved. The third stays good because the shift is small, but several small shifts add up over a page's life.

Fixing INP

INP suffers when the main thread is busy: a big client-side render, a long loop, or a slow event handler. Ways to help:

  • Send less JavaScript. Keep "use client" files small and low in the tree; see Composing Server and Client Components.
  • Keep event handlers short. Do heavy computation in a worker or on the server, and update state in small steps. For work that can wait, mark the state update as a transition with useTransition so urgent input stays responsive.
  • Avoid rendering thousands of rows at once; paginate or virtualize.
  • Avoid needless re-renders in client code. The React Compiler (below) can do this for you.

Loading less up front with next/dynamic

Not every Client Component is needed when the page first appears: a chart below the fold, a rich text editor behind a button, a modal. Lazy loading splits such a component into its own chunk that downloads only when it is first rendered. Next.js gives you next/dynamic, a thin wrapper around dynamic import():

TSX
// app/dashboard/charts.tsx (read-only)
"use client";

import dynamic from "next/dynamic";

const SalesChart = dynamic(() => import("./sales-chart"), {
  loading: () => <p>Loading chart...</p>,
  ssr: false,
});

export function Charts({ show }: { show: boolean }) {
  return show ? <SalesChart /> : null;
}

The pieces:

  • The function passed to dynamic returns import("./sales-chart"), which tells the bundler to put that module in a separate chunk.
  • loading is shown while the chunk downloads.
  • ssr: false skips server rendering for the component. It is for code that touches window at import time. The option can only be used inside a Client Component; a Server Component that needs it must import a small client wrapper like the one above.

You can also load a library only when needed, with a plain dynamic import inside an event handler:

TSX
// read-only
async function exportPdf() {
  const { buildPdf } = await import("./build-pdf"); // chunk downloads on first click
  buildPdf();
}

Plain React.lazy with Suspense works too. The stand-in below uses it, since a sandbox cannot split real chunks. The component takes about 400 milliseconds to "arrive", as a real download would. The sizes shown are invented for the demonstration.

Load a component on demand

Click "Show chart": you see the fallback first, then the bars. Hide it and show it again and the chunk is not downloaded a second time, because a loaded module is kept; the console prints "chunk requested" and "chunk downloaded" only the first time.

Finding what is heavy

Guessing which dependency bloats the bundle rarely works. Use a bundle analyzer, which draws every module as a rectangle sized by its bytes. The classic package is @next/bundle-analyzer:

TypeScript
// next.config.ts (read-only)
import type { NextConfig } from "next";
import bundleAnalyzer from "@next/bundle-analyzer";

const withBundleAnalyzer = bundleAnalyzer({ enabled: process.env.ANALYZE === "true" });

const nextConfig: NextConfig = {};

export default withBundleAnalyzer(nextConfig);

Run a production build with ANALYZE=true and it opens reports for the client and server bundles. Turbopack builds have their own experimental analyzer in recent releases; check the documentation for your version. What to look for:

  • A large library used in one place (an entire date or charting package): replace it with something lighter, or load it with dynamic.
  • The same library bundled twice at different versions.
  • Server-only code leaking into the client bundle (see Keeping Server Code on the Server).
  • Icon or utility packages imported through a "barrel" file (import { A } from "big-library") that pulls in the whole package. Next.js optimizes many popular packages automatically, and the experimental.optimizePackageImports option lets you add more.

Measuring in your own app

Next.js lets you report the vitals from real visitors to your analytics. In a Client Component, call the useReportWebVitals hook and mount the component in the root layout:

TSX
// app/web-vitals.tsx (read-only)
"use client";

import { useReportWebVitals } from "next/web-vitals";

export function WebVitals() {
  useReportWebVitals((metric) => {
    // metric.name is "LCP", "CLS", "INP", ...; metric.value is the number
    navigator.sendBeacon("/api/vitals", JSON.stringify(metric));
  });
  return null;
}

For a quick look without any code, run Lighthouse in the browser's developer tools (lab data) and paste a public URL into PageSpeed Insights to see real-world data when your site has enough traffic.

The React Compiler option

The React Compiler is a build-time tool that analyzes your components and adds memoization automatically, so you no longer sprinkle useMemo, useCallback and memo everywhere. It helps client-side re-render cost, which is good for INP. It does nothing for Server Components, since they do not re-render in the browser. In recent Next.js versions you turn it on with one option after installing the Babel plugin:

TypeScript
// next.config.ts (read-only)
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  reactCompiler: true,
};

export default nextConfig;

It requires babel-plugin-react-compiler and makes builds somewhat slower. Your code has to follow the Rules of React (pure render, no mutation of props or state) for the compiler to work. If a component misbehaves, you can opt it out with the "use no memo" directive. Measure before and after, as it is an optimization like any other.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which Core Web Vital measures how much content unexpectedly moves while the page loads?

    Cumulative Layout Shift adds up unexpected movement. LCP is about the main content's paint time and INP is about responsiveness to input.
  2. 2. What does ssr: false in next/dynamic do, and where can it be used?

    The component is rendered only in the browser. In a Server Component you must import a small Client Component wrapper that uses dynamic with ssr false.
  3. 3. A heavy PDF library is only needed when the user clicks Export. What is the best way to load it?

    A dynamic import puts the library in its own chunk, which downloads only when the handler first runs.
  4. 4. Which statement about the React Compiler is correct?

    The compiler automates memoization for components that run in the browser. It needs pure components and does not change what ends up in the bundle.
  5. 5. Reserving the height of an image box before it loads mainly improves which metric?

    When the space is reserved, nothing is pushed down when the image arrives, so the layout shift score stays near zero.

Summary

  • Core Web Vitals are LCP (good at 2.5 s or less), CLS (0.1 or less) and INP (200 ms or less), judged on real visitors.
  • Improve LCP with server-rendered content, a prioritized hero image, caching and self-hosted fonts.
  • Improve CLS by giving images dimensions, using next/font, and reserving space for late content.
  • Improve INP by shipping less JavaScript, keeping handlers short and avoiding needless re-renders.
  • Use next/dynamic (or import() in handlers) to split off components and libraries that are not needed at first; ssr: false only works in Client Components.
  • Use a bundle analyzer to find heavy dependencies, useReportWebVitals to collect field data, and the React Compiler (reactCompiler: true) as an optional automatic memoization step.

Next: Internationalization