An organizer uploads a poster that's 3,000 pixels wide and weighs 1.9 MB. Someone viewing it on a phone, in a 360-pixel slot, downloads the full 1.9 MB. While it arrives, the text takes the image's place and, when it appears, everything drops down at once. Something similar happens with fonts: the text is painted with one and then reflowed with another.

They're the two heaviest resources and the ones that move the page around the most, and neither can be fixed in the database server. Next.js offers two pieces, next/image and next/font, that handle the mechanical part: sizes, formats, reserving space and self-hosting. What they can't know is how much room the image will take up in your design, which one is important or which sources you trust. That's what this lesson is about, along with a consequence that's often forgotten: an image optimizer is a public service that runs on your CPU.

  1. What next/image does

import Image from 'next/image'

<Image src="/images/events/9f1c….webp" alt="" width={800} height={450} />

The result is an ordinary <img>, with attributes that would be tedious to write by hand:

<img
  loading="lazy" decoding="async" width="800" height="450" style="color:transparent"
  srcset="/_next/image?url=%2Fimages%2F…&w=828&q=75 1x,
          /_next/image?url=%2Fimages%2F…&w=1920&q=75 2x"
  src="/_next/image?url=%2Fimages%2F…&w=1920&q=75" alt="">
  • Sizes. srcset offers several widths and the browser chooses based on its screen.
  • Format. The optimizer, at /_next/image, looks at the Accept header and delivers WebP to browsers that support it.
  • Lazy loading. loading="lazy" delays the ones that are far from view.
  • Reserved space. With width and height, the browser knows the aspect ratio before downloading anything.

The versions are generated on the first request for each size and stored on disk, in .next/cache/images. Nothing happens at build time. If there are several instances, each one has its own copy.

width and height are the dimensions of the original, or at least its aspect ratio; the on-screen size is decided by the CSS. When the image is in the project and imported (import logo from './logo.png'), Next.js works them out on its own.

  1. sizes: the most forgotten prop

The browser chooses the image before calculating the layout, so it doesn't know how much space it will take up. sizes tells it:

What Next.js generates What the browser assumes
With width, without sizes Two candidates, 1x and 2x A fixed size
With fill, without sizes Every screen width That it takes up the full width of the window
With sizes Every width, including the small ones Whatever you tell it

Forgetting sizes with fill is the most expensive mistake: a 400-pixel card on a 1,920-pixel monitor downloads the 1,920-pixel image. It's written as a list of conditions; the last one, without a condition, is the default value:

// Two columns from 40rem, and at most 30rem each
sizes="(min-width: 64rem) 30rem, (min-width: 40rem) 50vw, 100vw"

It doesn't have to be exact. It has to be close and match the design: if someone changes the grid to three columns, it has to be changed here too. The possible widths come from two lists, deviceSizes and imageSizes, whose default values work for almost everything.

  1. AgendaViva's posters

We don't know the dimensions of the posters, because in 06-05 we didn't store them. That's what fill is for: the image fills its container, which must be positioned and have a height or an aspect ratio of its own; otherwise, it will measure zero.

// components/event-poster.tsx
import Image from 'next/image'
import { imageUrl } from '@/lib/images'

interface Props {
  image: string
  alt: string
  sizes: string
  isMain?: boolean
}

export function EventPoster({ image, alt, sizes, isMain = false }: Props) {
  return (
    <div className="relative aspect-video overflow-hidden rounded-md bg-border">
      <Image
        src={imageUrl(image)}
        alt={alt}
        fill
        sizes={sizes}
        loading={isMain ? 'eager' : 'lazy'}
        fetchPriority={isMain ? 'high' : 'auto'}
        className="object-cover"
      />
    </div>
  )
}
// EventDetails: replaces the <img> from 06-05
{event.image && (
  <div className="my-4">
    <EventPoster
      image={event.image}
      alt={`Poster for "${event.title}"`}
      sizes="(min-width: 64rem) 62rem, 100vw"
      isMain
    />
  </div>
)}

