Skip to main content
Next.js includes built-in optimizations for images, fonts, scripts, and code-splitting. Most of these work the same way in both the Pages Router and App Router.

Image optimization

The next/image component automatically optimizes images on demand:
  • Serves modern formats (WebP, AVIF).
  • Resizes images to match the rendered size.
  • Lazy loads images by default.
  • Prevents Cumulative Layout Shift with reserved space.
pages/index.tsx

Key props

Remote images

To allow images from external domains, add them to next.config.js:
next.config.js

Font optimization

Use next/font to load fonts with zero layout shift. Fonts are downloaded at build time and self-hosted from your own domain.

Google Fonts

pages/_app.tsx

Local fonts

pages/_app.tsx
next/font ensures font files are not sent to Google (or any third party) at request time, improving privacy and performance.
next/font works the same way in the App Router. Apply the font class to your root layout.tsx to use it site-wide.

Script loading

The next/script component lets you control when third-party scripts load:
pages/index.tsx

Loading strategies

Inline scripts

Always add an id to inline scripts so Next.js can track and optimize them.

Lazy loading

Next.js supports lazy loading for components and libraries using next/dynamic.

Dynamic component imports

The HeavyChart component is only downloaded when it first renders.

Disabling SSR for a component

Some libraries (like those that access window) cannot run on the server. Disable SSR for them:

Lazy loading libraries

You can also lazy load third-party libraries inside event handlers:

Bundle analysis

Use @next/bundle-analyzer to visualize which modules contribute to your bundle size.
next.config.js
Run the analyzer:
This opens two treemap views in your browser: one for the client bundle and one for the server bundle.