Next.js Frontend Performance Optimization
A structured workflow for diagnosing and fixing Lighthouse performance issues in Next.js App Router projects. Work through the priority order below — each section tells you what to look for and what to do about it.
Step 0: Confirm the Measurement is Valid
Before touching any code, verify the user is benchmarking against a production build. Running Lighthouse against next dev gives artificially bad scores (no minification, no tree shaking, React dev mode overhead).
npm run build && npm run start
# Run Lighthouse against localhost (use PORT=3002 if port is occupied)
If the user hasn't done this, tell them to re-run Lighthouse against production before proceeding. Dev-mode scores are not actionable.
Step 1: Run the Bundle Analyzer
Install and configure @next/bundle-analyzer if not already present. It has zero runtime impact — it only runs during build when ANALYZE=true is set.
npm install @next/bundle-analyzer
ANALYZE=true npm run build
Look at the client treemap. The biggest blocks are your optimization targets. Read references/patterns.md § "Bundle Analyzer Setup" for the config snippet.
Step 2: Optimization Priority Order
Work through these in order of impact:
2.1 Defer Heavy Libraries
Symptoms: Bundle analyzer shows a large library (Three.js, D3, map libs, chart libs, animation libs) in a shared or initial chunk. Lighthouse flags high script evaluation time.
Decision: If the library is needed above the fold, it stays. If it's below the fold or only needed on interaction, defer it.
Fix — Two-Layer Deferral:
next/dynamicwithssr: false(the component needs browser APIs)- Gate rendering behind
requestIdleCallbackso the import fires only after the main thread is idle
The dynamic import() inside next/dynamic only fires when the component renders. Since ready starts as false, nothing loads until the browser is idle. The placeholder must match the real component's dimensions to prevent layout shift.
See references/patterns.md § "Two-Layer Deferral" for the full pattern.
2.2 Code-Split Below-Fold Sections
Symptoms: Large page bundles in the analyzer. Components visible only after scrolling are in the initial JS.
Fix: Use IntersectionObserver + raw import() for true deferred loading. This has zero JS cost until the user scrolls near the component.
next/dynamic vs raw import():
next/dynamic | Raw import() in useEffect | |
|---|---|---|
| Chunk in initial HTML | Yes (<script async>) | No |
| When chunk downloads | Page load | When import() is called |
| Initial JS cost | Chunk downloaded and parsed eagerly | Zero until triggered |
- Use
next/dynamicwhen the component needs its HTML in the initial page (SEO, layout stability) - Use raw
import()when the component is below the fold and you want zero initial JS cost
See references/patterns.md § "Lazy Import Hook" for the useLazyImport implementation.
2.3 Replace Simple Animations with CSS
Symptoms: Animation library (Framer Motion, GSAP) appears in the bundle analyzer's shared/initial chunk. Lighthouse flags high script evaluation or unattributable CPU time.
How animation libs sneak into the initial bundle:
- Layout-level imports — wrapping the app in a provider/config from the library
- Above-fold component imports — any static import pulls the library in
Decision guide — CSS vs JS animations:
Replace with CSS when:
- Fire-and-forget animations (entrance fades, slide-ins, spinners)
- Infinite simple loops (bounce, pulse, rotate)
- Visibility-triggered reveals (IntersectionObserver + CSS transition)
- Only animating
opacity,transform, orfilter(GPU-composited)
Keep the JS library when:
- Spring physics (damped oscillation, stiffness/damping)
- Gesture interaction (drag, pan, pinch)
- Enter/exit transitions for mounting/unmounting (AnimatePresence)
- Layout animations (shared layout transitions)
- Complex scroll-driven physics
Fix approach:
- Replace simple animations with CSS keyframes or transitions
- Replace scroll-driven parallax with native
requestAnimationFrame - Remove library imports from layout-level files
- Move remaining library-dependent components behind lazy loading
See references/patterns.md § "CSS Animation Replacements" for entrance animations, scroll reveals, and parallax patterns.
2.4 Fix Render-Blocking Resources
Symptoms: Lighthouse flags "Render blocking requests" with a CSS file. Critical chain shows document → CSS → font.
Fixes:
- Small CSS files (< 15 KiB): inline critical above-the-fold styles, load the rest async
- Font-dependent chains: preload fonts to break the
document → CSS → fontchain crossOrigin="anonymous"is required on font preloads — without it the browser fetches twice- All
@font-facerules needfont-display: swap - Prefer
next/fontwhich handles preloading andfont-displayautomatically
// app/layout.tsx — break the font chain
<head>
<link rel="preload" href="/fonts/YourFont.woff2" as="font" type="font/woff2" crossOrigin="anonymous" />
</head>
2.5 Optimize the LCP Element
Find the LCP element in the Lighthouse report under "Largest Contentful Paint element" in Diagnostics.
If LCP is text:
- Fix render-blocking CSS (§ 2.4)
- Preload the font that renders the text
- Ensure
font-display: swap
If LCP is an image:
- Add
priorityprop tonext/image(addsfetchpriority="high"and preloads) - Don't lazy-load LCP images — they must load eagerly
- For CSS
background-image, add<link rel="preload" as="image">in<head>
If LCP is a canvas/WebGL element:
- Render a static fallback image as initial content, swap in the canvas when ready
- The fallback should be an
<img>withfetchpriority="high" - The canvas itself should be deferred (§ 2.1)
2.6 Clean Up Dependencies
Checklist:
dependenciesvsdevDependencies: build tools, test frameworks, linters belong in devDependenciesbrowserslist: add["defaults and supports es6-module"]to skip unnecessary polyfills- Barrel file imports: import directly from specific files, not barrel files (
@/components) - Run
ANALYZE=true npm run buildafter adding new deps to catch unexpected bundle growth
2.7 Fonts
- Preload critical fonts with
<link rel="preload"> - Use
font-display: swapin all@font-facerules - Use
next/fontwhen possible — handles preloading and self-hosting automatically - Subset fonts if only using Latin characters (
glyphhangerorpyftsubset) - Audit font variants — check for weights/styles you don't actually use
2.8 Ensure Minification & Compression
Verify Next.js defaults (SWC minification, gzip/brotli) aren't overridden in next.config.
Step 3: Accessibility
All animation changes must preserve accessibility:
- Add a global
@media (prefers-reduced-motion: reduce)rule that kills animation duration - For JS animations, check
window.matchMedia('(prefers-reduced-motion: reduce)')before running
See references/patterns.md § "Reduced Motion" for the CSS snippet.
Step 4: Back/Forward Cache (bfcache)
Common failures:
- WebSocket usage: if only for HMR in dev, resolves in production automatically
Cache-Control: no-store: prevents bfcache — only use on pages with authenticated/sensitive data
Some bfcache failures are "Not actionable" or "Pending browser support" — skip those.
Working with the User
When the user shares Lighthouse results:
- Identify which of the above categories are flagged
- Ask for the bundle analyzer treemap if they haven't shared it
- Work through fixes in priority order, not all at once
- Verify the app builds after each change:
npm run build - Have the user re-run Lighthouse after fixes to confirm improvement