// EventCard: the first thing inside the <article>
{event.image && (
  <div className="mb-3">
    <EventPoster
      image={event.image}
      alt=""
      sizes="(min-width: 64rem) 30rem, (min-width: 40rem) 50vw, 100vw"
    />
  </div>
)}
  • relative and aspect-video meet both of fill's conditions. The background color acts as a placeholder while it loads.
  • object-cover crops whatever doesn't fit. With object-contain you'd see it whole, with bands.
  • It's still a Server Component. Image is a client component inside, but it only receives strings and numbers. Props that are functions, such as onLoad or loader, would require whoever passes them to be a client component (03-03).
  • The inline style the component writes is one of the reasons for 'unsafe-inline' in style-src.

The ImagePicker preview (06-05) keeps its <img>: its source is a blob: URL, which only exists in that browser and the optimizer can't read. There it does make sense to silence the rule on that line, // eslint-disable-next-line @next/next/no-img-element, with the reason written down.

3.1. Alternative text

alt is mandatory and it isn't a title. It replaces the image for people who can't see it, and the right text depends on the context:

Case alt
On the card, next to the title "": decorative. Repeating the title would make it be read twice
On the event page, where it's content What it is: Poster for "Jazz Night"
An image that's a link The destination, not the picture
A chart or a map The information it provides, or a nearby text

"Poster for…" is the most we can claim without having seen it. If the poster contains information that isn't on the event page, such as the list of musicians, people who can't see it miss out: the solution is to ask the organizer for that text (exercise 2), not to guess it. alt="" and no alt at all are different things: without it, some screen readers read out the file name.

3.2. The main image

The poster on the event page is probably the largest element visible on load, what the metrics call LCP (10-01). With lazy, the browser would be slow to request it, because it has to lay out the page first. Three options:

Option Effect
loading="eager" It isn't delayed
fetchPriority="high" It goes ahead of other requests. On its own it does not remove lazy loading
preload Adds a <link rel="preload"> in the <head>, before the browser finds the <img>

The documentation recommends the first two in most cases, and preload only when you know for sure which image is the main one and it pays to make it discoverable earlier. Our event page is in the static shell, so the <img> shows up right away; besides, React can preload eager images on its own while rendering. Don't combine preload with the others.

In older projects you'll see priority: it's deprecated since 16, and preload replaces it. Apply this to one image per page; if everything is a priority, nothing is. On the home page, which card deserves it will be decided by measuring, in 10-01.

3.3. Placeholders

placeholder="blur" shows a blurred version while it loads. With imported images it's automatic; with ours we'd have to generate a thumbnail on upload, store it and pass it in blurDataURL, which is included in the HTML of every card. For an events guide, a background color gives almost the same result at no cost. The option requires data: in img-src, which our CSP already allows.

  1. The optimizer is a door

/_next/image is a public URL with three parameters: which image, what width and what quality. Anyone can call it by hand. Without limits, it could be used to optimize other people's images at your expense, to make your server request addresses on your internal network (SSRF, 08-06), or to exhaust disk and CPU by requesting a thousand variants. The images options are, above all, an allowlist:

// next.config.ts (added)
images: {
  // Only posters, and no parameters in the URL
  localPatterns: [{ pathname: '/images/events/**', search: '' }],
  // Our originals don't exceed 2 MB
  maximumResponseBody: 3_000_000,
  // Don't follow redirects
  maximumRedirects: 0,
  // Limit for the disk cache
  maximumDiskCacheSize: 500_000_000,
},
Option Default What it controls
localPatterns Any local path, without parameters Which paths on the site can be optimized. Everything else responds with 400
remotePatterns None Which external addresses. Without it, none
qualities [75] Which qualities are accepted. Since 16 they must be declared
maximumResponseBody 50 MB Maximum size of the original
maximumRedirects 3 How many remote redirects are followed
dangerouslyAllowLocalIP false Whether private network addresses can be requested
dangerouslyAllowSVG false Whether SVGs, which can contain scripts, are served
  • localPatterns is restricted because the default includes /api/…: the optimizer can call your Route Handlers. Imported images keep working, since Next.js adds their folder on its own.
  • search: '' matters. If it's omitted, any parameter is accepted, and every ?x=1, ?x=2 is a new entry on disk.
  • There's no remotePatterns: AgendaViva doesn't display external images. If it were needed, make it as specific as possible. hostname: '**' turns your server into a proxy for anyone. And keep in mind that redirects are not checked against the list; hence maximumRedirects: 0.
  • A quality outside the list is adjusted to the nearest one in the component, and responds with 400 if requested by hand.
  • images.domains is deprecated. It doesn't let you restrict the protocol or the path.

