Suleman Ahmed - BlogOptimizing Next.js App Performance: Font, Image, and Scripts

Web performance is critical for user retention and search engine optimization. Next.js provides built-in tools to help us optimize images, fonts, and scripts. Let's explore how to use them effectively.

1. Next-Level Image Optimization

The Next.js `<Image />` component automatically optimizes images on-the-fly, serving WebP or AVIF versions. To prevent Layout Shift (CLS), you must always provide width/height or use the `fill` layout.

{"value":{"_key":"64434dd32a67","_type":"code","code":"import Image from 'next/image';\n\nexport default function HeroBanner() {\n return (\n <div className=\"relative w-full h-[400px]\">\n <Image\n src=\"/hero.jpg\"\n alt=\"Hero banner illustration\"\n fill\n priority\n className=\"object-cover\"\n sizes=\"(max-width: 768px) 100vw, 50vw\"\n />\n </div>\n );\n}","filename":"","language":"typescript"},"isInline":false,"index":3}

2. Zero Layout Shift Fonts

Google Fonts loaded through `next/font/google` are hosted locally inside the build bundle. This prevents the browser from showing fallback fonts while loading, avoiding text flashes and layout shifts.

{"value":{"_key":"c5b5d47e0189","_type":"code","code":"import { Inter } from 'next/font/google';\n\nconst inter = Inter({\n subsets: ['latin'],\n display: 'swap',\n variable: '--font-inter',\n});\n\nexport default function Layout({ children }) {\n return (\n <html lang=\"en\" className={inter.variable}>\n <body className=\"font-sans\">{children}</body>\n </html>\n );\n}","filename":"","language":"typescript"},"isInline":false,"index":6}

3. Strategic Script Loading

Third-party scripts (like analytics) can drag down performance. The Next.js `<Script />` component lets you decide when scripts should execute.

{"value":{"_key":"4f299f719df0","_type":"code","code":"import Script from 'next/script';\n\nexport default function Analytics() {\n return (\n <Script\n src=\"https://example.com/analytics.js\"\n strategy=\"afterInteractive\" // Loads during idle browser time\n />\n );\n}","filename":"","language":"typescript"},"isInline":false,"index":9}

By implementing these optimizations, your Next.js application will achieve optimal Lighthouse performance scores.