generateMetadata for Dynamic SEO and Social Cards
The title tag and description meta are the only parts of your application that most people will ever read before deciding whether to click. They appear in search results, in link unfurls in Slack and WhatsApp, and in the browser tab. In a Server Component framework they are also one of the few places where the value depends on the data: the title of a blog post lives in the database, so it cannot be a constant string in a config file.
generateMetadata is the function that closes that gap. It runs on the server during rendering, receives the same params and searchParams as your page, and returns an object that Next.js turns into head tags. This lesson covers what it can and cannot do, how static and dynamic metadata combine, and the specific fields that control what a shared link looks like.
Prerequisites
- !Server Components and async page functions
- !Dynamic routes and params
- !A rough idea of what Open Graph tags are
What You'll Learn
- 1Write generateMetadata that reads route params safely
- 2Build complete Open Graph and Twitter card output
- 3Set canonical and alternate URLs for multi-locale sites
- 4Diagnose missing or duplicated head tags after a deployment
Two ways to declare a head
Next.js gives you a static export and a function, and it merges them. export const metadata is a plain object evaluated once at build; export async function generateMetadata({ params, searchParams }) is called per request for dynamic routes. You may use both in the same file â the dynamic result is shallow-merged over the static one, so the static object is best treated as defaults for keys the function does not return.
// app/blog/[slug]/page.js
import { getPost } from '@/lib/posts';
// Defaults for every route in this segment.
export const metadata = {
metadataBase: new URL('https://example.com'),
robots: { index: true, follow: true },
};
export async function generateMetadata({ params }) {
const { slug } = await params;
const post = await getPost(slug);
if (!post) {
return { title: 'Post not found' };
}
const url = `/blog/${post.slug}`;
return {
title: post.title,
description: post.excerpt,
alternates: { canonical: url },
openGraph: {
type: 'article',
url,
title: post.title,
description: post.excerpt,
publishedTime: post.publishedAt,
authors: [post.author.name],
images: [{ url: post.coverImage, width: 1200, height: 630, alt: post.title }],
},
twitter: {
card: 'summary_large_image',
title: post.title,
description: post.excerpt,
images: [post.coverImage],
},
};
}
Two rules keep this honest. The function must not fetch anything the page will fetch again â if the post lookup is slow, you now pay for it twice, so share the result through a cache or a single data layer. And if the record does not exist, returning a title while the page calls notFound() is fine: the 404 status still wins.
Titles, templates, and where they apply
A title template declared once stops every page from spelling out your brand by hand. Set title.template in a layout and child pages inherit it; set title.default for the segment that has no explicit title. A page can opt out entirely by returning a full title object with absolute: true, which is what you want for the homepage or for a legal page that should not read "Privacy â Example â Example".
// app/(marketing)/layout.js
export const metadata = {
title: {
template: '%s | Example',
default: 'Example â products for careful people',
},
description: 'A shop that sells a small number of very good things.',
};
// app/(marketing)/about/page.js â renders "About us | Example"
export const metadata = { title: 'About us' };
// app/(marketing)/legal/page.js â renders exactly "Privacy Policy"
export const metadata = { title: { absolute: 'Privacy Policy' } };
Templates apply down the layout tree, not up. A title set in a child does not rewrite a parent's, and metadata objects merge shallowly: if generateMetadata returns an openGraph object, it replaces the static openGraph wholesale rather than merging field by field. Return the fields you need every time, or build the object from a shared helper.
The rules the function has to obey
generateMetadata runs during the server render, and its return value has to cross a serialization boundary on the way to the head. That single requirement eliminates a whole class of confusing failures. Every value must be a plain, JSON-representable primitive or nested object: strings, numbers, booleans, arrays, and plain objects. A Date instance assigned to publishedTime throws during serialization; calling .toISOString() on it first is not a style preference, it is a requirement. Functions cannot appear anywhere in the object, and neither can class instances or Maps.
The export itself carries constraints too. A file with a client component cannot export generateMetadata at all, because the function must execute on the server. And because the function runs before the page body is finished, any dynamic API it calls â cookies(), headers(), a search-params read â opts the route into dynamic rendering, which may quietly move a page you expected to be static. If you return a constant string from a function that reads a cookie, you have bought dynamic rendering for no benefit.
Finally, the function must be resilient. It runs for bots, crawlers, and prefetches as well as for humans, often with parameters you did not anticipate, and an exception here fails the whole request rather than degrading the head. Guard the missing-record case explicitly and return an honest fallback object instead of letting a lookup rejection propagate.
What the social preview actually reads
A link unfurl does not run your JavaScript. It fetches the HTML, looks for a small set of tags, and picks a fallback chain. Knowing the chain explains most "our preview is wrong" reports.
| Preview element | Primary tag | Fallback | Typical size limit |
|---|---|---|---|
| Title | og:title | <title> | 60 to 90 characters before truncation |
| Description | og:description | meta name="description" | 160 to 200 characters |
| Image | og:image | none â no image, no card | 1200 Ã 630 pixels |
| Card shape | twitter:card | summary | summary_large_image for images |
| Canonical URL | og:url | none | Absolute, https only |
Several practical consequences fall out of that table. Images must be absolute URLs, which is exactly why metadataBase exists: set it once in the root layout and relative image paths resolve correctly in every environment, including preview deploys on a different host. Dimensions should be declared, because a crawler that has to guess will often drop the image. And the image must be crawlable â a private storage bucket with an auth wall returns a blank card to every crawler.
Alternates, locales, and canonical discipline
Multi-locale sites need more than translated titles. alternates.canonical tells search engines which URL is the real one for a piece of content, and alternates.languages maps each locale to its own URL so the correct version surfaces in regional results.
// app/[locale]/blog/[slug]/page.js
export async function generateMetadata({ params }) {
const { locale, slug } = await params;
const post = await getPost(slug, locale);
const locales = ['en', 'fr', 'de'];
return {
alternates: {
canonical: `/${locale}/blog/${slug}`,
languages: Object.fromEntries(
locales.map((l) => [l, `/${l}/blog/${slug}`])
),
},
};
}
Without a canonical, the same article at /blog/post, /blog/post/ and ?ref=newsletter compete with one another and split ranking. Setting the canonical collapses those variants into one signal. What you should not do is canonicalise across locales: /fr/blog/post and /en/blog/post are different pages for different readers, and each needs its own entry in the language map.
Debugging head output that looks wrong
When the right tags are not in the response, check four things in order. First, confirm you are looking at server-rendered HTML rather than the hydrated DOM â view source, not inspect. Second, look for two exports fighting: a static metadata and a generateMetadata that returns overlapping keys, or a layout above you that sets the same field. Third, verify the route is actually dynamic; a statically generated page evaluated generateMetadata at build time, so data changed since then will not appear. Fourth, remember that streaming complicates this â if the head was flushed before your component resolved, the metadata came from whatever was available at flush time, so the fetch belongs inside generateMetadata, not in the page.
Validation beats guessing. Paste the production URL into the platform card validator for the social network you care about, and run the rendered HTML through a crawler that reports every title and description it finds. Each warning in those tools maps directly to one of the four checks above.
Common Mistakes
Fetching the post twice â once in generateMetadata and once in the page
Fix: Cache the lookup in a shared module or pass it through a request-scoped cache so both consumers hit the data layer once.
Returning an openGraph object with only a title
Fix: The static and dynamic objects merge shallowly, so a partial openGraph silently drops your image and description. Return the full set or build it with a helper.
Using relative image URLs without metadataBase
Fix: Set metadataBase once in the root layout so every environment produces absolute, crawlable image URLs.
Setting the canonical to the current URL including query parameters
Fix: Canonicalise to the clean path without tracking parameters, otherwise each campaign link becomes its own candidate.
Best Practices
- Declare brand-wide defaults in the root layout and override per segment
- Keep generateMetadata free of duplicate work the page will do anyway
- Generate Open Graph images at 1200 by 630 with the title in the image itself
- Validate a representative URL for every route shape after each deploy
Key Takeaways
- generateMetadata runs on the server with the page's params and returns plain head data.
- Static metadata and generateMetadata combine shallowly, so partial objects can drop fields.
- Title templates flow down the layout tree and can be overridden with an absolute title.
- Social previews read Open Graph tags with a fallback chain; absolute images win.
- Canonicals consolidate variants but must never collapse different locales into one URL.