An external domain doesn't change the CSP: the browser still requests /_next/image, from this origin. It's the server that connects outside.

Two more limits, which aren't options. The optimizer doesn't forward cookies or headers, so it can't read images that require a session; and if it could, it would store them in a shared cache. For private content, use unoptimized and a Route Handler that checks permission. And it processes files that other people upload: a bug in the library that decodes them is your bug, as the October 2026 advisory reminded us (08-06). Keeping up to date covers this too.

4.1. How long a version lasts

The lifetime is the greater of two values: minimumCacheTTL, four hours by default, and the original's Cache-Control. Ours declares a year and immutable (06-05), because each upload uses a new key. This is where it pays off: there's no way to invalidate an optimized version, and we don't need one, since changing the poster changes the URL.

If your images keep their name when they're modified, use a low TTL or add a version to the path.

4.2. Formats

WebP by default. You can add AVIF with formats: ['image/avif', 'image/webp']: according to the documentation it compresses about 20% more and takes 50% longer to encode, with one copy on disk per format. For a modest server, WebP is the recommended balance. If there's a CDN in front, it must forward Accept and vary on it, or it will end up serving WebP to browsers that don't understand it.

4.3. A different optimizer

If the posters move to a storage service with its own image service, it can do the work. You replace the loader, the function that builds each URL:

// Example only: lib/image-loader.ts
'use client'

interface Params {
  src: string
  width: number
  quality?: number
}

export default function imageLoader({ src, width, quality }: Params): string {
  return `https://images.agendaviva.example${src}?width=${width}&quality=${quality ?? 75}`
}

// next.config.ts
images: { loader: 'custom', loaderFile: './lib/image-loader.ts' },

The rest of the component stays: srcset, lazy loading, reserved space. Now the browser does go to another domain, and it has to be added to img-src. It's also the way out for a static export or a server with no CPU to spare (11-05).

  1. Fonts

Loading a font from a third party's server has three drawbacks: one more connection before the text is visible, the fact that your visitor is on your page (their IP travels to that third party) and a jump when the temporary font is swapped. next/font avoids them:

  • It downloads the font at build time and serves it from your domain. The browser makes no outside requests, and the CSP's font-src 'self' is enough.
  • It generates an adjusted fallback font: it modifies the metrics of a system font so that it takes up the same space as the final one. When one is swapped for the other, the lines don't move.
  • It preloads the files on the routes that use it.
// app/fonts.ts
import { Bricolage_Grotesque, Source_Sans_3 } from 'next/font/google'

export const bodyFont = Source_Sans_3({
  subsets: ['latin'],
  variable: '--typeface-body',
})

export const headingFont = Bricolage_Grotesque({
  subsets: ['latin'],
  variable: '--typeface-heading',
})
// app/layout.tsx (imports joinClasses and both fonts)
<html
  lang="en"
  className={joinClasses(bodyFont.variable, headingFont.variable)}
  suppressHydrationWarning
>
/* app/globals.css: inside @theme inline */
--font-sans: var(--typeface-body), system-ui, sans-serif;
--font-heading: var(--typeface-heading), system-ui, sans-serif;

