0
0
NextJSframework~5 mins

GenerateMetadata for dynamic metadata in NextJS

Choose your learning style9 modes available
Introduction

GenerateMetadata lets you create page titles and descriptions that change based on the page content. This helps your website show the right info in search results and browser tabs.

You want each blog post to have its own title and description.
You have a product page that shows different product names and details.
You want to update metadata based on user input or URL parameters.
You want better SEO by customizing metadata for each page dynamically.
Syntax
NextJS
export async function generateMetadata({ params }) {
  // fetch or compute data based on params
  return {
    title: `Title for ${params.id}`,
    description: `Description for ${params.id}`
  };
}

The function must be async if you fetch data.

Return an object with metadata fields like title and description.

Examples
Static metadata without parameters.
NextJS
export async function generateMetadata() {
  return {
    title: 'Home Page',
    description: 'Welcome to the home page'
  };
}
Dynamic metadata using URL parameters.
NextJS
export async function generateMetadata({ params }) {
  return {
    title: `Post: ${params.slug}`,
    description: `Read about ${params.slug}`
  };
}
Fetching data to create metadata dynamically.
NextJS
export async function generateMetadata({ params }) {
  const data = await fetch(`https://api.example.com/posts/${params.slug}`);
  const post = await data.json();
  return {
    title: post.title,
    description: post.summary
  };
}
Sample Program

This example shows a page component that uses generateMetadata to set the page title and description based on the URL parameter slug. The page content also uses the slug to display the post.

NextJS
import React from 'react';

export async function generateMetadata({ params }) {
  const post = {
    title: `Post about ${params.slug}`,
    description: `This is a detailed post about ${params.slug}.`
  };
  return post;
}

export default function PostPage({ params }) {
  return (
    <main>
      <h1>{`Post: ${params.slug}`}</h1>
      <p>{`Content for post ${params.slug} goes here.`}</p>
    </main>
  );
}
OutputSuccess
Important Notes

Always return an object with metadata fields from generateMetadata.

Use params to access dynamic route parts.

Metadata updates help search engines and improve user experience.

Summary

GenerateMetadata creates dynamic page titles and descriptions.

It runs on the server before the page renders.

Use it to improve SEO and show relevant info per page.