Skip to the solution
MediumSystem Design5 min read

How do you analyze and reduce bundle size in Next.js?

914 views

The problem

Question presented to candidate: "Lighthouse flags too much JavaScript on our product pages. How do you find out what is in the bundle, and what are your main levers to reduce it in a Next.js app?"

What a strong answer should cover:

  • Next.js 16 removed the size and First Load JS columns from next build; measure with the Turbopack bundle analyzer (next analyze since 16.4; next experimental-analyze in 16.1 to 16.3, still an alias), @next/bundle-analyzer for Webpack builds, and Lighthouse.
  • Biggest lever: keep code in Server Components, which ship no client JavaScript, and push 'use client' down to small leaves.
  • Import only what you use: per-function imports or optimizePackageImports for large libraries.
  • Lazy load heavy client code with next/dynamic or import() in handlers.
  • Move third-party scripts to next/script with a late strategy, and keep server-only packages out of client imports.

Clarifying questions expected:

  • "Which route and which user flow?" β€” measure the page that matters, not the whole app.
  • "Is the cost in our code or in dependencies?" β€” the analyzer answers that.

Code / implementation expected: Yes β€” an import change and the analyzer command.

  • nextjs
  • bundle-size
  • performance
  • optimization

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read Β· 8 sections

Read the code

Precise imports, package optimization and the analyzer
// Before: pulls in the whole library
import _ from "lodash";
const onSearch = _.debounce(search, 300);

// After: one module
import debounce from "lodash/debounce";
const onSearch2 = debounce(search, 300);

// next.config.ts: precise imports for barrel-heavy packages
const nextConfig = { experimental: { optimizePackageImports: ["@acme/icons"] } };
export default nextConfig;

// Terminal (Turbopack): Next.js 16.4+
//   npx next analyze                      (16.1 to 16.3: npx next experimental-analyze)
//   npx next analyze --output --snapshot before && npx next analyze export --snapshot before > graph.jsonl

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 39 of 129 in Next.js

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Next.js questions
Up nextMedium

How does fetch caching work in the Next.js App Router (force-cache, no-store, revalidate)?

Continue