JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsnextjs
PrevNext

Learn the concept

Performance Optimization

nextjs
senior
performance

What performance optimization techniques does Next.js provide?

nextjs
performance
optimization
images
fonts
code-splitting
streaming
suspense
Quick Answer

Next.js provides automatic optimizations including code splitting per route, image optimization via next/image, font optimization with next/font, script loading control with next/script, Server Components to reduce JavaScript bundles, Suspense for streaming, automatic prefetching of links, and edge deployment capabilities.

Detailed Explanation

Built-in Optimizations

1. Code Splitting

  • Automatic per-route: Each page only loads its required JavaScript
  • Dynamic imports: next/dynamic for component-level splitting
  • Third-party bundling: optimizePackageImports for tree-shaking

2. Image Optimization (next/image)

  • Automatic format conversion (WebP, AVIF)
  • Responsive images with sizes attribute
  • Lazy loading by default
  • Blur placeholder while loading
  • Prevents Cumulative Layout Shift (CLS)

3. Font Optimization (next/font)

  • Zero layout shift (font-display: swap by default)
  • Self-hosted fonts (no external requests)
  • Automatic subsetting
  • Works with Google Fonts and local fonts

4. Script Optimization (next/script)

  • Control loading priority: beforeInteractive, afterInteractive, lazyOnload
  • Web Worker offloading with worker strategy
  • Inline scripts with proper hydration

5. Server Components

  • Zero client-side JavaScript for server-rendered components
  • Smaller bundle sizes
  • Faster initial page loads
  • Direct database/API access without waterfalls

6. Streaming & Suspense

  • Progressive HTML streaming
  • Loading states with Suspense boundaries
  • Faster Time to First Byte (TTFB)
  • Better perceived performance

7. Prefetching

  • Links in viewport are prefetched automatically
  • Route segments preloaded on hover
  • Configurable with prefetch prop

Advanced Optimizations

Bundle Analysis

Bash
npm install @next/bundle-analyzer

Route Segment Config

  • dynamic: Force static or dynamic
  • revalidate: Cache duration
  • fetchCache: Control fetch caching

Partial Prerendering (PPR)

  • Static shell with dynamic holes
  • Best of static and dynamic
  • Instant initial load with fresh content
  • More mature and stable in Next.js 14 with improved DX

Code Examples

Image Optimization Best PracticesTSX
import Image from 'next/image';

// Hero image - prioritize loading
export function Hero() {
  return (
    <Image
      src="/hero.jpg"
      alt="Hero image"
      width={1920}
      height={1080}
      preload // Load immediately, no lazy loading (replaces priority)
      placeholder="blur"
      blurDataURL="data:image/jpeg;base64,..." // Low-res placeholder
    />
  );
}

// Responsive image with sizes
export function ProductImage({ src, alt }: { src: string; alt: string }) {
  return (
    <Image
      src={src}
      alt={alt}
      fill // Fills parent container
      sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
      className="object-cover"
    />
  );
}

// next.config.js - Remote image domains
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'cdn.example.com',
        pathname: '/images/**',
      },
    ],
    formats: ['image/avif', 'image/webp'],
  },
};

Real-World Applications

Use Cases

Core Web Vitals Optimization

Using next/image with preload for LCP, next/font for CLS prevention, and code splitting for INP improvement

Third-Party Script Management

Using next/script with afterInteractive and lazyOnload strategies to prevent third-party scripts from blocking page load

Progressive Page Loading

Using Suspense boundaries and streaming to show content incrementally, improving perceived performance

Mini Projects

Performance Optimization Audit

intermediate

Take a poorly performing Next.js page and optimize with next/image, next/font, dynamic imports, and Suspense, measuring with Lighthouse

Bundle Size Optimization

advanced

Set up @next/bundle-analyzer, identify large dependencies, and optimize with dynamic imports and tree-shaking

Industry Examples

Walmart

Improved Core Web Vitals by 30% after adopting Next.js image optimization and automatic code splitting

TikTok

Uses Next.js for their web app with aggressive code splitting and streaming for fast time-to-interactive

Resources

Optimizing - Next.js Documentation

docs

Image Optimization

docs

Core Web Vitals

docs

Related Questions

What is next/image and why should you use it over the regular img tag?

junior
optimization
Previous
How does Middleware work in Next.js and what are common use cases?
Next
How does caching and revalidation work in Next.js?
PrevNext