Understanding generateMetadata and Static Props in Next.js
If you have been working with Next.js, you must have encountered this framework allowing you to easily customize metadata for your applications. Metadata refers to information that can include the title of the page, descriptions, keywords, and other factors. This information is very important in SEO (Search Engine Optimization) and can significantly affect the visibility of your web pages.
In the latest versions of Next.js, we have a feature called generateMetadata
that allows us to dynamically create metadata for each page. This functionality is especially beneficial when you are dealing with websites that contain variable and non-static content. By using this feature, you can specify that the metadata be based on specific data for each request.
Now, let's take a look at how to use generateMetadata
effectively. For example, suppose you have a news website that includes a title and specific descriptions for each news article. You can utilize generateMetadata
to automatically adjust the metadata for each news piece.
Furthermore, we will review a simple example of how to use generateMetadata
. I intend to provide a base structure for this task. Here is a sample code snippet from Next.js structure:
export async function generateMetadata({ params }) {
const { id } = params;
const newsItem = await getNewsById(id);
return {
title: newsItem.title,
description: newsItem.description,
};
}
Code Explanation
In this code, we initially define the generateMetadata
function, which receives a parameter called params
. This parameter often contains information that allows us to access specific data for each page.
Then, using const { id } = params;
, we extract the news identifier from the input parameters. This identifier will be used for fetching the relevant news data.
Now, by using this parameter with getNewsById(id)
, we can fetch the news data based on the identifier. This function can retrieve news data from an API or a database.
Ultimately, we return an object containing two properties: title
and description
. These are the metadata attributes related to our news which will be set automatically. This metadata will be utilized in the <head>
of your page.