Next.js · Nov 23, 2026 · 10 min read

Next.js 15 Bundle Optimization: Analyzer, Dynamic Imports & Modularization

Hands-on guide showing how to install and read the official bundle analyzer, apply dynamic imports with Suspense, leverage Server Components, and use modularImports to cut client-side JavaScript in re

Next.js 15 Bundle Optimization: Analyzer, Dynamic Imports & Modularization

Why Bundle Size Directly Affects Production Performance

Every kilobyte of JavaScript shipped to the browser delays Time to Interactive and increases Total Blocking Time. For users on 3G or slow 4G connections common outside major cities, this delay translates into higher bounce rates. Next.js 15 ships with improved Turbopack and better tree-shaking defaults, yet many applications still ship 400-800 KB of gzipped JavaScript because developers import entire libraries or heavy client components at the root layout level.

The official bundle analyzer remains the fastest way to see exactly what code ends up in each chunk. Combined with Next.js App Router patterns such as Server Components and dynamic imports, you can routinely cut client bundles by 40-60 % without changing business logic. This article walks through the exact setup, interpretation, and iterative optimization steps using real, copy-pasteable code examples.

Installing and Configuring the Official Bundle Analyzer

Start by adding the analyzer package. The version compatible with Next.js 15.0+ is @next/bundle-analyzer 15.0.0 or later.

npm install --save-dev @next/bundle-analyzer

Create or update next.config.mjs (ESM config is recommended for Next.js 15):

import createNextIntlPlugin from 'next-intl/plugin';
import withBundleAnalyzer from '@next/bundle-analyzer';

const withNextIntl = createNextIntlPlugin();

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

export default bundleAnalyzer(withNextIntl({
  reactStrictMode: true,
  experimental: {
    reactCompiler: true,
  },
}));

Run the build with the environment variable set:

ANALYZE=true npm run build

This opens an interactive HTML report at ./.next/analyze/client.html and server.html. The report uses a treemap where rectangle size represents gzipped size and color indicates module origin (webpack, user code, node_modules).

Reading the Analyzer Treemap Correctly

The client bundle view is the most important. Look for large red or orange rectangles inside the node_modules folder. Common offenders include:

  • lodash (full import pulls all 70+ utilities)
  • recharts or chart.js with all Chart types
  • date-fns when importing the entire library instead of individual functions
  • pdf-lib or dompurify pulled into layout.tsx
  • Any large icon library imported as import * as Icons from 'lucide-react'

Hovering a rectangle shows the exact import path and uncompressed vs gzipped size. The goal is to move heavy modules into their own asynchronous chunks that load only when the relevant page or feature is used.

Dynamic Imports with React.lazy and Next.js dynamic()

Next.js wraps React.lazy with its own dynamic function that supports SSR options and automatic bundle splitting. Here is a concrete example of a heavy analytics dashboard component.

// app/dashboard/page.tsx
import dynamic from 'next/dynamic';
import { Suspense } from 'react';

const HeavyDashboard = dynamic(
  () => import('@/components/HeavyDashboard'),
  {
    ssr: false,
    loading: () => <div className="h-96 w-full animate-pulse bg-zinc-900 rounded-xl" />,
  }
);

export default function DashboardPage() {
  return (
    <Suspense fallback={<DashboardSkeleton />}>
      <HeavyDashboard />
    </Suspense>
  );
}

The HeavyDashboard component can safely import Recharts, TanStack Table with column resizing, and a large set of Lucide icons. These modules now live in their own chunk that is fetched only after the user navigates to /dashboard.

Trade-off: the first visit to the dashboard shows a loading state. Use a well-designed skeleton that matches the final layout to reduce perceived latency. The benefit is that the root layout and marketing pages stay under 45 KB gzipped.

Leveraging Server Components to Keep Libraries Off the Client

Server Components run exclusively on the server, so any library imported in them never reaches the browser. This is the single highest-impact optimization in Next.js 15.

Consider a PDF generation feature. Instead of using a client-heavy react-pdf viewer on every page, generate metadata on the server and stream the result:

// app/api/report/pdf/route.ts
import { PDFDocument } from 'pdf-lib'; // 180 KB uncompressed, stays on server

