Back to Snippets
Next.jsTypeScript

Next.js Dynamic Metadata

Generate dynamic SEO metadata based on page params and fetched data.

nextjsseometadatadynamic
import type { Metadata } from class=class="text-emerald-400">"text-emerald-400">'next'

interface PageProps {
  params: Promise<{ slug: string }>
}

async function getPost(slug: string) {
  const res = await fetch(class="text-emerald-400">`https:class=class="text-emerald-400">"text-gray">//api.example.com/posts/${slug}`, {
    next: { revalidate: 3600 },
  })
  if (!res.ok) return null
  return res.json()
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { slug } = await params
  const post = await getPost(slug)

  if (!post) return { title: class=class="text-emerald-400">"text-emerald-400">'Not Found' }

  return {
    title: class="text-emerald-400">`${post.title} | My Blog`,
    description: post.excerpt,
    openGraph: {
      title: post.title,
      description: post.excerpt,
      images: [post.coverImage],
    },
  }
}

export default async function PostPage({ params }: PageProps) {
  const { slug } = await params
  const post = await getPost(slug)
  if (!post) return <div>Not found</div>
  return <article><h1>{post.title}</h1><p>{post.content}</p></article>
}

How to Use

Use generateMetadata in any page.tsx to set dynamic titles, descriptions, and Open Graph tags. Next.js calls this function at build time for static pages and at request time for dynamic ones.

Related Technology

Next.js

Have a Project in Mind?

Let's discuss how we can bring your idea to life. With 50+ projects delivered, we take you from first plan to a production-ready product, and we offer custom software development with fixed-price quotes. Book a free consultation, no commitment.

or book a free call