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
| Prop | Description |
|---|---|
src | Image path or URL. |
alt | Required descriptive text for accessibility. |
width and height | Intrinsic dimensions in pixels (required for local images in static layout). |
priority | Preloads the image. Use for the largest above-the-fold image (LCP). |
fill | Fills the parent element. Use with sizes for responsive images. |
sizes | Describes how wide the image is at different viewport widths. |
quality | Integer from 1–100. Defaults to 75. |
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
| Strategy | When it loads |
|---|---|
beforeInteractive | Before the page becomes interactive. For critical scripts only. Place in _document.tsx. |
afterInteractive | After the page is interactive. Default. |
lazyOnload | During idle time. For low-priority scripts like chat widgets. |
worker | In a web worker (requires Partytown). |
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
