Open four AgendaViva event pages in four tabs: all four are called "AgendaViva". Paste a link to one of them into a chat: you get the site's name and the same description as for any other page. For an events guide, whose reach depends on people sharing links, that means giving up half the visits.

The browser, search engines and messaging apps don't read the page the way a person does: they look at the <head>. Next.js generates that content from data you return, without you writing tags, and it does two things that are hard by hand: merging what each layout says with what the page says, and deciding when it's sent if it depends on a query. With Cache Components, that second part has its own rules, and it's worth knowing them before a shared link goes out without a title.

  1. The metadata object

A layout or a page exports metadata. We were already doing it in app/layout.tsx; now it'll be the base for the whole site:

// app/layout.tsx
import type { Metadata, Viewport } from 'next'
import { SITE_DESCRIPTION, SITE_NAME, SITE_URL } from '@/lib/site'

export const metadata: Metadata = {
  metadataBase: new URL(SITE_URL),
  title: {
    default: `${SITE_NAME}: what's on in Vallenar del Río`,
    template: `%s · ${SITE_NAME}`,
  },
  description: SITE_DESCRIPTION,
  applicationName: SITE_NAME,
  openGraph: { siteName: SITE_NAME, locale: 'en_US', type: 'website' },
  twitter: { card: 'summary_large_image' },
}
// lib/site.ts (added)
export const SITE_DESCRIPTION = 'Concerts, theater, exhibitions and workshops in Vallenar del Río'
  • title.template applies to the titles of child segments, not to the file's own title. That's why default is mandatory: it's what pages that say nothing use.
  • title.absolute, in a page, ignores the template. We'll use it where the site name would be redundant.
  • metadataBase completes relative addresses. canonical and social images must be absolute, and this way they're written as /events.

The leading slash doesn't behave as in an ordinary URL: if metadataBase were https://example.com/guide, /events would give https://example.com/guide/events. Metadata is appended to the base, not substituted for it.

You don't need to set charset and viewport: Next.js always includes them. And don't write <title> or <meta> in the layout: they'd end up duplicated and without the order streaming needs.

1.1. How they're merged

Next.js evaluates the segments from the root down to the page and merges them shallowly: if two define the same field, the one closest to the page wins, in full. Nothing is merged inside it.

// app/layout.tsx:  openGraph: { siteName: 'AgendaViva', locale: 'en_US' }
// page:            openGraph: { title: 'Venues' }
// result:          og:title is "Venues", but there's no longer og:site_name or og:locale

It's the usual reason why "the image doesn't show up on this page". The solution is a function that builds the complete object, used by every page:

// lib/metadata.ts
import type { Metadata } from 'next'
import { SITE_NAME } from '@/lib/site'

export const SHARED_IMAGE = {
  url: '/opengraph-image',
  width: 1200,
  height: 630,
  alt: "AgendaViva, Vallenar del Río's cultural events guide",
}

interface MetadataInput {
  title: string
  description: string
  path: string
  hasOwnImage?: boolean
}

export function createMetadata({
  title,
  description,
  path,
  hasOwnImage = false,
}: MetadataInput): Metadata {
  return {
    title,
    description,
    alternates: { canonical: path },
    openGraph: {
      title,
      description,
      url: path,
      siteName: SITE_NAME,
      locale: 'en_US',
      type: 'website',
      // The property must be absent: undefined would also hide the segment's image
      ...(hasOwnImage ? {} : { images: [SHARED_IMAGE] }),
    },
  }
}
// app/(public)/venues/page.tsx
export const metadata = createMetadata({
  title: 'Venues',
  description: "Theaters, halls and community centers in Vallenar del Río, and what's on at each.",
  path: '/venues',
})

// app/(public)/page.tsx
export const metadata: Metadata = {
  ...createMetadata({
    title: `${SITE_NAME}: what's on in Vallenar del Río`,
    description: SITE_DESCRIPTION,
    path: '/',
  }),
  title: { absolute: `${SITE_NAME}: what's on in Vallenar del Río` },
}

The home page needs absolute: its segment hangs from the root, and the template would add "· AgendaViva" to a title that already contains it. For now /events gets the same treatment as the venues; since it has filters, we'll come back to it in 09-04.

Don't put canonical in the root layout. Every page would inherit it, and each one would declare that its official version is the home page: an effective way of disappearing from search engines.

  1. generateMetadata

An event page depends on the data. Instead of an object, you export a function, which receives the same as the page:

// app/(public)/events/[slug]/page.tsx (added)
export async function generateMetadata({ params }: Pick<Props, 'params'>): Promise<Metadata> {
  const { slug } = await params
  const details = await getEventDetails(slug)
  if (!details) return { title: 'Event not found' }

  const { event, venue } = details
  const canceled = event.status === 'canceled'

  return createMetadata({
    title: canceled ? `Canceled: ${event.title}` : event.title,
    description: `${formatDateTime(event.startsAt)}, ${venue.name}. ${event.summary}`,
    path: `/events/${event.slug}`,
    hasOwnImage: true,
  })
}
  • It isn't one more query. getEventDetails has been cached since 05-03; the page and the metadata read the same entry, with the same tag. When an administrator publishes and invalidateEvent is called, both are refreshed. With an uncached function you'd have to wrap it in React.cache (04-03).
  • generateMetadata always runs on the server, and can only be exported from a Server Component. A file can't export both metadata and generateMetadata.
  • The nonexistent event gets a title, nothing more. It's the page that calls notFound(), and Next.js adds noindex. It could also be called here.
  • searchParams is only available in pages, not in layouts.
  • The data is escaped. A title with < or quotes doesn't break the <head>.

The second argument, parent, is a promise with the already resolved metadata of the parent segments, in case you want to extend something instead of replacing it. With createMetadata we don't need it. Do the same on the venue page, with getVenueBySlug and without hasOwnImage.

  1. When it's sent

Metadata goes in the <head>, which is the first thing in the response. If it depends on a slow query, there are two possible behaviors: wait, and delay the whole page, or send the page and send the metadata afterwards. Next.js does the latter with browsers, and calls it metadata streaming: the tags arrive later, at the end of the <body>, and are applied just the same.

flowchart TD
    A["What does the metadata depend on?"] --> B["Nothing, or cached data<br/>with params known at build time"]
    A --> C["The request or uncached data"]
    B --> D["It goes in the shell's head"]
    C --> E{"Who's asking?"}
    E -->|Browser or Googlebot| F["Shell first,<br/>tags later through the stream"]
    E -->|HTML-limited bot| G["No shell: it waits<br/>and they go in the head"]

For AgendaViva:

Route Metadata When it arrives
/, /venues Static object In the shell
Event page on the generateStaticParams list Function with cached data In the shell
Event page not on the list, first visit params is known at request time Through the stream
The same one, afterwards Already generated (05-05) In the shell
/events with filters (09-04) Depends on searchParams Through the stream

HTML-limited bots are those that don't run JavaScript or look at the complete document: those of social networks and messaging apps, and some search engines, such as Bing. Next.js recognizes them by their User-Agent, stops serving them the shell and waits until the metadata is ready. Googlebot isn't among them: according to the documentation, it handles metadata that arrives later just fine. The list can be changed with htmlLimitedBots, which replaces the built-in one; with /.*/ metadata streaming is turned off for everyone. Unless an important bot is missing from the list, leave it alone.

You already saw the practical consequence in 05-02: for those bots rendering is repeated at request time, and the data must be available then.

3.1. The dynamic metadata error

Suppose a page is fully prerenderable and only its title reads a cookie. Next.js stops:

Route "/help": Next.js encountered runtime data in `generateMetadata()`.

The reason is that it can't tell an oversight from an intention. The whole page could be static and would become dynamic because of a title. There are three ways out:

  1. Make it independent of the request: a static object or, if it varies by parameter, generateStaticParams.
  2. Cache what it queries, with 'use cache' in the function or in the data function. If you put it in generateMetadata, what you return must be serializable, and a URL instance isn't: write strings.
  3. Declare it, with a component that renders nothing and waits at request time:
// Example only
import { connection } from 'next/server'

async function DynamicMarker() {
  await connection()
  return null
}

// In the page, inside <Suspense>
<Suspense fallback={null}><DynamicMarker /></Suspense>

You won't see it in AgendaViva, because SiteNotice is already a hole on every public page. That's a coincidence, not a permission: if it's ever removed, the error will appear wherever the metadata depends on the request and nothing else does.

generateMetadata doesn't need <Suspense>, nor could it have one: it isn't part of the tree. And if an exception is thrown inside it, the page fails; that's why only what's essential is queried there.

  1. Open Graph and cards

When you paste a link, the app downloads the page and looks for og: tags. It's a 2010 format that almost all of them use. The twitter: tags are a variant; Next.js fills in the ones you don't specify with the Open Graph ones, which is why we only set card: 'summary_large_image', which asks for the large image.