export async function GET(request: Request) {
  const pdfDoc = await PDFDocument.create();
  // populate document using data fetched with Drizzle or Prisma
  const pdfBytes = await pdfDoc.save();

  return new Response(pdfBytes, {
    headers: {
      'Content-Type': 'application/pdf',
      'Content-Disposition': 'attachment; filename="report.pdf"',
    },
  });
}

The client only receives a button that triggers a fetch to this Route Handler. No PDF library code is shipped to the browser.

Apply the same principle to any data transformation that does not require user interaction: CSV parsing with PapaParse, image optimization with Sharp (via an API route), or complex permission checks using Casbin. Keep these on the server and return only the computed JSON or UI.

modularImports in next.config.mjs for Automatic Tree Shaking

Next.js 13.4+ introduced the modularImports transform that rewrites imports at build time. This works especially well with libraries that export from barrel files.

export default {
  modularImports: {
    lodash: {
      transform: 'lodash/{{member}}',
    },
    'date-fns': {
      transform: 'date-fns/{{member}}',
    },
    '@headlessui/react': {
      transform: '@headlessui/react/{{member}}',
    },
  },
};

After this configuration, the following code:

import { debounce, throttle } from 'lodash';

is automatically transformed to:

import debounce from 'lodash/debounce';
import throttle from 'lodash/throttle';

This prevents the entire Lodash bundle from being included. Measure the difference by running the analyzer before and after adding the transform. The change is usually immediate and requires no code edits beyond the config.

Optimizing Popular UI and Data Libraries

Many projects use shadcn/ui together with Tailwind. The components are already tree-shakable, but the icon library is often the hidden cost. Replace react-icons (multiple icon sets in one package) with lucide-react and import only the icons you need:

import { ArrowRight, CheckCircle2, Loader2 } from 'lucide-react';

Each icon is a separate ES module; unused icons are completely removed by the bundler.

For charts, prefer Tremor or lightweight Recharts compositions over importing the entire recharts package when only a single chart type is used. If you need only a line chart, dynamically import a wrapper that itself imports only LineChart, Line, XAxis and CartesianGrid.

Date handling is another frequent source of bloat. Replace moment (72 KB gzipped, no tree shaking) with date-fns v3 or dayjs. With the modularImports transform shown earlier, only the functions you actually call are included.

Handling Large Client-Side Machine Learning or Visualization Libraries

When a project must run Transformers.js or ONNX models in the browser, the model files and library easily exceed 15 MB uncompressed. The only responsible pattern is to load them dynamically and only on the exact route that needs them.

const ModelRunner = dynamic(
  () => import('@/components/ModelRunner'),
  { ssr: false }
);

Inside ModelRunner.tsx you can import @xenova/transformers and the specific model. The chunk containing the 8 MB quantized model is downloaded only when the user clicks “Analyze document”. Combine this with a progress bar using the onProgress callback from the library to keep users informed.

Setting Bundle Size Budgets in CI

Prevent regression by adding size limits to continuous integration. Install the size-limit package with the webpack plugin:

npm install --save-dev size-limit @size-limit/webpack

Create .size-limit.json:

[
  {
    "path": ".next/static/chunks/main-*.js",
    "limit": "45 kB",
    "gzip": true
  },
  {
    "path": ".next/static/chunks/pages/dashboard-*.js",
    "limit": "120 kB",
    "gzip": true
  }
]

Add to your GitHub workflow:

- name: Check bundle size
  run: npm run size-limit

If any limit is exceeded the CI fails, forcing the team to optimize before merging. This practice keeps the bundle size under control as features accumulate.

Advanced Chunk Splitting Strategies

Next.js automatically creates shared chunks for modules used by multiple pages. You can influence this further by using next/dynamic with the same loading component across routes so that the shared loading UI is deduplicated.

For vendor libraries that are large but rarely change (e.g. a pinned version of TanStack Query v5), you can force them into a separate chunk by configuring webpack in next.config.mjs:

