Next.js
02 / 06

Performance & Optimization

Next.js Performance & Optimization

Image Optimization

import Image from 'next/image';

// Optimized images with automatic sizing
export default function Page() {
  return (
    <div>
      {/* Local image */}
      <Image
        src="/hero.jpg"
        width={800}
        height={600}
        alt="Hero"
        priority  // Load eagerly for LCP
      />
      
      {/* Remote image */}
      <Image
        src="https://example.com/image.jpg"
        width={400}
        height={300}
        alt="Remote"
      />
      
      {/* Fill parent */}
      <div style={{ position: 'relative', width: '100%', height: '400px' }}>
        <Image
          src="/bg.jpg"
          fill
          style={{ objectFit: 'cover' }}
          alt="Background"
        />
      </div>
      
      {/* Placeholder */}
      <Image
        src="/photo.jpg"
        width={600}
        height={400}
        placeholder="blur"
        blurDataURL="data:image/png;base64,..."  
        alt="Photo"
      />
    </div>
  );
}

Font Optimization

// app/layout.tsx
import { Inter, Roboto_Mono } from 'next/font/google';
import localFont from 'next/font/local';

const inter = Inter({
  subsets: ['latin'],
  display: 'swap',
});

const robotoMono = Roboto_Mono({
  subsets: ['latin'],
  weight: ['400', '700'],
});

const customFont = localFont({
  src: './fonts/MyFont.woff2',
  display: 'swap',
});

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" className={inter.className}>
      <body>{children}</body>
    </html>
  );
}

Metadata & SEO

// Static metadata
import type { Metadata } from 'next';

export const metadata: Metadata = {
  title: 'My Page',
  description: 'Page description',
  keywords: ['next.js', 'react'],
  openGraph: {
    title: 'My Page',
    description: 'Page description',
    images: ['/og-image.jpg'],
  },
};

// Dynamic metadata
export async function generateMetadata(
  { params }: { params: { id: string } }
): Promise<Metadata> {
  const post = await fetchPost(params.id);
  
  return {
    title: post.title,
    description: post.excerpt,
    openGraph: {
      images: [post.image],
    },
  };
}

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free