Next.js
/Intermediate
Dynamic Metadata
Definition
Using the `generateMetadata()` function to dynamically fetch data from a database and use it to construct SEO tags for a specific dynamic route.
Explain Like I'm New
If you have a dynamic route like `[productId]`, you can't hardcode the title. You need to look at the ID, fetch the product from the database, and make the title 'Buy the iPhone 15'. `generateMetadata` pauses the server, does exactly that, and then renders the page.
Real World Example
A blog post page where the browser tab title perfectly matches the title of the article fetched from the CMS.
Common Use Cases
- •E-commerce product pages
- •Blog posts
- •User profiles
Interactive Example
import { Metadata } from 'next'; import db from '@/lib/db'; // 1. Next.js runs this FIRST to build the <head> tags export async function generateMetadata({ params }): Promise<Metadata> { // Fetch the specific product based on the URL parameter const product = await db.getProduct(params.id); return { title: product.name, // e.g., 'Nike Air Max' description: product.summary, }; } // 2. Next.js runs this SECOND to build the <body> HTML export default async function ProductPage({ params }) { // This fetch is perfectly memoized and costs 0ms! const product = await db.getProduct(params.id); return <h1>{product.name}</h1>; }
Interview Questions
basic
- What function do you export to generate metadata based on route parameters?
intermediate
- If you fetch a product in `generateMetadata`, and then fetch the exact same product again in your `page.tsx` component, does Next.js query the database twice?