CW
Next.js Performance

Performance Optimization

Core Web Vitals, image optimization, code splitting, caching strategies, and performance monitoring.

Advertisement

Performance Optimization

Core Web Vitals, image optimization, code splitting, caching strategies, and performance monitoring.

Overview

Performance is critical for user experience and SEO. Next.js provides built-in optimizations and patterns to help you build fast applications.

Key Concepts

  • Core Web Vitals — LCP, FID, CLS metrics
  • Image Optimization — Next.js Image component
  • Code Splitting — Dynamic imports and lazy loading
  • Caching — Router cache, data cache, full route cache
  • Bundle Analysis — Identify and remove large dependencies

Code Examples

// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    formats: ['image/avif', 'image/webp'],
    remotePatterns: [
      {
        protocol: 'https',
        hostname: '**.example.com',
      },
    ],
  },
  experimental: {
    optimizePackageImports: ['lodash', 'date-fns'],
  },
};

module.exports = nextConfig;
// components/optimized/Image.tsx
import Image from 'next/image';

export function OptimizedImage({ src, alt }) {
  return (
    <Image
      src={src}
      alt={alt}
      width={800}
      height={600}
      placeholder="blur"
      blurDataURL="data:image/jpeg;base64,/9j/4AAQSkZJRg..."
      sizes="(max-width: 768px) 100vw, 50vw"
      priority={false}
    />
  );
}
// Dynamic imports for code splitting
import dynamic from 'next/dynamic';

const HeavyComponent = dynamic(() => import('./HeavyComponent'), {
  loading: () => <p>Loading...</p>,
  ssr: false,
});

export function Dashboard() {
  return (
    <div>
      <h1>Dashboard</h1>
      <HeavyComponent />
    </div>
  );
}

Caching Strategies

// Data fetching with revalidation
async function getProducts() {
  const res = await fetch('https://api.example.com/products', {
    next: { revalidate: 3600 }, // Cache for 1 hour
  });
  return res.json();
}

// Route segment config
export const dynamic = 'force-static';
export const revalidate = 60; // Revalidate every 60 seconds

Performance Monitoring

// app/layout.tsx
import { Analytics } from '@vercel/analytics/react';
import { SpeedInsights } from '@vercel/speed-insights/next';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <Analytics />
        <SpeedInsights />
      </body>
    </html>
  );
}

Best Practices

  1. Use Next/Image — Automatic optimization, lazy loading, WebP
  2. Dynamic Imports — Load components only when needed
  3. Parallel Routes — Load multiple routes simultaneously
  4. Prefetching — Next.js prefetches linked routes by default
  5. Bundle Analysis — Use @next/bundle-analyzer to find large packages

Summary

  • Next.js provides built-in performance optimizations
  • Use Image component for automatic image optimization
  • Implement code splitting with dynamic imports
  • Leverage caching strategies for data and routes
  • Monitor performance with Vercel Analytics