All articles
November 12, 2026

Next.js generateMetadata: titles, canonicals and Open Graph, 2026

Use a static metadata object when nothing depends on the request, and generateMetadata when it does. Set metadataBase once, mind the shallow merge, and let file-based OG images win.

Team of four gathers around a monitor in a dark brick office, pointing at the screen as they review a page

Static metadata or generateMetadata

Export a static metadata object when the tags do not depend on the request or on fetched data. Export generateMetadata when they do, for example a blog post title that comes from a database. A route segment can export one or the other, never both, and both work only in Server Components, according to the Next.js generateMetadata reference.

The static version is the right default for pages like /about or /pricing:

import type { Metadata } from 'next'

export const metadata: Metadata = {
  title: 'About',
  description: 'Who we are and how we work.',
}

Dynamic routes need the function. In the documented examples, params and searchParams are Promises, so you await them. The second argument, parent, is a promise of the metadata already resolved from parent segments:

import type { Metadata, ResolvingMetadata } from 'next'

type Props = {
  params: Promise<{ slug: string }>
}

export async function generateMetadata(
  { params }: Props,
  parent: ResolvingMetadata
): Promise<Metadata> {
  const { slug } = await params
  const post = await getPost(slug)
  const previousImages = (await parent).openGraph?.images || []

  return {
    title: post.title,
    description: post.description,
    openGraph: { images: [post.ogImage, ...previousImages] },
  }
}

A few details save debugging time. searchParams exists only in page.js, not in layouts. You can call notFound() and redirect() inside the function. If a page is a mix of server data and client interactivity, keep page.tsx as the Server Component that exports the metadata and move the interactive part into a separate 'use client' file. That split is also how teams usually structure a marketing site versus a dashboard: the public, indexable routes stay on the server.

One fetch for metadata and page

The page usually needs the same record that the metadata needs. Requests made with fetch inside generateMetadata are memoized across generateMetadata, generateStaticParams, layouts, pages and Server Components, so the same URL is fetched once per render.

When you query a database or an SDK instead of fetch, wrap the loader in React's cache. The Next.js metadata guide shows the pattern:

import { cache } from 'react'

export const getPost = cache(async (slug: string) => {
  return db.query.posts.findFirst({ where: eq(posts.slug, slug) })
})

Call getPost(slug) in both generateMetadata and the page component. The function body runs once, and the two call sites share the result.

Title templates: default, template and absolute

Set the site-wide pattern once in the root layout:

export const metadata: Metadata = {
  title: {
    template: '%s | Acme',
    default: 'Acme',
  },
}

A page that exports title: 'About' now renders <title>About | Acme</title>. Three rules trip people up:

  • title.template applies to child segments, not to the segment where you define it. A template in app/layout.tsx does not touch a title in app/page.tsx of the same segment.
  • title.default is required whenever you set a template. It is the fallback for children that define no title.
  • title.absolute skips the parent template. Use it for a page whose title must stand alone, such as the home page.

A template defined in a page.js has no effect, because a page is always the last segment of a route.

Keep titles short. The template adds characters, so write each page title knowing the suffix follows.

Canonical URLs with metadataBase and alternates

Set metadataBase once in the root layout. After that, every URL-based field in that segment and below can use a relative path:

export const metadata: Metadata = {
  metadataBase: new URL('https://acme.com'),
  alternates: {
    canonical: '/',
    languages: {
      'en-US': '/en-US',
      'de-DE': '/de-DE',
    },
  },
}

Next.js resolves these to <link rel="canonical" href="https://acme.com" /> and hreflang alternate links with full URLs. Three behaviors are worth knowing:

  • A relative path without a configured metadataBase causes a build error, so you find out early.
  • A field that already contains an absolute URL ignores metadataBase.
  • Duplicate slashes between the base and the path are normalized to one.

On a dynamic route, build the canonical from the same slug you used to load the record: alternates: { canonical: `/blog/${slug}` }. Do not derive it from the incoming request URL, or tracking parameters and trailing variants leak into the canonical.

Google's guidance on specifying a canonical URL says to use absolute paths rather than relative paths in the rel="canonical" link element. Because Next.js composes the final URL from metadataBase, the rendered tag is absolute even though your source is relative. Check the page source once to confirm. The same page also recommends a self-referential canonical on the canonical page itself, and treats the annotation as a strong hint, not a directive. Google may still pick another URL, so keep your sitemap, redirects and canonical tags pointing at the same address. The same consistency applies to canonicals during a site migration.

