How do you generate dynamic metadata for a page based on data fetched at request time, such as a product page?
Short answer
You export an async function called generateMetadata from your page file, fetch the relevant data inside it just like you would in the page component, and return a metadata object built from that data, letting each dynamic page have its own accurate, unique title and description.
Advertisement
AModel answer
You export an async function called generateMetadata from your page file, fetch the relevant data inside it just like you would in the page component, and return a metadata object built from that data, letting each dynamic page have its own accurate, unique title and description.
export async function generateMetadata({ params }) {
const { id } = await params;
const product = await getProduct(id);
return {
title: `${product.name} | My Store`,
description: product.shortDescription
};
}Real-world example
An online store generates a unique page title and description for every single product automatically, using that product's actual name and description pulled from the database, improving search visibility for thousands of pages at once.
Likely follow-ups
- Does generateMetadata run before or after the page component itself?
- How do you avoid fetching the same data twice in both generateMetadata and the page component?
Related topics