/* and in @layer base */
h1, h2, h3 {
  font-family: var(--typeface-heading), system-ui, sans-serif;
}
  • Both are variable fonts: a single file contains every weight, and weight isn't needed. With one that isn't, it's mandatory, and each weight is another file.
  • variable declares a CSS variable on the element that has the class. --font-sans is Tailwind's default family: redefining it changes all the text.
  • subsets indicates which parts are preloaded. latin covers Spanish, Catalan and English. Spaces in the name are written as underscores.
  • display is 'swap' by default: you see the fallback until the real one arrives. 'optional' gives up on the real one if it's slow, with no visible change at all.
  • A single module. Each call creates a copy of the font; calling it in two files would serve it twice.

Two families is a sensible limit. Each one is another download, and the difference they make shrinks quickly. global-error.tsx doesn't use these fonts: it has its own document.

5.1. Local fonts

If the font is a corporate one, or you don't want to depend on the network at build time, there's next/font/local:

// Example only
import localFont from 'next/font/local'

export const bodyFont = localFont({
  src: './fonts/vallenar-variable.woff2', // Relative to this file
  weight: '200 900',
  variable: '--typeface-body',
})
next/font/google next/font/local
Source Google's catalog, at build time A file in your repository
Network at build time Yes No
Visitor requests to third parties None None
Subsetting by alphabet Automatic You do it, or you serve the whole font
Adjusted fallback Yes Yes, based on Arial or Times New Roman
License Open Check it: not all of them allow serving the font on the web

A CI server without internet access forces you to use the second. Store the files as woff2, outside public/: that way they get a fingerprinted name and are cached forever by the browser.

  1. The jumps, one by one

Unexpected layout shift is measured with the CLS metric (10-01). These are its causes and what we've done about each one:

Cause Remedy In AgendaViva
Image without dimensions width/height, or a container with an aspect ratio aspect-video
A font that changes the lines Adjusted fallback next/font
A Suspense hole smaller than its content A skeleton of the same size CardsSkeleton, EventDetailsSkeleton (04-04)
A banner that appears at the top Reserve its height or overlay it SiteNotice: covered in 10-01
A theme that changes after painting A script before the content 03-04
Iframes and ads A container with a minimum height None

Cards with and without a poster have different heights, but that isn't a jump: their height is known from the start.

  1. Video

Next.js doesn't optimize video. For your own, a <video> with controls, preload="none", poster, dimensions and a <track> for subtitles is enough; autoplay only when muted and never for anything that must be understood. A large file doesn't go in public/, but in a storage service or a service that adapts quality to the connection.

For one hosted on a platform, an <iframe> with title and loading="lazy", or better, an image that loads the player when clicked: it avoids a third party's scripts and cookies until someone decides to watch it. In both cases you need to extend the CSP, media-src or frame-src, and in the second, ask for consent.

  1. Checking it

npm run build && npm run start
# Take the optimizer URL from the HTML of an event page with a poster and request it as each browser would
curl -sI -H 'Accept: image/webp' 'localhost:3000/_next/image?url=%2Fimages%2Fevents%2FKEY.jpg&w=640&q=75'
# These must respond with 400
curl -so /dev/null -w '%{http_code}\n' 'localhost:3000/_next/image?url=%2Fapi%2Fv1%2Ffilters&w=640&q=75'
curl -so /dev/null -w '%{http_code}\n' 'localhost:3000/_next/image?url=https%3A%2F%2Fexample.com%2Fa.png&w=640&q=75'
curl -so /dev/null -w '%{http_code}\n' 'localhost:3000/_next/image?url=%2Fimages%2Fevents%2FKEY.jpg&w=640&q=100'

In the network panel, at a phone's width, check which width gets downloaded in the list: it should be close to the size of the card multiplied by the screen's pixel density. If it's always the largest, sizes is missing or wrong. In the fonts filter, every address should be on your domain.

In development, images are optimized on demand and without a lasting cache, so the timings aren't representative.