Open Graph and Twitter fields

The openGraph object maps to og: tags. For an article page, set type: 'article' and add the article fields:

openGraph: {
  title: post.title,
  description: post.description,
  url: `/blog/${slug}`,
  siteName: 'Acme',
  type: 'article',
  publishedTime: post.publishedAt,
  images: [{ url: post.ogImage, width: 1200, height: 630, alt: post.title }],
},
twitter: {
  card: 'summary_large_image',
  images: [post.ogImage],
},

The reference examples mark image URLs as needing to be absolute, and the metadataBase rule above lets you pass relative paths that resolve to absolute ones. Either way, the tag that crawlers read must be a full URL. Give every image an alt and explicit dimensions. For the pixel-level choices, see image formats and alt text.

You often do not need to write the image fields at all. File-based metadata has higher priority than the metadata object and generateMetadata. Drop an opengraph-image.jpg into app/ for a site-wide default, or into a deeper folder such as app/blog/ to override it for that route. The more specific file wins.

For a unique image per post, add opengraph-image.tsx in app/blog/[slug]/. It exports size (1200 by 630 is the common choice) and contentType, and returns an ImageResponse from next/og. ImageResponse supports flexbox and a subset of CSS; display: grid does not work. Next.js writes the matching og:image tags for you, including the type and size.

The shallow-merge trap

Metadata is evaluated from the root layout down to the page, and the objects are merged shallowly. A key defined later replaces the same key from an earlier segment, and that includes nested objects.

Say app/layout.tsx sets openGraph with a title and a description, and app/blog/page.tsx sets openGraph: { title: 'Blog' }. The page output has the title Blog and no og:description at all, because the page's openGraph replaced the layout's whole object. If a page sets no openGraph, it inherits the layout's.

The fix is to share the fields you want to keep:

// app/shared-metadata.ts
export const openGraphImage = { images: ['https://acme.com/og.png'] }

// app/about/page.tsx
export const metadata = {
  openGraph: { ...openGraphImage, title: 'About' },
}

The same shallow replacement applies to robots. If you set robots.googleBot on one page, restate everything you need there.

Metadata for crawlers: streaming and bots

Since Next.js 15.2.0, generateMetadata supports streaming. On dynamic pages, Next.js can send the initial UI first and append the metadata once the function resolves. Prerendered pages are unaffected, because their metadata is resolved at build time and sits in the initial HTML.

Social scrapers are the concern. Per the docs, Next.js detects HTML-limited bots such as facebookexternalhit from the User-Agent header and waits for generateMetadata to finish, so their tags land in the <head>. The docs say metadata was verified with bots that execute JavaScript, such as Googlebot. If you need every client to get blocking metadata, set htmlLimitedBots: /.*/ in next.config. The docs warn this can lengthen response times, so the default is the better choice unless you have a specific bot that misbehaves.

With Cache Components enabled, metadata that reads cookies(), headers(), params or uncached data defers to request time. For metadata that depends only on external data, put 'use cache' at the top of generateMetadata. Return values must be serializable, so pass metadataBase as a string there.

What to ship

Four decisions cover most sites: a static metadata in the root layout with metadataBase and a title template, generateMetadata on dynamic routes with a shared cached loader, a canonical built from the slug, and a file-based OG image that you override only where a page needs its own. Then test in the page source, not the browser tab, and run a sample URL through the social debuggers you rely on.

If you want a second pair of eyes on the technical SEO of a Next.js build, talk to Kallos Labs.

Frequently asked questions

Can I export both metadata and generateMetadata from the same page?

No. A route segment can export one or the other, not both, and both work only in Server Components. Use the static object when nothing depends on the request or on fetched data.

Do I need metadataBase?

If any URL field such as a canonical or an Open Graph image uses a relative path, yes: without metadataBase that causes a build error. Set it once in the root layout. Absolute URLs ignore it.

Why did my layout's Open Graph description disappear on a page?

Metadata merges shallowly. If a page defines openGraph, it replaces the layout's whole openGraph object. Spread shared fields from a common variable, or leave openGraph out of the page to inherit it.

Will social crawlers see metadata that streams in?

For dynamic pages Next.js streams metadata, but it detects HTML-limited bots such as facebookexternalhit by user agent and waits so the tags land in the head. Prerendered pages resolve metadata at build time.