Performance Optimization
How I Optimized My Next.js Bundle Size by 40%
A deep dive into code-splitting, dynamic imports, and bundle analysis tools to achieve a perfect 100/100 Lighthouse score.

How I Optimized My Next.js Bundle Size by 40%
A deep dive into code-splitting, dynamic imports, and bundle analysis tools to achieve a perfect 100/100 Lighthouse score.
When building modern web applications, performance isn't just a metric—it's a core feature. As new features are added during development, JavaScript bundle sizes tend to grow silently. This inevitably leads to slow initial page loads and negatively impacts SEO Core Web Vitals.
Recently, my portfolio's bundle size reached a massive 450kb. Here is the step-by-step engineering process I used to shave off 40% of that weight and optimize the user experience.
1. Analyzing the Damage with @next/bundle-analyzer
Before rewriting any code, I needed hard data. I installed Google's recommended bundle analyzer tool for Next.js to visually map which libraries were consuming the most space.
The visualizer revealed two massive hidden culprits:
The Lodash Trap: A single utility function was pulling in the entire lodash library instead of just the required module.
Eager Loading: A heavy syntax-highlighter tool was being downloaded on the initial page load, even on pages where it wasn't needed or before the user even scrolled to it.
2. Implementing Next.js Dynamic Imports
To fix the eager loading issue, I utilized Next.js's built-in next/dynamic utility. This allows for lazy-loading client components. By deferring heavy components like comment sections and syntax highlight blocks until they are actually needed, the initial JavaScript payload drops significantly.
Here is how I implemented dynamic imports for the code blocks:
< >
import dynamic from 'next/dynamic';
const CodeBlock = dynamic(() => import('@/components/CodeBlock'), {
loading: () =>
Loading Workspace...
, ssr: false, }); < /> By disabling Server-Side Rendering (ssr: false) for this specific interactive component and providing a lightweight loading state, the browser is freed up to paint the critical UI instantly. The Result By combining targeted imports and dynamic component loading, the initial JavaScript bundle was reduced by exactly 40%. The site now loads near-instantly, resulting in a flawless 100/100 Lighthouse performance score and a much smoother experience for visitors.