Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Next.js Metadata API: generateMetadata, Open Graph, sitemap.ts, and robots.ts

metadataBase decides whether share previews work at all. Title templates, dynamic metadata with cached loaders, and sitemap generation that stays fresh.

~4 min readNext.js
#Next.js#SEO#Metadata#Sitemap
3D illustration of a page card emitting a social preview image and a structured sitemap tree

Quick Summary

Metadata in the App Router is a static export or an async function: export const metadata: Metadata = {...} for values known at build time, export async function generateMetadata(props) when they depend on params, a fetch, or a database read. Both are typed by Next.js's Metadata type, and both can only exist once per segment.

title has two forms that behave differently: a string sets the tab title verbatim, while an object with default and template lets child segments inherit a pattern ("%s | RYUSLOG"). metadataBase resolves every relative URL in openGraph.images, alternates.canonical, and Twitter cards — without it, relative OG image paths resolve against localhost in development and produce absolute garbage in production metadata.

app/sitemap.ts and app/robots.ts are route conventions that generate /sitemap.xml and /robots.txt from functions returning typed arrays. For per-route social images, opengraph-image.tsx runs ImageResponse to render a PNG at request time (or build time), which removes the need for a separate design pipeline.

Basic Syntax & Core Signatures

tsx
// app/layout.tsx — static metadata for the whole app import type { Metadata } from "next"; export const metadata: Metadata = { metadataBase: new URL("https://www.ryuslog.com"), title: { default: "RYUSLOG DEV", template: "%s | RYUSLOG DEV" }, description: "Reference guides for developers who need the exact semantics.", alternates: { canonical: "/" }, openGraph: { type: "website", siteName: "RYUSLOG DEV", images: [{ url: "/og-default.png", width: 1200, height: 630, alt: "RYUSLOG DEV" }], }, twitter: { card: "summary_large_image", creator: "@rshday" }, robots: { index: true, follow: true }, };
tsx
// app/blog/[slug]/page.tsx — dynamic metadata, params is a Promise import type { Metadata } from "next"; 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) return { title: "Post not found", robots: { index: false } }; return { title: post.title, // -> "Title | RYUSLOG DEV" description: post.excerpt, alternates: { canonical: `/blog/${slug}` }, openGraph: { type: "article", publishedTime: post.publishedAt, images: [`/og/${slug}.png`] }, }; }
ts
// app/sitemap.ts import type { MetadataRoute } from "next"; export default async function sitemap(): Promise<MetadataRoute.Sitemap> { const posts = await db.post.findMany({ select: { slug: true, updatedAt: true } }); return [ { url: "https://www.ryuslog.com", lastModified: new Date(), changeFrequency: "daily", priority: 1 }, ...posts.map((p) => ({ url: `https://www.ryuslog.com/blog/${p.slug}`, lastModified: p.updatedAt, changeFrequency: "weekly" as const, priority: 0.7, })), ]; }
ts
// app/robots.ts import type { MetadataRoute } from "next"; export default function robots(): MetadataRoute.Robots { return { rules: [{ userAgent: "*", allow: "/", disallow: ["/api/", "/admin/"] }], sitemap: "https://www.ryuslog.com/sitemap.xml", }; }
tsx
// app/og/[slug]/opengraph-image.tsx — image generated from code import { ImageResponse } from "next/og"; 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; return new ImageResponse( <div style={{ display: "flex", fontSize: 64, background: "#0b1120", color: "#fff", width: "100%", height: "100%" }}> {slug} </div>, size ); }

Key Comparison Table

NeedExportWhere
Static title and OG tagsexport const metadataAny layout.tsx or page.tsx
Values from params or dataexport async function generateMetadataSame
/sitemap.xmlexport default function sitemap()app/sitemap.ts
/robots.txtexport default function robots()app/robots.ts
PWA manifestexport default function manifest()app/manifest.ts
One image per routeopengraph-image.tsxNext to page.tsx
Viewport, theme colourexport const viewportRoot layout
FieldMerges with parentNotes
title.template / defaultChildren inherit the templateA child title string is wrapped
openGraphShallow-merged per keySet openGraph in a child and you replace the object's keys
alternatesNot inherited automaticallySet canonical per page
robotsInheritedOverride to noindex on one page
metadataBaseInherited from the rootRequired for relative URLs