What people see is, above all, the image. There are three ways to provide it:

Way What for
openGraph.images in the metadata An address that already exists
An opengraph-image.png file in a segment A fixed image. Its alternative text goes in opengraph-image.alt.txt
opengraph-image.tsx Generating it from the data

The precedence is surprising: openGraph.images declared in the page beats the file, even if it's in the same folder; and the other way round, if a page defines openGraph without images and has no file of its own, it can lose the inherited one. createMetadata covers both cases with hasOwnImage.

4.1. The shared image

// app/opengraph-image.tsx
import { ImageResponse } from 'next/og'
import { SITE_DESCRIPTION, SITE_NAME } from '@/lib/site'

export const alt = "AgendaViva, Vallenar del Río's cultural events guide"
export const size = { width: 1200, height: 630 }
export const contentType = 'image/png'

export default function SiteImage() {
  return new ImageResponse(
    (
      <div
        style={{
          width: '100%',
          height: '100%',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          padding: 80,
          background: '#115e59',
          color: '#ffffff',
        }}
      >
        <div style={{ fontSize: 110, fontWeight: 700 }}>{SITE_NAME}</div>
        <div style={{ fontSize: 44 }}>{SITE_DESCRIPTION}</div>
      </div>
    ),
    size,
  )
}

ImageResponse turns JSX into a PNG. It isn't a browser: it supports a subset of CSS, with flexbox and without grid; every container with several children needs display: 'flex'; there's no Tailwind, no tokens and none of your components with hooks. Colors are written out. The whole thing, with fonts and images, can't exceed 500 KB.

Since it depends on nothing, it's generated at build time. Next.js adds the tags with the address, the dimensions and the alternative text to the page.

4.2. Each event's image

// app/(public)/events/[slug]/opengraph-image.tsx
import { ImageResponse } from 'next/og'
import { getEventDetails } from '@/lib/data/events'
import { CATEGORY_LABELS, formatDateTime } from '@/lib/format'
import { SITE_NAME } from '@/lib/site'

export const alt = 'Title, date and venue of the event'
export const size = { width: 1200, height: 630 }
export const contentType = 'image/png'

const MAX_LENGTH = 90

export default async function EventImage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const details = await getEventDetails(slug)
  if (!details) return new Response(null, { status: 404 })

  const { event, venue } = details
  const title =
    event.title.length > MAX_LENGTH
      ? `${event.title.slice(0, MAX_LENGTH - 1)}…`
      : event.title

  return new ImageResponse(
    (
      <div
        style={{
          width: '100%',
          height: '100%',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'space-between',
          padding: 80,
          background: '#f8fafc',
          color: '#0f172a',
        }}
      >
        <div style={{ fontSize: 36, color: '#115e59' }}>
          {`${SITE_NAME} · ${CATEGORY_LABELS[event.category]}`}
        </div>
        <div style={{ fontSize: title.length > 45 ? 64 : 88, fontWeight: 700 }}>{title}</div>
        <div style={{ display: 'flex', flexDirection: 'column', fontSize: 40 }}>
          <div>
            {event.status === 'canceled' ? 'Canceled' : formatDateTime(event.startsAt)}
          </div>
          <div>{`${venue.name} (${venue.district})`}</div>
        </div>
      </div>
    ),
    { ...size, headers: { 'Cache-Control': 'public, max-age=3600' } },
  )
}
  • It's a special Route Handler. It receives params as a promise and returns a response. It doesn't go through layouts or error boundaries.
  • The data comes from the cache, and with Cache Components Next.js also stores the result of the drawing. Cache-Control also stops a CDN from asking again for an hour. By default max-age=0, must-revalidate would be sent.
  • Template strings instead of loose text: {`${a} · ${b}`} is a single child. With {a} · {b} there would be three and the element would need display: 'flex'.
  • The title is truncated. The engine doesn't shrink the text to fit; long titles get a different size and a limit.
  • We don't include the poster. It's an arbitrary image, maybe vertical and in a format the engine doesn't support, and at thumbnail size it can't be read. Title, date and venue can.

The image of a dynamic segment depends on params, and Next.js treats that metadata like the rest: it needs generateStaticParams or the page to have declared holes. The event page meets both conditions.

Custom fonts: they're read once, in the module, and passed in fonts. They must be ttf, otf or woff; the woff2 the website uses won't do.

// Example only
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'

