In the latest updates, version 13 and 14 of Next introduced the usage of the generateMetadata function as the preferred method to define all page metadata.
However, a drawback of this approach is that because of the separation of logic, fetching data based on backend fields now requires making two separate calls instead of just one.
Let's look at the example below in the file page.tsx
:
export default async function ProfilePage(props){
try{
const profile = await prisma.users.findUnique({
// ... fetch user data
});
return <div>Profile page</div>;
} catch(err){
notFound();
}
}
export async function generateMetadata(params){
const profile = await prisma.users.findUnique({
// ... fetch user data
});
return {
title: `${profile.name}'s Profile`,
};
}
This leads to redundant data fetching, meaning I have to retrieve the same information twice.
Is there a way to achieve the same outcome without having to duplicate the fetch process? Instead of resorting to using document.title
, which can result in a disruptive experience when applied to nested pages. How should I go about resolving this issue?