English

Optimize your Next.js 15 apps for maximum performance with these proven techniques.

Image Optimization

import Image from 'next/image';

// Automatic optimization and lazy loading
<Image
  src="/hero.jpg"
  alt="Hero"
  width={1200}
  height={600}
  priority // Above the fold
  placeholder="blur"
  blurDataURL="data:image/..." // Or use import
/>

// Responsive images
<Image
  src="/product.jpg"
  alt="Product"
  fill
  sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
  className="object-cover"
/>

Dynamic Imports

import dynamic from 'next/dynamic';

// Code splitting for heavy components
const HeavyChart = dynamic(() => import('@/components/HeavyChart'), {
  loading: () => <Skeleton />,
  ssr: false, // Client-side only
});

// Conditional loading
const AdminPanel = dynamic(() => import('@/components/AdminPanel'), {
  loading: () => <div>Loading...</div>,
});

export default function Dashboard({ isAdmin }) {
  return <div>{isAdmin && <AdminPanel />}</div>;
}

Caching Strategies

// Route segment config
export const revalidate = 3600; // Revalidate every hour
export const dynamic = 'force-static'; // Force static generation
export const fetchCache = 'force-cache';

// Data fetching with caching
async function getData() {
  const res = await fetch('https://api.example.com/data', {
    next: {
      revalidate: 3600, // ISR
      tags: ['products'], // For on-demand revalidation
    },
  });
  return res.json();
}

// On-demand revalidation
import { revalidateTag } from 'next/cache';

export async function POST(req: Request) {
  revalidateTag('products');
  return Response.json({ revalidated: true });
}

Bundle Analysis

// next.config.js
const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
});

module.exports = withBundleAnalyzer({
  // config
});
ANALYZE=true npm run build

Streaming and Suspense

import { Suspense } from 'react';

export default function Page() {
  return (
    <>
      <Header />
      <Suspense fallback={<PostsSkeleton />}>
        <Posts />
      </Suspense>
      <Suspense fallback={<CommentsSkeleton />}>
        <Comments />
      </Suspense>
    </>
  );
}

Parallel Data Fetching

export default async function Page() {
  // Parallel fetching
  const [user, posts] = await Promise.all([getUser(), getPosts()]);

  return (
    <>
      <UserProfile user={user} />
      <PostList posts={posts} />
    </>
  );
}

These optimizations ensure your Next.js app delivers peak performance.

0
0
0
0