const bold = await readFile(join(process.cwd(), 'assets/vallenar-bold.ttf'))

// In the ImageResponse options
fonts: [{ name: 'Vallenar', data: bold, weight: 700, style: 'normal' }],

There's also generateImageMetadata, which produces several images from the same file, each with its own id (a promise since 16) and its own alternative text.

  1. Icons and manifest

They're files with reserved names in app/:

File Where it's seen
favicon.ico Tabs, and browsers that request it without looking at the HTML. Only at the root of app/
icon.svg Tabs in current browsers; it looks sharp at any size
apple-icon.png or .tsx Home screen on iOS, 180 × 180
manifest.ts Installing the site as an app
<!-- app/icon.svg -->
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
  <rect width="32" height="32" rx="7" fill="#115e59"/>
  <path d="M8 24 16 8l8 16M11 18h10" fill="none" stroke="#fff" stroke-width="3"/>
</svg>
// app/manifest.ts
import type { MetadataRoute } from 'next'
import { SITE_DESCRIPTION, SITE_NAME } from '@/lib/site'

export default function manifest(): MetadataRoute.Manifest {
  return {
    name: SITE_NAME,
    short_name: SITE_NAME,
    description: SITE_DESCRIPTION,
    lang: 'en',
    start_url: '/',
    display: 'browser',
    background_color: '#f8fafc',
    theme_color: '#115e59',
    icons: [{ src: '/icon.svg', sizes: 'any', type: 'image/svg+xml' }],
  }
}

display: 'browser' is deliberate: standalone would remove the browser bar, and with it the back button and the address. It only suits an app designed for it.

The Apple icon is generated like the previous images, in app/apple-icon.tsx, with a size of 180 by 180. Next.js links everything in the <head> and adds a fingerprint to the addresses. Replace the generator's favicon.ico with your own: it's the only one that can't be generated with code.

These routes don't need the proxy. Update its matcher (07-02):

// proxy.ts
source: '/((?!_next/|images/|favicon.ico|icon.svg|apple-icon|opengraph-image|manifest.webmanifest|robots.txt|sitemap.xml).*)',

5.1. viewport

The color of the browser's interface doesn't go in metadata, but in a separate export:

// app/layout.tsx
export const viewport: Viewport = {
  themeColor: [
    { media: '(prefers-color-scheme: light)', color: '#f8fafc' },
    { media: '(prefers-color-scheme: dark)', color: '#020617' },
  ],
}

It's approximate: it follows the system, and anyone who has manually chosen the other theme (03-04) will see the bar in the opposite color. The server doesn't know, and the viewport can't be sent later like metadata, because it affects the first paint: reading a cookie there would block the whole page.

Don't disable zoom with maximumScale or userScalable: false. It harms people who need it.

  1. What shouldn't be indexed

The dashboard, the admin area and the account pages have no business being in a search engine. It's declared in each layout, and their pages inherit it:

// app/(dashboard)/layout.tsx
export const metadata: Metadata = {
  title: { default: 'Management', template: `%s · ${SITE_NAME} Management` },
  robots: { index: false, follow: false },
}

// app/(account)/layout.tsx, and the my-bookings and account pages
export const metadata: Metadata = {
  robots: { index: false, follow: false },
}

Each page adds its own title: "My events", "New event", "Review", "Sign in"… Don't put data in private titles: they appear in the history, on a shared screen and in the tab list.

noindex isn't protection: it asks search engines not to show the page. What protects it is 08-04. Nor should it be combined with a block in robots.txt, as you'll see in 09-04: if a bot can't read the page, it can't read that it mustn't index it.

On /sign-up/confirm, the address carries a token. Its layout is already excluded from indexing and the Referrer-Policy header keeps it from leaking (08-05). Also check that this page has no canonical or og:url built from the parameters.

  1. Checking

npm run build && npm run start

# What a browser receives in the shell
curl -s localhost:3000/events/jazz-night |
  grep -oE '<title>[^<]*</title>|<link rel="canonical"[^>]*>|<meta property="og:[^>]*>'

# What a social network's bot receives
curl -s -A 'Twitterbot/1.0' localhost:3000/events/jazz-night | grep -oE 'og:[a-z:]+" content="[^"]*"'

# The image: the address comes from the tags
IMAGE=$(curl -s -A 'Twitterbot/1.0' localhost:3000/events/jazz-night | grep -oE 'og:image" content="[^"]*"' | head -1 | cut -d'"' -f3)
curl -sI "$IMAGE"

