Dynamic Metadata Passing from Content in NextJS

In the previous lesson, we learned how to set metadata in the site content. This method is good, but not always applicable. The point is that page metadata can change depending on a dynamic route parameter.

Let's look at an example. Suppose we have a content file for displaying a user by their id. Suppose this file contains an array of users:

app/users/[id]/page.jsxlet users = [
  'user1',
  'user2',
  'user3',
  'user4',
  'user5',
];

Let's output the data of the user corresponding to the passed parameter:

app/users/[id]/page.jsxexport default function User({ params }) {
  return <>
    <h1>user {params.id}</h1>
    <p>
      name: {users[params.id]}
    </p>
  </>;
}

Now let's move on to our problem. Since we are showing different users, the metadata for them should also be different. We need to form it dynamically, depending on the parameter value.

This is done using a special function generateMetadata, which we must export from our component:

src/app/test/page.jsxexport const generateMetadata = () => {
  return {
    title: '',
    description: '',
  };
};

In this function, we have access to the route parameters:

src/app/test/page.jsxexport const generateMetadata = ({params}) => {
  console.log(params);
};

Let's return the necessary metadata depending on the parameter value:

src/app/test/page.jsxexport const generateMetadata = ({params}) => {
  return {
    title: `Page for user {params.id}`,
    description: `Description for user "{users[params.id]}"`,
  };
};
Задание 1

Create a route that handles addresses like /post/:id, where instead of :id there can be any number.

Given the following array:

page.jsxlet posts = [
  {
    id: '1',
    title: 'post 1',
    desc: 'description for post 1',
    text: 'text1 text1 text1 text1 text1 text1 text1 text1',
  },
  {
    id: '2',
    title: 'post 2',
    desc: 'description for post 2',
    text: 'text2 text2 text2 text2 text2 text2 text2 text2',
  },
  {
    id: '3',
    title: 'post 3',
    desc: 'description for post 3',
    text: 'text3 text3 text3 text3 text3 text3 text3 text3',
  },
];

export default function Post() {
  
}

Make sure that for a given id the markup of the corresponding post is displayed, and the correct title and meta description are set.