Common Mistakes and Tips

  • fill without sizes: the window's width gets downloaded.
  • fill in a container with no position or no height: it covers the page or isn't visible.
  • Marking every image as a priority.
  • Using priority, which is deprecated, or combining preload with loading.
  • remotePatterns with broad wildcards, or without search.
  • Leaving localPatterns open with Route Handlers that return images.
  • Enabling SVG so that "the logo works". Your own SVG is served with unoptimized or written in the JSX.
  • Optimizing private images.
  • Changing the content without changing the URL.
  • Linking Google Fonts with <link>: the CSP blocks it, and if it doesn't, it leaks visits.
  • Calling the font in several files, or adding families out of habit.
  • alt that repeats the title, or no alt at all.

Exercises

Exercise 1: working out sizes

Write sizes for: (a) a poster at full width on mobile and in a 20rem side column from 48rem; (b) a gallery with one column, two from 40rem and four from 80rem, with the container capped at 80rem; (c) a 48-pixel avatar. What happens if in (a) you write just 100vw?

Solution

  • (a) (min-width: 48rem) 20rem, 100vw
  • (b) (min-width: 80rem) 20rem, (min-width: 40rem) 50vw, 100vw. From 80rem on the container doesn't grow, so each column measures 20rem even if the window is larger.
  • (c) None: with width={48} height={48} it's a fixed size, and Next.js offers 1x and 2x.

With 100vw it looks the same, but on a 1,920-pixel desktop with a density-2 screen it requests the 3,840 version for a 320 slot. There's no error at all; that's why you have to check it in the network panel.

Exercise 2: real alternative text

Design the change so that the organizer writes the poster's alternative text: data, form, validation and use. Should it be mandatory? What's shown while there isn't one?

Solution

// Practice only
// lib/db/schema.ts, in events
imageAlt: text('image_alt'),

// lib/schemas/event.ts
imageAlt: text({ min: 0, max: 250 }).transform((value) => value || null),

// EventDetails
alt={event.imageAlt ?? `Poster for "${event.title}"`}

The field goes in the poster form, next to the image it describes, with a specific hint: "Write what the poster says that isn't already on the event page". Making it mandatory produces filler text such as "poster", which is worse than the default value; you can remind the organizer before submitting for review. When the image is replaced it has to be cleared, because it described a different one. And since it's event page content, changing it calls invalidateEvent.

Exercise 3: reviewing a configuration

Point out the risks in this configuration and propose another. The site shows sponsor logos from https://media.example.com/logos/.

images: {
  domains: ['media.example.com'],
  remotePatterns: [{ hostname: '**' }],
  dangerouslyAllowSVG: true,
  dangerouslyAllowLocalIP: true,
  qualities: Array.from({ length: 100 }, (_, i) => i + 1),
  minimumCacheTTL: 0,
}

Solution

images: {
  localPatterns: [{ pathname: '/images/events/**', search: '' }],
  remotePatterns: [new URL('https://media.example.com/logos/**')],
  maximumRedirects: 0,
  maximumResponseBody: 3_000_000,
}

hostname: '**' accepts any server, including over http:, and with local addresses allowed it reaches the internal network: it's an SSRF on a plate. domains is deprecated and unnecessary. SVGs can contain scripts; if the logos are SVGs, they're displayed with unoptimized (and img-src in the CSP) or converted. A hundred qualities are a hundred variants per width that anyone can request to fill up the disk. A TTL of zero forces endless revalidation.

Conclusion

next/image turns an image into a set of sizes, delivers them in a modern format and reserves their space; you provide sizes, the aspect ratio and which one is the main image. Its optimizer is a public service, and the images options are its allowlist. next/font serves fonts from your domain with a fallback that doesn't move the lines. AgendaViva's posters now weigh what each screen needs, and nothing jumps when they arrive.

The page looks good inside AgendaViva. But most people will arrive from outside: a search result, a link in a chat, a tab among twenty others. All of that is built with information that isn't in the body of the page and that today is the same everywhere: "AgendaViva". The next lesson is Metadata and Open Graph Images.

© Copyright 2026. All rights reserved