Next.js - generateMetadata Function



In Next.js generateMetadata() function is used to dynamically generate metadata based on route parameters or fetched data. In this chapter we will learn, what is generateMetadata function, how to use it, syntax and example usage of generateMetadata method.

Next.js Generate Metadata Method

The generateMetadata function is a feature introduced in Next.js 13+ (App router) to simplify the management of metadata. This function can create metadata based on route parameters or fetched external data. That means when user navigate to a product page in our website, the title changes to name of current product.

Syntax

Following is syntax of generateMetadata function.

// Import library
import { Metadata } from "next";

// Dynamic Metadata function
export const generateMetadata = (prams, searchParams): Metadata => {
    return {
        title: `Product ${params.id} - My Store`,
        description: "Page Description"
        // Other metadata
    };
}
  • params: This define route parameters. For example, { id: "123" } for a dynamic route like /blog/[id].
  • searchParams: This define query parameters from the URL. For example { sort: "asc" } for a URL like /blog?sort=asc

Example of Using generateMetadata

In the following code, we will generate a dynamic title (ie, the metadata) for a component based on page selected by user. Learn how dynamic routes works before going through the example.

// app/products/[id]/page.tsx

import { Metadata } from "next";

type Props ={
    params: {
        id: string;
    };
}
// Dynamic Metadata function
export const generateMetadata = ({ params }: Props): Metadata => {
    return {
        title: `Product ${params.id} - My Store`,
    };
}

export default function ProductPage({params }: Props) {

    return (
        <div>
            <h1>Product {params.id}</h1>
            <p>This is the product page for item {params.id}</p>
        </div>
    );
}

Output

In the output you can see that the title of page is changing based on route we choose.

Dynamic Meta Data
Advertisements