Bundle optimization in Next.js
From the Next.js cheat sheet · Performance Optimization · verified Jul 2026
Bundle optimization
typescript
// next.config.js - Bundle analyzer
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
})
module.exports = withBundleAnalyzer({
// Your config
})
// Run: ANALYZE=true npm run build
// Dynamic imports for code splitting
import dynamic from 'next/dynamic'
// Lazy load heavy component
const HeavyChart = dynamic(() => import('@/components/HeavyChart'), {
loading: () => <div>Loading chart...</div>,
ssr: false, // Disable SSR for client-only components
})
// Conditional loading
export function Dashboard() {
const [showChart, setShowChart] = useState(false)
return (
<div>
<button onClick={() => setShowChart(true)}>
Show Chart
</button>
{showChart && <HeavyChart />}
</div>
)
}
// Dynamic import in event handler
export function MyComponent() {
const handleClick = async () => {
const { processData } = await import('@/lib/heavy-processing')
const result = await processData()
console.log(result)
}
return <button onClick={handleClick}>Process</button>
}💡 Analyze bundle with @next/bundle-analyzer
⚡ Code splitting happens automatically
📌 Dynamic imports for lazy loading
🔥 Tree shaking removes unused code