0 day streak
javascript / intermediate
Snippet

Dynamic SEO with generateMetadata

Next.js allows you to dynamically generate metadata for a page based on its parameters or fetched data. This is crucial for SEO and social media sharing in dynamic applications.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
import { Metadata } from 'next';
export async function generateMetadata({ params }): Promise<Metadata> {
const product = await fetchProduct(params.id);
return {
title: product.name,
description: `Buy ${product.name} for only ${product.price}`,
openGraph: { images: [product.image] }
};
}
nextjs
Breakdown
1
export async function generateMetadata
A reserved Next.js function used to define the head tags for a specific route segment.
2
const product = await fetchProduct(params.id)
Fetches data required for the metadata (Next.js automatically dedupes this fetch).
3
return { title: product.name, ... }
Returns a Metadata object that defines titles, descriptions, and OG tags.