Next.js › Metadata API & SEO Optimization
How do you generate dynamic metadata for a page based on data fetched at request time, such as a product page?
IntermediateAnswer
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.