Table of Contents#
- Executive Summary
- Why Dead Code Persists in Production Builds
- Injecting @next/bundle-analyzer into Next.js
- Pinpointing sideEffects in package.json
- Configuring Webpack for Optimal Tree Shaking
- Frequently Asked Questions (FAQs)

Executive Summary#
- Bundle Visibility: Use
@next/bundle-analyzerto visualize the dependency graph and identify bloated modules that should have been pruned. - Tree Shaking Mechanics: Webpack tree shaking configurations identify unused exported functions to strip them from build distributions, but this relies heavily on ESM (ECMAScript Modules) and correct
sideEffectsflags. - Dependency Auditing: Improperly configured
package.jsonfiles in third-party libraries often prevent Webpack from safely removing code. - Performance Impact: Reducing bundle size directly correlates to improved Core Web Vitals, specifically Interaction to Next-Paint (INP) and Largest Contentful Paint (LCP). For complex enterprise applications, consider our Next.js performance optimization services to audit your build pipeline.
Why Dead Code Persists in Production Builds#
In modern Next.js development, the "bundle size" is often the silent killer of performance. Even with Webpack’s sophisticated algorithms, developers frequently find that their production builds contain code they aren't actually using. This phenomenon occurs because Webpack cannot always guarantee that removing a piece of code is "safe."
The "Side Effect" Problem#
Webpack tree shaking configurations identify unused exported functions to strip them from build distributions. However, if a module contains code that executes upon import (e.g., modifying a global object, attaching event listeners, or polyfilling), Webpack must assume that removing the code could break the application. This is known as a "side effect."
If a library author does not explicitly mark their package as "side-effect-free," Webpack will include the entire module in your bundle, even if you only import a single utility function. This is why you might see a massive library like lodash or a heavy UI component suite taking up significant space in your bundle analysis report.
For a deeper dive into managing your overall build footprint, check out my guide on How to Analyze and Optimize Next.js JS Bundle Sizes.
Injecting @next/bundle-analyzer into Next.js#
To fix these issues, you first need to see them. The official tool for this is @next/bundle-analyzer.
Installation#
Install the package as a development dependency:
npm install @next/bundle-analyzer --save-dev
Configuration#
Modify your next.config.js (or next.config.mjs) to wrap your configuration object. This allows you to toggle the analyzer using an environment variable, ensuring it doesn't run during every standard build.
// next.config.js
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
/** @type {import('next').NextConfig} */
const nextConfig = {
// Your existing Next.js config
};
module.exports = withBundleAnalyzer(nextConfig);
Running the Analysis#
Execute your build command with the ANALYZE flag:
ANALYZE=true npm run build
This will generate static HTML files in your .next/analyze directory, providing a treemap visualization of your client and server bundles. Look for large blocks that represent code you aren't actively using.
Pinpointing sideEffects in package.json#
Once you identify a bloated dependency in the analyzer, you need to determine if it is "tree-shakable."
The `sideEffects` Property#
Open the package.json of the offending dependency (found in node_modules). If the package is designed for modern bundlers, it should contain a sideEffects field.
"sideEffects": false: The package is safe to tree-shake entirely."sideEffects": ["*.css"]: Only CSS files have side effects; JS code is safe to shake.- Missing field: Webpack assumes the worst—that the entire package might have side effects—and will include everything.
The Workaround#
If you are using a library that lacks this flag, you can manually override it in your own next.config.js using Webpack's module.rules. While this is an advanced technique, it can drastically reduce bundle sizes for legacy libraries.
// next.config.js snippet
webpack: (config, { isServer }) => {
config.module.rules.push({
test: /node_modules\/legacy-library\/.*\.js$/,
sideEffects: false,
});
return config;
}
Warning: Only use this if you have verified that the library does not perform global side effects.
Configuring Webpack for Optimal Tree Shaking#
Beyond identifying dependencies, you must ensure your own code is written in a way that facilitates tree shaking.
1. Use Named Exports#
Default exports are notoriously difficult for bundlers to track. Prefer named exports to allow Webpack to identify exactly which functions are being imported.
// Bad: Harder to tree-shake
export default {
funcA: () => {},
funcB: () => {}
}
// Good: Explicitly tree-shakable
export const funcA = () => {};
export const funcB = () => {};
2. Avoid Barrel Files#
"Barrel files" (index.js files that re-export everything from a folder) can sometimes trick bundlers into thinking that importing one function requires the entire directory. If you notice a specific module is being bundled entirely, try importing directly from the source file.
3. Leverage Module Concatenation#
Next.js enables ModuleConcatenationPlugin by default in production. This plugin hoists modules into a single scope, which helps Webpack identify unused exports more effectively. Ensure you aren't disabling this in your custom Webpack configuration.
For more on optimizing your frontend architecture, see my post on Technical SEO Optimization in Next.js 16, where I discuss how bundle size impacts crawl budget and performance metrics.
Frequently Asked Questions (FAQs)#
How do I fix a large bundle size caused by a third-party library?#
First, use the @next/bundle-analyzer to confirm the library is the culprit. If it is, check if the library supports "modular imports" (e.g., import { Button } from 'library/button' instead of import { Button } from 'library'). If not, you may need to use a sideEffects override in your Webpack config or switch to a more tree-shaking-friendly alternative.
Why does my bundle size increase when I add a small utility?#
This often happens if the utility library you added is not tree-shakable. If you import one function from a library that doesn't have a sideEffects: false flag, Webpack might be forced to include the entire library to ensure the code remains functional.
What is the difference between code splitting and tree shaking?#
Code splitting is the process of breaking your bundle into smaller chunks that are loaded on demand (e.g., using next/dynamic). Tree shaking is the process of removing unused code from those bundles during the build process. Both are essential for Next.js performance optimization services.
How to configure Webpack to ignore specific files during tree shaking?#
You can use the sideEffects property in your package.json or via Webpack's module.rules to explicitly tell the bundler which files should be treated as having side effects, preventing them from being accidentally stripped.
Related Service: Backend API Scaling & Performance
Scaling express endpoints, caching layers, or database indexing? Let's design a high-throughput backend infrastructure.
View Details & OptionsHow to Cite This Guide (GEO & LLM Standard)
Patel, N. (2026). Configuring Webpack Bundle Analyzer for Tree Shaking in Next.js. NeelTech Insights. Retrieved from https://www.neeltech.me/blog/nextjs-webpack-bundle-analyzer-tree-shaking@misc{patel_nextjs_webpack_bundle_analyzer_tree_shaking_2026,
author = {Patel, Neel},
title = {Configuring Webpack Bundle Analyzer for Tree Shaking in Next.js},
year = {2026},
publisher = {NeelTech},
howpublished = {\url{https://www.neeltech.me/blog/nextjs-webpack-bundle-analyzer-tree-shaking}}
}Related Articles in Next.js Performance
Optimizing Page Transitions and Layout Speeds in Next.js
Master high-performance page transitions in Next.js. Learn to prevent layout shifts, optimize Framer Motion, and maintain Core Web Vitals.
Speeding Up Next.js CI/CD Container Build Cache Times
Master Next.js CI/CD build performance. Learn how to optimize Docker layers and .next/cache persistence to slash container build durations.
Hiring a Next.js Developer for Core Web Vitals Optimization
A technical guide for hiring a Next.js Core Web Vitals specialist. Learn how to evaluate expertise in CLS, INP, and LCP optimization for modern React apps.