I am having multiple dynamic routes in my nextjs application like /[product] and /u/[user]
I am using this code to generate dynamic meta tags for /[product]
import React from 'react'
import { host } from '@/host';
import Product from '../../../../components/Product';
export async function generateMetadata({ params }) {
const response = await fetch(`${host}/api/product/details`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ product: params.product }),
});
const json = await response.json();
return {
title: `${json.product.name} - ${json.product.tagline} | Product Information and Reviews `,
description: json.product.description,
keywords: json.product.tags,
openGraph: {
type: "website",
siteName: "myapp",
title: `${json.product.name} - ${json.product.tagline} | Product Information and Reviews `,
description: json.product.description,
images: json.product.thumbnail
},
twitter: {
card: "summary",
title: `${json.product.name} - ${json.product.tagline} | Product Information and Reviews `,
description: json.product.description,
images: json.product.thumbnail
},
};
}
const Page = ({params}) =\> {
return (
\<Product params={params} \>\</Product\>
)
}
export default Page
I am getting the correct response for my product page but when I use a similar code for my /u/[user] page, I am getting an errror :
Error: Cannot read properties of undefined (reading 'username')
here is the code:
import React from "react";
import { host } from "@/host";
import UserProfile from "../../../../components/UserProfile";
export async function generateMetadata({ params }) {
const response = await fetch(`${host}/api/user/fetchuniqueuser`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ profile: params.user }),
});
const json = await response.json();
return {
title: `${json.fetchuniqueuser.username}`,
};
}
const UserPage = ({ params }) =\> {
return \<UserProfile params={params}\>\</UserProfile\>;
};
export default UserPage;
However when I hit the same api call from my client side component inside my useEffect hook, I am getting the desired data:
useEffect(() => {
async function fetchUser() {
const response = await fetch(`${host}/api/user/fetchuniqueuser`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ profile: params.user }),
});
const json = await response.json();
console.log(json)
setuser(json.fetchuniqueuser)
}
fetchUser()
}, [params])
Can anyone tell me whats wrong here
Also is there any easier method to set dynamic meta in nextjs app router ?
Please help me
I expected that generateMetadata will work in multiple dynamic routes but its not working as expected.