▲ Next.js Advanced

How does Next.js handle bundle optimization?

Why Interviewers Ask This

Advanced questions like this reveal whether a candidate has internalized Next.js deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.

Answer

Next.js applies several layers of bundle optimization automatically: 1. Automatic code splitting: each page/route gets its own JavaScript bundle. Shared code between pages is extracted into a common chunk. Lazy-loaded routes are split into separate chunks. 2. Server Components (App Router): Server Component code is NEVER included in the client bundle — massive reduction. Only Client Component code goes to the browser. 3. Tree shaking: Webpack/Turbopack removes unused exports from packages. Next.js fully supports tree-shaking. Mark side-effect-free modules in package.json: "sideEffects": false. 4. Dynamic imports (manual code splitting): const HeavyChart = dynamic(() => import("./Chart"), { loading: () => <p>Loading...</p>, ssr: false // Client-only });. Splits heavy components into separate chunks, loaded on demand. 5. Package imports optimization: optimizePackageImports: ["@mui/material", "lodash"] in next.config.js — enables tree-shaking for barrel files (index.js that re-exports everything). 6. SWC minification: uses Rust-based SWC for minification (faster + smaller output than Terser). 7. CSS optimization: CSS modules for scoped CSS, Tailwind CSS purging in production. 8. Bundle analysis: @next/bundle-analyzer — visualize what's in each bundle. Find large dependencies and replace with lighter alternatives. 9. Image and font optimization: prevent large image bundles — images should be served from CDN, not bundled. 10. Third-party scripts: use strategy="lazyOnload" for non-critical third-party scripts.

Common Mistake

A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.