Next.js Metadata API: Control Your Site's Preview
The Next.js Metadata API is a structured way to control your page's `<head>` for SEO and social sharing. It lets you define titles, descriptions, and Open Graph images for crawlers and link previews.
WHY IT EXISTS Managing the HTML <head> is critical for SEO and how your site appears when shared. Doing this manually is error-prone, especially in dynamic applications where titles, descriptions, and images change per page. The Metadata API provides a centralized, type-safe way to manage this within the Next.js App Router.
THE MENTAL MODEL Think of the Metadata API as a configuration file for your page's identity. Instead of writing raw HTML tags like <title> or <meta>, you export a JavaScript object from your layout.js or page.js file. Next.js then takes this object and renders the correct HTML in the server-rendered response.
HOW IT WORKS Next.js looks for a special metadata export in your route segments (page.js or layout.js). For static metadata, you export a plain object. For dynamic metadata that depends on route parameters, like a blog post title, you export an async function called generateMetadata. Next.js also supports file-based metadata: placing a file like opengraph-image.jpg or robots.txt in a route segment applies it to that route and its children. Metadata is merged from the root layout down to the page, with child routes overriding parent settings.
WHEN TO USE IT Use it in any Next.js App Router project to manage SEO and social sharing. It's the standard way to set page titles, descriptions, canonical URLs, and social media card images (Open Graph and Twitter). It's also used for generating sitemap.xml for crawlers.
WHEN NOT TO USE IT This API is specific to the Next.js App Router. If you are using the older Pages Router, you would use the <Head> component from next/head instead. It's also not a full replacement for complex structured data (JSON-LD), though you can include JSON-LD scripts through the metadata object.
ONE CANONICAL EXAMPLE To set a dynamic title for a blog post page at app/blog/[slug]/page.js, you would fetch the post data and use generateMetadata. The function receives the route params as an argument. For example: export async function generateMetadata({ params }) { const post = await getPost(params.slug); return { title: post.title }; }. This ensures each blog post page has a unique, SEO-friendly title in its HTML <head>.
Read the original → nextjs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.