# Bundling Fix common bundling issues with third-party packages. ## Server-Incompatible Packages Some packages use browser APIs (`window`, `document`, `localStorage`) and fail in Server Components. ### Error Signs ``` ReferenceError: window is not defined ReferenceError: document is not defined ReferenceError: localStorage is not defined Module not found: Can't resolve 'fs' ``` ### Solution 1: Mark as Client-Only If the package is only needed on client: ```tsx // Bad: Fails - package uses window import SomeChart from 'some-chart-library' export default function Page() { return } // Good: Use dynamic import with ssr: false import dynamic from 'next/dynamic' const SomeChart = dynamic(() => import('some-chart-library'), { ssr: false, }) export default function Page() { return } ``` ### Solution 2: Externalize from Server Bundle For packages that should run on server but have bundling issues: ```js // next.config.js module.exports = { serverExternalPackages: ['problematic-package'], } ``` Use this for: - Packages with native bindings (sharp, bcrypt) - Packages that don't bundle well (some ORMs) - Packages with circular dependencies ### Solution 3: Client Component Wrapper Wrap the entire usage in a client component: ```tsx // components/ChartWrapper.tsx 'use client' import { Chart } from 'chart-library' export function ChartWrapper(props) { return } // app/page.tsx (server component) import { ChartWrapper } from '@/components/ChartWrapper' export default function Page() { return } ``` ## CSS Imports Import CSS files instead of using `` tags. Next.js handles bundling and optimization. ```tsx // Bad: Manual link tag // Good: Import CSS import './styles.css' // Good: CSS Modules import styles from './Button.module.css' ``` ## Polyfills Next.js includes common polyfills automatically. Don't load redundant ones from polyfill.io or similar CDNs. Already included: `Array.from`, `Object.assign`, `Promise`, `fetch`, `Map`, `Set`, `Symbol`, `URLSearchParams`, and 50+ others. ```tsx // Bad: Redundant polyfills