Skip to content
Radical Labs

Using generateMetadata for SEO in Next.js 13+

Filed
2025-06-15
Updated
2026-10-07
Topic
Web
Length
12 min read
By
Radical Labs

generateMetadata is how a page in the Next.js App Router tells search engines and social apps what it is: its title, its description, its canonical address, its share image. It runs on the server, so the tags are in the HTML a crawler reads, with no client-side SEO library.

This guide covers what to return from it for SEO, the files that sit beside it (share images, sitemaps, robots.txt), and the mistakes we see most often in real projects. The code is written for Next.js 15 and 16, where params is a Promise. On Next.js 13 or 14, params is a plain object: drop the await and read it directly.

The metadata object vs generateMetadata

The App Router gives you two ways to set metadata. Both work only in Server Components, in a layout or page file:

ExportUse it whenFor example
export const metadataThe values are known when you write the fileAn About page, or the site’s defaults
export async function generateMetadataThe values depend on the URL or on dataA blog post, a product, a city page

A file exports one or the other, never both. Next.js turns what they return into tags in the page’s <head>, so there’s no next/head and no next-seo package to add.

When a page can be prerendered, its metadata is written into the HTML at build time. When it’s rendered on request, the metadata is resolved on the server for each request (and can stream, which we cover below).

A generateMetadata example for a blog post

Here’s a typical dynamic route. It reads the slug, loads the post, and returns the three tags that matter most for search: the title, the description and the canonical address.

TSX

// app/blog/[slug]/page.tsx
import type { Metadata } from 'next'
import { notFound } from 'next/navigation'
import { cache } from 'react'
import { getPostBySlug } from '@/lib/posts' // your CMS or database call

// One lookup per request, shared by the metadata and the page.
const getPost = cache(getPostBySlug)

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

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params
  const post = await getPost(slug)
  if (!post) notFound()

  return {
    title: post.title,
    description: post.excerpt,
    alternates: { canonical: `/blog/${slug}` },
  }
}

export default async function Page({ params }: Props) {
  const { slug } = await params
  const post = await getPost(slug)
  if (!post) notFound()

  return <article>{/* the post */}</article>
}

Four details in there are worth knowing:

  • await params. Since Next.js 15, params is a Promise, and Next.js 16 removed the old synchronous fallback. Reading params.slug without awaiting gives you nothing.
  • cache(). Next.js already deduplicates fetch calls between the metadata and the page. A database or SDK call isn’t deduplicated, so wrap it in React’s cache or you’ll query twice per request.
  • notFound(). It works inside generateMetadata and sends a real 404. Returning a “Post not found” title instead serves the error with a 200 status, which Google reports as a soft 404.
  • Typing. In Next.js 15.5 and later, next typegen gives you a global PageProps<'/blog/[slug]'> type, so you don’t have to write Props by hand.

Site-wide defaults and title templates

Set the defaults once, in the root layout. Every page inherits them and overrides only what it needs.

TSX

// app/layout.tsx
import type { Metadata } from 'next'

export const metadata: Metadata = {
  metadataBase: new URL('https://example.com'),
  title: {
    default: 'Example Studio',
    template: '%s | Example Studio',
  },
  description: 'One sentence on what the whole site offers.',
  openGraph: {
    siteName: 'Example Studio',
    locale: 'en_US',
    type: 'website',
  },
}

metadataBase lets every other URL in your metadata be a short path like /blog/my-post; Next.js joins it to the base to make the full address. Without it, a relative URL in metadata fails the build.

The template puts each page’s own title where the %s is. Three rules catch people out:

  • A template applies to the routes below the file that sets it, not beside it. The template in app/layout.tsx doesn’t touch the title set in app/page.tsx, so your home page needs its full title written out.
  • A template needs a default, which any page without a title of its own will use.
  • title: { absolute: '…' } skips the template, for a page that should carry exactly the title you give it.

With the layout above, titles come out like this:

The page setsThe title tag reads
title: 'Pricing'Pricing | Example Studio
No titleExample Studio
title: { absolute: 'Pricing for agencies' }Pricing for agencies

Canonical URLs and robots, page by page

A canonical tag tells Google which address is the real one when the same page can be reached several ways: with tracking parameters, with filters, with and without www. Set it per page with alternates.canonical, built from the route’s own params as in the example above.

Don’t put a canonical in a layout

Metadata is inherited. A canonical of / in the root layout tells Google that every page which doesn’t set its own is a copy of the home page, and Google may drop them from results. Set the canonical in each page instead.

Build it from params, not from the request. generateMetadata runs on the server, so client hooks like usePathname aren’t available there, and the canonical should be the clean address anyway, without query strings.

