Skip to main content
CodingMarble

Web development

How to Speed Up a Next.js Website

Most slow Next.js sites are slow for ordinary reasons: oversized images, late-loading fonts, too much client-side JavaScript and uncached data. Fix those four in order, and measure with both Lighthouse and real-user data so you know the change helped.

By CodingMarble · Published · 5 min read

A monitor showing a design system interface beside desk plants
Photo: Balázs Kétyi on Unsplash

Measure before you change anything

Speed work goes wrong when it starts with guesses. Before touching code, run Lighthouse in Chrome DevTools on a production build, not the dev server, because next dev ships unminified code and extra tooling that makes every page look worse than it is. Run npm run build followed by npm run start, open an incognito window so extensions do not interfere, and record the result for the two or three pages that matter most, usually the home page, a key landing page and a heavy template such as a product or blog page.

Lighthouse is a lab test: one device profile, one network profile, one moment. It is excellent for finding what is wrong and poor for deciding how real visitors feel. For that you need field data, which is collected from real Chrome users. PageSpeed Insights shows it at the top of the report when your site has enough traffic, and the Core Web Vitals report in Search Console groups your URLs by status. If your site is new and has no field data yet, treat Lighthouse as a guide and revisit after a few weeks of traffic.

Keep a small log: date, page, the metric you were trying to move, and what you changed. When a later deploy makes things worse, that log tells you where to look. Change one thing at a time where you can, otherwise you will not know which change did the work.

Images: let next/image do the heavy lifting

Images are the most common reason a page is slow, and the Largest Contentful Paint element is an image on a large share of pages. The next/image component resizes images on demand, serves modern formats the browser accepts, lazy-loads images below the fold and reserves space so the layout does not jump. The two props people forget are sizes and priority.

The sizes prop tells the browser how wide the image will actually be at each viewport width, so it can pick a suitably small file from the generated set. Without it, a fill image may be treated as full-viewport width and the browser downloads far more than needed. The priority prop belongs on the one image that is likely to be your LCP element, usually the hero. Do not set it on everything, since that cancels the point of lazy loading.

TSX· A hero image that is prioritised and told how wide it will render.
import Image from "next/image";

export function Hero() {
  return (
    <div style={{ position: "relative", aspectRatio: "16 / 9" }}>
      <Image
        src="/images/hero.jpg"
        alt="Team reviewing a website design on a laptop"
        fill
        priority
        sizes="(min-width: 1024px) 960px, 100vw"
        style={{ objectFit: "cover" }}
      />
    </div>
  );
}

To verify, open the Network panel, filter by Img, and check the transferred size and format of the hero. If a 1,200 pixel wide file is arriving on a phone, your sizes value is wrong or missing.

Fonts: self-host through next/font

Web fonts cause two visible problems: text that is invisible or swaps late, and layout that shifts when the real font replaces the fallback. The next/font module downloads font files at build time and serves them from your own domain, which removes a third-party connection and lets the framework preload the file. It also generates a fallback font with adjusted metrics so the swap moves text very little.

TSX· Loading a variable font once in the root layout.
import { Inter } from "next/font/google";

const inter = Inter({
  subsets: ["latin"],
  display: "swap",
});

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" className={inter.className}>
      <body>{children}</body>
    </html>
  );
}

Limit yourself to the weights and styles you really use, and prefer one variable font over four static files. Each extra family is another request and more bytes on the critical path. Check the result in the Network panel under Font: you should see files coming from your own origin, not from a Google domain.

Cut the JavaScript the browser must run

JavaScript is costly twice: it has to download, and then the main thread has to parse and execute it, which delays interaction. Start by looking at what you ship. Running the build prints the first-load JavaScript for each route, and the official bundle analyzer plugin for Next.js draws a treemap so you can spot one dependency that dominates a route. Common offenders are date libraries pulled in whole for a single format call, icon packs imported as a barrel, and chart or editor libraries loaded on pages that do not show a chart or editor.

For code that is needed only after a user action or only below the fold, use next/dynamic so it becomes a separate chunk fetched when required. Dynamic import is not free: the chunk needs a network round trip, so use it for things the user may never see, such as a modal, a rich text editor or a map, and not for content on the first screen.

TSX· Loading a heavy editor only when the component renders in the browser.
"use client";

import dynamic from "next/dynamic";

const RichEditor = dynamic(() => import("./RichEditor"), {
  ssr: false,
  loading: () => <p>Loading editor...</p>,
});

export function PostForm() {
  return <RichEditor />;
}

Third-party scripts deserve the same suspicion. Analytics, chat widgets and tag managers are often the largest cost on a page you wrote carefully. Load them with the next/script component and a lazy strategy, and remove any you cannot name a reason for.

Keep components on the server by default

In the App Router, components are server components unless a file begins with the use client directive. Server components send rendered output rather than their own code, so a long article body, a product description or a footer adds no component JavaScript to the bundle. The practical rule is to push the use client boundary as far down the tree as you can. If only a like button needs state, make the button a small client component and leave its parent on the server.

A frequent mistake is placing use client at the top of a layout because one child needed useState. That turns everything imported below it into client code. Search your project for the directive and ask of each file whether it truly needs state, effects or browser APIs. If not, remove it and see whether the build still passes.

Caching and revalidation

Fast pages are often just pages that were not rebuilt for each visitor. Next.js can render a route ahead of time and serve it from a cache, and it lets you set how long cached data stays fresh. Caching defaults have changed between major versions, so read the caching page of the current Next.js documentation rather than relying on an older tutorial, and then confirm the behaviour yourself.

TypeScript· Time-based revalidation for data that changes occasionally.
export const revalidate = 3600; // seconds, applies to the route segment

export async function getPosts() {
  const res = await fetch("https://api.example.com/posts", {
    next: { revalidate: 3600 },
  });
  if (!res.ok) throw new Error("Failed to load posts");
  return res.json();
}

Choose the freshness window from the business need, not from habit. A pricing table edited twice a year can be cached for a long time and refreshed on demand when someone edits it. A stock level cannot. To verify, look at the response headers in DevTools for cache status, and test what a visitor sees right after you change the source data. Also put static assets behind a CDN with long cache lifetimes; hashed filenames make that safe.

Confirm the improvement in the field

After each round of changes, rerun Lighthouse on the same pages under the same conditions and compare against your log. Then wait. Field data in PageSpeed Insights and Search Console is aggregated over a rolling window, so improvements appear gradually rather than the next morning. Adding the web-vitals library or the reporting hook in Next.js lets you send LCP, INP and CLS values from real sessions to your own analytics, which shows you which devices and pages are still struggling.

If Lighthouse improves and field data does not, the usual reasons are that real users are on slower phones than the test profile, that logged-in or personalised pages differ from what you tested, or that a third-party script behaves differently in production. Treat the gap as information, and go back to the slowest real segment rather than the prettiest score.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.