Practical Edge Cases & Deep Dives

1. metadataBase and relative image URLs

tsx
export const metadata: Metadata = { metadataBase: new URL(process.env.SITE_URL ?? "http://localhost:3000"), openGraph: { images: ["/og.png"] }, // resolved to an absolute URL };

Without metadataBase, Next.js logs a warning and resolves relative OG image paths against localhost, so a shared link previews a broken image. In production the value must be the canonical origin (with www, if that is canonical) — a mismatch between metadataBase and the site's canonical host produces two different image URLs for the same page and dilutes the cache.

2. Title templates and the page that should not inherit one

tsx
// root layout export const metadata = { title: { default: "RYUSLOG DEV", template: "%s | RYUSLOG DEV" } }; // a page export const metadata = { title: "TypeScript Generics" }; // "TypeScript Generics | RYUSLOG DEV" // absolute, skipping the template export const metadata = { title: { absolute: "RYUSLOG DEV — Reference Guides" } };

A child that sets title: "RYUSLOG DEV" gets the template applied and ends up with a doubled brand. absolute is the escape hatch, and it is also what a landing page usually wants.

3. generateMetadata and duplicate fetching

tsx
// Both of these hit the database for the same post export async function generateMetadata({ params }) { const post = await getPost((await params).slug); ... } export default async function Page({ params }) { const post = await getPost((await params).slug); ... }

Two calls, one render. The request is deduplicated only when it is a fetch with the same URL inside the same render pass; a database call through an ORM is not memoized. Wrap the loader in React's cache() so both functions share one call:

ts
import { cache } from "react"; export const getPost = cache(async (slug: string) => db.post.findUnique({ where: { slug } }));

In Next.js 15 metadata streams to the browser for users while blocking bots — so a slow generateMetadata delays what a crawler sees but not the first paint.

4. sitemap.ts at scale: sizes, freshness, and caching

ts
export const revalidate = 3600; // regenerate hourly export const dynamic = "force-dynamic"; // or regenerate on every request

A single sitemap is limited to 50,000 URLs and 50 MB uncompressed by the protocol. Past that, split with generateSitemaps() and a sitemap index. Static output is produced at build time, so a site that publishes constantly needs revalidate or a dynamic route, and a deploy is what makes new URLs appear immediately. Changing lastModified on every request is a good way to have crawlers ignore the field — set it from the record, not from new Date().

5. What belongs in robots and what does not

ts
robots: { index: false, follow: true } // a page: noindex, links still followed

metadata.robots writes a <meta name="robots"> tag, which is per page. app/robots.ts writes the site-wide /robots.txt, which is a crawl hint. They do different jobs: noindex keeps a page out of the index and is the reliable way to de-list content; disallow stops crawling and, notably, prevents a crawler from ever seeing the noindex tag on that URL. Blocking in robots.txt and also expecting noindex to work is the classic contradiction.

Common Runtime & Configuration Mistakes

SymptomCauseFix
OG image URL is localhostmetadataBase missingSet it on the root layout
Title shows the brand twiceChild set a string title under a templatetitle: { absolute: ... }
Metadata not updatingCached route, or static export at buildrevalidate, or dynamic rendering
generateMetadata and page fetch twiceNo memoizationWrap the loader in cache()
Sitemap missing new URLsGenerated at build onlyrevalidate or force-dynamic
noindex ignoredrobots.txt blocks the crawlRemove the disallow, keep noindex
Sitemap over 50,000 URLsProtocol limitgenerateSitemaps() plus an index
Two metadata exports in one fileStatic and dynamic both declaredKeep one, per segment
themeColor in metadata ignoredMoved to viewportexport const viewport
Canonical points at the wrong hostalternates.canonical relative + wrong metadataBaseOne canonical origin

Metadata is a build-time contract with the rest of the web: an absolute base, one canonical URL per page, and titles and descriptions that describe the actual content. Generate it from the same data the page renders, and the crawler sees what the user sees.

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.