The image address has a suffix, because the folder is inside a route group and Next.js prevents two from clashing: don't write it by hand. It starts with SITE_URL, so if you built without NEXT_PUBLIC_SITE_URL it will point to localhost, and once published no app will be able to download it. It's the first place to look when "it works locally but not in production".

Also try an event page that isn't on the list from section 3: the browser receives the title through the stream and the bot receives it in the <head>. Platforms store what they saw the first time; almost all of them offer a tool to ask them to read it again. And since they read pages without a session, a draft can't have a preview.

Common Mistakes and Tips

  • canonical in the root layout.
  • Defining openGraph halfway in a page and losing what was inherited.
  • images: undefined in the belief that this makes it use the file. The property must be absent.
  • Forgetting metadataBase, or building without the public address.
  • Querying without a cache in generateMetadata and repeating the query in the page.
  • Reading cookies for the title of a static page.
  • The same title on every page, or the template applied twice.
  • 'use client' in the page: it can't export metadata. Move the interactive part down into a component.
  • Using grid or Tailwind in ImageResponse.
  • themeColor in metadata, which is deprecated: it goes in viewport.
  • Personal data in titles or images. Social images are public.
  • Assuming that whatever has noindex is protected.

Exercises

Exercise 1: working out the result

The root layout is the one from section 1. Say which <title>, canonical and og:image each page has: (a) it exports metadata = { title: 'Help' }; (b) it exports { title: 'Help', openGraph: { title: 'Help' } }; (c) it uses createMetadata with path: '/help'; (d) like (c), with an opengraph-image.png file in its folder.

Solution

  • (a) "Help · AgendaViva". No canonical. It inherits openGraph from the layout and the image from app/opengraph-image.tsx. Since nobody defines og:title, Next.js fills it in with the page title.
  • (b) The same title. The page's openGraph replaces the inherited one: siteName and locale disappear, and the image may be lost.
  • (c) The same title, canonical pointing to /help (absolute) and the shared image.
  • (d) Same as (c): images declared in the page beat the file. For the file to be used you have to pass hasOwnImage: true.

Someone suggests that /events?q=jazz should have the title "Results for jazz" and a social image with that text. Analyze the proposal: what it would cost, what risk it carries and what you'd do.

Solution

The title depends on searchParams: it arrives through the stream, and social bots wait. That's acceptable. You'll do it in 09-04.

The image, no. opengraph-image.tsx receives params, not searchParams, so you'd need a Route Handler of your own, /api/image?q=…. And therein lies the risk: anyone could generate an image with AgendaViva's branding and whatever text they wanted, and link to it as if we had published it. It's also on-demand CPU work, with infinite inputs. If free text must go in an image, the address is signed (07-03) so that only the ones we've created are valid.

Proposal: a title with the search, the shared image and noindex.

Exercise 3: no duplicate query

This page makes two queries, and the build warns about uncached data in generateMetadata(). Fix it in two ways and say when to use each one.

async function readVenue(slug: string) {
  const db = await getDb()
  const [venue] = await db.select().from(venues).where(eq(venues.slug, slug)).limit(1)
  return venue ?? null
}

export async function generateMetadata({ params }: Props) {
  const venue = await readVenue((await params).slug)
  return { title: venue?.name }
}

Solution

With 'use cache' in readVenue, cacheLife('days') and cacheTag(venueTag(slug)): page and metadata share the entry, and with generateStaticParams the title stays in the shell. It's the right choice for shared data, and it's what getVenueBySlug already does: the best option is to use that one.

With React.cache: it avoids the second query in the same request, but the data is still uncached. The warning persists if everything else is prerenderable, and it has to be declared with a hole. It's the right choice when the data is per person or can't be stale.

The null case was also missing: title: undefined inherits the general title; better to give it one of its own.

Conclusion

Metadata is data returned by layouts and pages. It's merged from the root to the leaf, shallowly, so a function that builds the complete object prevents most failures. If it depends on cached data, it goes in the shell; if it depends on the request, it arrives later, except for bots that wouldn't know how to read it. Social images are drawn with JSX and the same data, icons and the manifest are named files, and private content carries noindex.

With this, each page says what it should about itself. What's left is helping whoever goes through all of them: which addresses exist, which ones aren't worth a visit, what to do with a thousand filter combinations and with a concert that took place last year. That's the content of Sitemap, Robots and Structured Data.

© Copyright 2026. All rights reserved