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.

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
// 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 },
};// 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`] },
};
}// 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,
})),
];
}// 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",
};
}// 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
| Need | Export | Where |
|---|---|---|
| Static title and OG tags | export const metadata | Any layout.tsx or page.tsx |
| Values from params or data | export async function generateMetadata | Same |
/sitemap.xml | export default function sitemap() | app/sitemap.ts |
/robots.txt | export default function robots() | app/robots.ts |
| PWA manifest | export default function manifest() | app/manifest.ts |
| One image per route | opengraph-image.tsx | Next to page.tsx |
| Viewport, theme colour | export const viewport | Root layout |
| Field | Merges with parent | Notes |
|---|---|---|
title.template / default | Children inherit the template | A child title string is wrapped |
openGraph | Shallow-merged per key | Set openGraph in a child and you replace the object's keys |
alternates | Not inherited automatically | Set canonical per page |
robots | Inherited | Override to noindex on one page |
metadataBase | Inherited from the root | Required for relative URLs |
Practical Edge Cases & Deep Dives
1. metadataBase and relative image URLs
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
// 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
// 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:
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
export const revalidate = 3600; // regenerate hourly
export const dynamic = "force-dynamic"; // or regenerate on every requestA 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
robots: { index: false, follow: true } // a page: noindex, links still followedmetadata.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
| Symptom | Cause | Fix |
|---|---|---|
OG image URL is localhost | metadataBase missing | Set it on the root layout |
| Title shows the brand twice | Child set a string title under a template | title: { absolute: ... } |
| Metadata not updating | Cached route, or static export at build | revalidate, or dynamic rendering |
generateMetadata and page fetch twice | No memoization | Wrap the loader in cache() |
| Sitemap missing new URLs | Generated at build only | revalidate or force-dynamic |
noindex ignored | robots.txt blocks the crawl | Remove the disallow, keep noindex |
| Sitemap over 50,000 URLs | Protocol limit | generateSitemaps() plus an index |
| Two metadata exports in one file | Static and dynamic both declared | Keep one, per segment |
themeColor in metadata ignored | Moved to viewport | export const viewport |
| Canonical points at the wrong host | alternates.canonical relative + wrong metadataBase | One 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 toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesNext.js Static Export, Standalone Output, and Docker Deployment
Export has no server, standalone has a pruned one, and the default expects a full install. The three COPY lines that decide whether a container renders CSS.
Next.js Parallel Routes and Intercepting Routes: Slot Layouts and Modals
Named slots render several pages in one layout, and (.) interception makes a click open over the page while a direct link renders the full route. Why every slot needs default.tsx.
Next.js ISR: Route Revalidate, revalidateTag, and On-Demand Invalidation
Two clocks and one trigger: route revalidate seconds, fetch-level tags, and a webhook that calls revalidateTag. A timer is a ceiling on freshness, never a guarantee.
Next.js Environment Variables: NEXT_PUBLIC_, Build-Time Inlining, and Runtime Config
The prefix decides whether a value is compiled into the browser bundle or stays on the server. One image, two environments, and the choice that follows from it.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.