webpack: (config) => {
  config.optimization.splitChunks.cacheGroups = {
    ...config.optimization.splitChunks.cacheGroups,
    tanstack: {
      test: /[\\/]node_modules[\\/](@tanstack)[\\/]/,
      name: 'tanstack',
      chunks: 'all',
      priority: 10,
    },
  };
  return config;
},

This creates a stable tanstack-abc123.js chunk that can be cached long-term by CDNs and browsers even when your application code changes weekly.

Real-World Optimization Walkthrough on a SaaS Dashboard

Consider a typical B2B analytics product. The marketing pages, pricing page, and login screen should stay extremely light. The dashboard route contains:

  • Multiple Recharts graphs
  • Advanced data table with virtual scrolling (TanStack Table + react-window)
  • Sidebar with 40 Lucide icons
  • Real-time updates via Server Sent Events

Initial bundle analysis showed 387 KB gzipped for the dashboard chunk. After the following changes the size dropped to 118 KB:

  1. Converted the entire dashboard layout to a Server Component that fetches data with Drizzle ORM on the server.
  2. Dynamic import of the charting library and table only inside a client component wrapped by Suspense.
  3. Added modularImports for date-fns and lodash.
  4. Switched from full lucide-react barrel import to individual icon imports.
  5. Moved PDF export to a Route Handler that uses pdf-lib on the server.

Each change was validated by re-running the analyzer and confirming that no new large modules appeared in the client bundle. The Lighthouse performance score on a simulated 4G mobile connection improved noticeably because First Contentful Paint occurred 900 ms earlier.

Common Pitfalls and How to Avoid Them

Dynamic imports without proper Suspense boundaries cause layout shifts. Always provide a loading component that reserves the exact height of the final content when possible.

Over-splitting can increase the number of network requests. A good middle ground is to keep related features (for example all chart components) inside one dynamic chunk rather than splitting every single chart into its own file.

Some libraries ship both ESM and CommonJS and the bundler sometimes picks the wrong one. Pin the ESM version explicitly in package.json with the exports field or use the browser field when available.

Do not dynamically import libraries that are needed for above-the-fold content. The hero section, navigation, and critical CTAs should remain synchronous so they render during the initial HTML stream.

Monitoring Bundle Size Over Time

Integrate bundle monitoring into your design system or component library repository. Every time a new shared component is added, the analyzer report should be generated automatically and attached as a comment in pull requests using tools like size-limit-action on GitHub.

For teams running multiple Next.js micro-frontends, maintain a central budget document that lists acceptable gzipped sizes per route type (marketing < 60 KB, dashboard < 140 KB, admin < 90 KB). These numbers act as guardrails rather than hard rules and are adjusted only after careful measurement.

Combining Optimizations with Other Next.js 15 Features

Partial Prerendering (PPR) in Next.js 15 works synergistically with these techniques. Static parts of a page are rendered at build time while dynamic holes are streamed in. Because the dynamic holes are usually client components, keeping those components lightweight through dynamic imports ensures the streamed payload stays small.

The React Compiler (enabled via experimental.reactCompiler) further reduces runtime JavaScript by eliminating unnecessary memoization. After applying the bundle techniques above, enable the compiler and re-measure; you will often see an additional 5-12 KB reduction because fewer helper functions are generated.

Final Checklist Before Every Major Release

  • Run ANALYZE=true npm run build and inspect every client chunk larger than 40 KB.
  • Verify that no heavy library appears in the root layout or any marketing page.
  • Confirm all icons are imported individually.
  • Check that date, utility, and UI libraries use modularImports transforms.
  • Validate that CI size-limit checks pass.
  • Measure Lighthouse scores on mobile and desktop after changes.
  • Document any new dynamic imports added so the team understands the loading states.

Following this checklist consistently keeps production bundles small even as the application grows from a few pages to dozens of complex dashboards and AI-powered tools.

By combining the bundle analyzer for visibility, dynamic imports for on-demand loading, Server Components for zero client cost, and configuration transforms for automatic optimization, you create a fast, scalable Next.js 15 application that loads quickly for every user regardless of device or network conditions. The techniques shown here require only configuration changes and disciplined import habits—no major refactoring of business logic is necessary.

Keep reading

Related Articles