Back the tag with a redirect for the duplicate host, so www and the bare domain don’t both serve the site. It’s what we do on this site:

TS

// next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  async redirects() {
    return [
      {
        source: '/:path*',
        has: [{ type: 'host', value: 'www.example.com' }],
        destination: 'https://example.com/:path*',
        permanent: true,
      },
    ]
  },
}

export default nextConfig

Keeping a page out of search

Internal search results, thank-you pages, drafts and filtered views usually shouldn’t be in Google. Mark them with robots:

TSX

// app/search/page.tsx
import type { Metadata } from 'next'

export const metadata: Metadata = {
  robots: { index: false, follow: true },
}

The inheritance rule applies here too: a noindex in a layout removes every page below it. And noindex isn’t the same as a block in robots.txt. If robots.txt stops Google crawling a page, Google never sees its noindex, and the address can still appear in results.

Open Graph, X cards and share images

Open Graph tags set the title, description and image people see when your link is shared on LinkedIn, Slack, WhatsApp or Facebook. X reads them too, and needs one tag of its own to show a large image.

Why your share image disappears

Next.js merges metadata from the layout down to the page, but only one level deep. If a page returns an openGraph object, it replaces the layout’s whole openGraph, site name and default image included. Keep the shared fields in one place and spread them in:

TS

// app/shared-metadata.ts
export const sharedOpenGraph = {
  siteName: 'Example Studio',
  locale: 'en_US',
}

TSX

// app/blog/[slug]/page.tsx
import { sharedOpenGraph } from '../../shared-metadata'

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params
  const post = await getPost(slug)
  if (!post) notFound()

  return {
    title: post.title,
    description: post.excerpt,
    alternates: { canonical: `/blog/${slug}` },
    openGraph: {
      ...sharedOpenGraph,
      type: 'article',
      url: `/blog/${slug}`,
      title: post.title,
      description: post.excerpt,
      publishedTime: post.publishedAt,
      modifiedTime: post.updatedAt,
      authors: [post.author.name],
    },
    twitter: { card: 'summary_large_image' },
  }
}

When you only want to add to what a parent set, generateMetadata takes a second argument, parent, with the metadata resolved so far: for example (await parent).openGraph?.images.

Generate the image with opengraph-image.tsx

Rather than design a share image for every post, generate one. A file named opengraph-image.tsx in a route’s folder becomes that route’s share image, and Next.js writes the og:image tags, with size and type, for you.

TSX

// app/blog/[slug]/opengraph-image.tsx
import { ImageResponse } from 'next/og'
import { getPostBySlug } from '@/lib/posts'

export const alt = 'Example Studio blog'
export const size = { width: 1200, height: 630 }
export const contentType = 'image/png'

export default async function Image({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const post = await getPostBySlug(slug)

  return new ImageResponse(
    (
      <div
        style={{
          width: '100%',
          height: '100%',
          display: 'flex',
          alignItems: 'flex-end',
          padding: 80,
          background: '#f5f5f5',
          color: '#111111',
          fontSize: 72,
        }}
      >
        {post?.title ?? 'Example Studio blog'}
      </div>
    ),
    size,
  )
}

  • By default it’s generated at build time and cached, so it costs nothing per visit, unless it reads request data such as cookies, or data you haven’t cached.
  • An image file like this takes priority over image fields in metadata or generateMetadata, so don’t set openGraph.images for the same route too.
  • ImageResponse comes from next/og. The separate @vercel/og package and an API route aren’t needed in the App Router.
  • 1200 × 630 pixels is the size LinkedIn, Facebook and X all crop well. Add a twitter-image.tsx the same way only if X should get a different image.

Structured data with JSON-LD

Structured data describes the page in a form search engines read directly: an article with its author and dates, a product with its price. It isn’t part of the Metadata API. The Next.js docs recommend rendering it as a script tag in the page itself:

TSX

export default async function Page({ params }: Props) {
  const { slug } = await params
  const post = await getPost(slug)
  if (!post) notFound()

  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': 'BlogPosting',
    headline: post.title,
    description: post.excerpt,
    datePublished: post.publishedAt,
    dateModified: post.updatedAt,
    author: { '@type': 'Person', name: post.author.name },
    mainEntityOfPage: `https://example.com/blog/${slug}`,
  }

  return (
    <article>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: JSON.stringify(jsonLd).replace(/</g, '\\u003c'),
        }}
      />
      {/* the post */}
    </article>
  )
}

