Metadata API, Sitemaps, and Structured Data
Search engines and social platforms judge your pages by signals you either control or leave to chance. The App Router's Metadata API is how you control them: static metadata exports for fixed pages, generateMetadata for dynamic ones, file-convention sitemaps and robots rules, and JSON-LD for the structured data that earns rich results. Done well, the same page that renders your product also declares its title, description, social card, canonical URL, and schema type without a single third-party script.
This lesson treats metadata as an engineering surface rather than a marketing afterthought. You will learn how static and dynamic metadata merge with layout defaults, how to build sitemaps that reflect real content, how robots rules interact with them, and how JSON-LD plugs into the same data your page already fetched.
Prerequisites
- !App Router pages, layouts, and dynamic params
- !Understanding of HTTP status codes and canonical URLs
- !Familiarity with the schema.org vocabulary at a basic level
What You'll Learn
- 1Compose static and generateMetadata exports that inherit sensibly
- 2Emit Open Graph and Twitter card data that renders correct previews
- 3Generate sitemaps and robots.txt from live data
- 4Attach valid JSON-LD for common page types
Static metadata and inheritance
A page or layout exports a metadata object, and child segments inherit fields they do not define. A layout can set the site name and default title template; each page overrides just its own title and description.
// app/layout.js
export const metadata = {
metadataBase: new URL('https://www.example.com'),
title: {
default: 'Example â Products and Guides',
template: '%s | Example',
},
description: 'Practical guides and well-made products for developers.',
openGraph: {
siteName: 'Example',
type: 'website',
},
robots: { index: true, follow: true },
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
// app/pricing/page.js
export const metadata = {
title: 'Pricing', // becomes "Pricing | Example"
description: 'Simple per-seat pricing with a free tier for open source.',
alternates: { canonical: '/pricing' },
};
metadataBase resolves relative Open Graph image paths into absolute URLs â without it, social scrapers receive unusable relative links, which is the most common cause of missing preview images. The title template keeps branding consistent while letting each page speak its specific topic. Layout metadata also composes with segment metadata upward: a nested layout can add its own defaults without restating the site name.
Dynamic metadata per route
For content routes, generateMetadata receives the same params and searchParams as the page and returns a metadata object. Next.js awaits both, and any fetch issued inside generateMetadata is memoized against the page's own fetch of the same URL within the request â so fetching the post once for the title and once for the body does not double the network cost.
// app/blog/[slug]/page.js
export async function generateMetadata({ params }) {
const { slug } = await params;
const post = await getPost(slug);
if (!post) return { title: 'Post not found' };
return {
title: post.title,
description: post.excerpt,
alternates: { canonical: `/blog/${slug}` },
openGraph: {
type: 'article',
title: post.title,
description: post.excerpt,
publishedTime: post.publishedAt,
authors: [post.author.name],
images: [{ url: post.coverImage, width: 1200, height: 630 }],
},
twitter: {
card: 'summary_large_image',
images: [post.coverImage],
},
};
}
export default async function BlogPost({ params }) {
const { slug } = await params;
const post = await getPost(slug);
return <article><h1>{post.title}</h1>{post.content}</article>;
}
One rule keeps this cheap: share the data-access function between generateMetadata and the page. Two independent queries with different filter shapes defeat memoization and double latency on the critical path.
Open Graph, Twitter, and canonical URLs
The fields that determine how a link renders when shared are worth being precise about. Open Graph needs an absolute image URL, ideally 1200 by 630 pixels. The Twitter card type decides between a large image, a compact summary, and a plain title. The canonical URL tells search engines which of several near-identical addresses is the one to index â pagination parameters, filtered sorts, and trailing-slash variants all benefit from an explicit alternates.canonical.
| Field | Affects | Typical mistake |
|---|---|---|
title / template | Browser tab and search snippet | Duplicate titles across pages |
description | Snippet and card text | Missing or copy-pasted text |
openGraph.images | Social preview card | Relative path without metadataBase |
alternates.canonical | Index consolidation | Canonical pointing to a redirect |
robots | Crawl and index | noindex left on in production |
twitter.card | X preview shape | Large image with card left at summary |
Sitemaps and robots from the file conventions
You do not need a build plugin to publish a sitemap. A sitemap.js file in the app directory exports an array of entries, and Next.js serves the XML. When content lives in a database, the sitemap reads it at request or revalidation time, so new posts appear without a deploy. robots.js pairs with it, telling crawlers which trees are fair game.
// app/sitemap.js
export default async function sitemap() {
const posts = await getAllPosts();
const base = 'https://www.example.com';
const staticRoutes = ['', '/pricing', '/blog'].map((path) => ({
url: base + path,
lastModified: new Date(),
changeFrequency: 'weekly',
priority: path === '' ? 1 : 0.7,
}));
const postRoutes = posts.map((post) => ({
url: `${base}/blog/${post.slug}`,
lastModified: post.updatedAt,
changeFrequency: 'monthly',
priority: 0.6,
}));
return [...staticRoutes, ...postRoutes];
}
// app/robots.js
export default function robots() {
return {
rules: [
{ userAgent: '*', allow: '/', disallow: ['/admin', '/api'] },
{ userAgent: 'GPTBot', disallow: '/' },
],
sitemap: 'https://www.example.com/sitemap.xml',
};
}
Large sites should split sitemaps into indexes past fifty thousand URLs, and never list routes that return non-200 responses â a sitemap full of 404s burns crawl budget and drags quality signals down.
JSON-LD structured data
Structured data describes your page in schema.org vocabulary so search engines can render rich results â breadcrumbs, product prices, FAQ snippets, article bylines. Next.js has no special API for it; you render a script tag with the serialized object inside your page component.
// app/blog/[slug]/page.js â JSON-LD for an article
export default async function BlogPost({ params }) {
const { slug } = await params;
const post = await getPost(slug);
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 },
image: post.coverImage,
mainEntityOfPage: {
'@type': 'WebPage',
'@id': `https://www.example.com/blog/${post.slug}`,
},
};
return (
<article>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
<h1>{post.title}</h1>
{post.content}
</article>
);
}
The dangerouslySetInnerHTML call is the documented way to inject a script in React; the risk is only real if the object contains user-controlled strings that could break out of the JSON, so escape or sanitize before serializing when any field comes from untrusted input.
The rendering pipeline view
Think of a request as producing two artifacts: HTML for crawlers and users, and metadata that rides along in the head. The Metadata API merges layout-to-page values, generateMetadata results override static exports, and the serializer emits the final tags. Knowing the merge order explains the "why is my title wrong" bugs: a stale metadata export deep in a route group, a page exporting both a static object and a function, or a description inherited from a layout that was never overridden.
Production pitfalls
The classic production SEO failures are mechanical. robots: { index: false } copied from staging and never removed, de-indexing the entire site. Canonical URLs that include pagination or filter parameters, consolidating distinct pages into one. Sitemap routes pointing at draft content. Open Graph images generated at request time without caching, so every social preview bot hammers the origin. And titles that duplicate across paginated or filtered views because generateMetadata ignores searchParams when building them.
Writing titles and descriptions that earn the click
The metadata fields are also copy, and the character budgets are real. Titles render around sixty characters before search engines truncate them, so the specific subject belongs first and the brand last â the template's job. A title that says nothing beyond the brand wastes the snippet. Descriptions run roughly one hundred and fifty characters; they do not affect ranking directly, but they determine whether the ranking converts into a visit. The habit that helps most is writing these two strings in the same pull request as the page, reviewing them like marketing copy, and forbidding the copy-paste of a previous page's description â duplicate descriptions across routes signal laziness to both crawlers and users. For templated pages, generateMetadata can compose a pattern â product name plus category plus a differentiator â so every dynamic page still reads as specific. Treat the snippet as the page's first impression and the audit that catches drift: a quarterly crawl of titles and descriptions, flagged when two routes collide, is a cheap quality program with measurable traffic effects.
Common Mistakes
Leaving noindex robots metadata in a production deploy
Fix: Drive the robots value from an environment variable and assert in CI that production builds set index to true.
Pointing canonical at URLs that redirect
Fix: Emit the final destination URL directly; canonicals should resolve 200 without hops.
Fetching post data separately in generateMetadata and the page
Fix: Share one getPost function; Next.js memoizes identical fetches within the request, so the second call is free.
Serving a sitemap that includes unauthenticated draft routes
Fix: Filter drafts in the sitemap query and revalidate the sitemap when publish state changes.
Best Practices
- Set metadataBase once in the root layout and keep every OG image absolute
- Write unique titles and descriptions per route; treat them as product copy with character budgets
- Generate sitemaps from the same canonical queries the pages use
- Validate JSON-LD with a rich results test whenever you change its shape
Interview Questions
Q1: How do static metadata and generateMetadata interact?
Both are merged field by field, with the page-level result winning on conflicts; layout exports provide the base that pages override.
Q2: Why does metadataBase matter for social cards?
Open Graph scrapers require absolute image URLs. metadataBase lets relative paths in your metadata resolve correctly instead of yielding broken previews.
Q3: When should a sitemap be revalidated?
Whenever content is published, updated, or removed; on-demand revalidation or a scheduled rebuild keeps it in step with the database without deploys.
Key Takeaways
- Export metadata statically for fixed pages and use generateMetadata for content driven by params.
- metadataBase, canonical alternates, and absolute OG images are the foundation of correct social and search rendering.
- File-convention sitemaps and robots.js replace plugins and can read live data with revalidation.
- JSON-LD rendered as a script tag earns rich results when it matches the visible page content.
- Audit noindex flags, canonical targets, and duplicate titles on every production release.