Image optimization
Thenext/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 tonext.config.js:
next.config.js
Font optimization
Usenext/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
Thenext/script component lets you control when third-party scripts load:
pages/index.tsx
Loading strategies
Inline scripts
id to inline scripts so Next.js can track and optimize them.
Lazy loading
Next.js supports lazy loading for components and libraries usingnext/dynamic.
Dynamic component imports
HeavyChart component is only downloaded when it first renders.
Disabling SSR for a component
Some libraries (like those that accesswindow) 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