Replacing < with its escaped form stops a stray </script> in your data from breaking out of the tag. Don’t put JSON-LD in metadata’s other field: that renders <meta> tags, not a script, so search engines won’t read it as structured data.

Check the result with Google’s Rich Results Test, or the Schema Markup Validator for types Google doesn’t show as rich results.

Sitemaps, robots.txt and hreflang

Two more files finish the job. app/sitemap.ts lists the pages you want indexed, and app/robots.ts points crawlers to it:

TS

// app/sitemap.ts
import type { MetadataRoute } from 'next'
import { getAllPosts } from '@/lib/posts'

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const posts = await getAllPosts()

  return [
    { url: 'https://example.com' },
    ...posts.map((post) => ({
      url: `https://example.com/blog/${post.slug}`,
      lastModified: post.updatedAt,
    })),
  ]
}

TS

// app/robots.ts
import type { MetadataRoute } from 'next'

export default function robots(): MetadataRoute.Robots {
  return {
    rules: { userAgent: '*', allow: '/' },
    sitemap: 'https://example.com/sitemap.xml',
  }
}

Sitemap entries need full addresses, with https and the domain, and should match each page’s canonical. Leave out pages marked noindex.

Language versions

If a page exists in several languages, tell Google about each version with alternates.languages, which Next.js renders as hreflang links:

TSX

// app/[lang]/pricing/page.tsx
type Props = { params: Promise<{ lang: string }> }

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { lang } = await params

  return {
    alternates: {
      canonical: `/${lang}/pricing`,
      languages: {
        en: '/en/pricing',
        de: '/de/pricing',
        'x-default': '/en/pricing',
      },
    },
  }
}

Each version should be its own canonical and list every version, itself included, so the links confirm each other. x-default names the page for visitors whose language you don’t offer.

Streaming metadata: does it hurt SEO?

Since Next.js 15.2, generateMetadata can stream. If it’s slow, Next.js sends the page first and adds the tags when they’re ready, in the body rather than the head.

The Next.js team has verified that crawlers which run JavaScript and read the whole page, like Googlebot, pick those tags up. Crawlers that only read the HTML, like Facebook’s link preview, are recognised by their user agent, and for them Next.js waits for the metadata and puts it in the head as before. The htmlLimitedBots option in next.config changes that list; matching every user agent turns streaming off.

For a prerendered page none of this comes up: the tags are already in the HTML.

With Cache Components in Next.js 16

If you’ve turned on Cache Components, metadata that reads request data or uncached data waits for the request. When the rest of the page could be prerendered, Next.js raises an error naming the page, so the choice is explicit. When the metadata reads only external data, add 'use cache' at the top of generateMetadata and it’s prerendered with the page. When it truly needs request data, like cookies, the Next.js docs show how to mark the page as dynamic on purpose.

Checking what crawlers see

Read the server’s HTML, not the browser’s Elements panel, which shows the page after JavaScript has changed it. View Source, or a quick curl, shows what a crawler gets:

Shell

curl -s https://example.com/blog/my-post | grep -iE '<title|<meta|canonical'

Then check how Google and the share previews read it:

  • URL Inspection in Google Search Console shows whether a page is indexed and which canonical Google chose. If Google’s choice differs from yours, it thinks another page is the original.
  • The Rich Results Test shows whether your structured data is valid and what it qualifies for.
  • Share previews: LinkedIn’s Post Inspector and Facebook’s Sharing Debugger show the card people will see, and refresh their cached copy after you change the tags.

Common generateMetadata mistakes

MistakeWhat happensFix
Reading params without awaitOn Next.js 16 the values come back emptyconst { slug } = await params
A canonical or noindex in a layoutEvery page below inherits itSet them in each page
openGraph set in a pageIt replaces the layout’s, site name and image includedSpread shared fields, or read parent
A “not found” title for missing dataGoogle sees a soft 404 on a 200 pageCall notFound()
Relative URLs without metadataBaseThe build failsSet metadataBase in the root layout
themeColor or viewport in metadataDeprecated since Next.js 14Export viewport or generateViewport
Filling in keywordsGoogle ignores the keywords meta tagSpend the time on titles and descriptions
The same title on many pagesResults can’t tell them apart, and Google may rewrite themWrite a distinct title for each page

Most of the SEO work in the App Router comes down to a few exports: defaults in the root layout, generateMetadata in each dynamic page, a share image file, a JSON-LD script, and sitemap.ts with robots.ts. Set them up once and every new page starts with the right tags.

If your content lives in a headless CMS, our Strapi 5 guide covers connecting one to Next.js.

Have something to build?

Tell us what you’re making.

Start a Project

What we build

Built fora brighter tomorrow