What is the best way to handle db request once to create Dynamic routes & generateMetadata
Answered
Daggertooth pike conger posted this in #help-forum
Daggertooth pike congerOP
import { Metadata, ResolvingMetadata } from 'next'
import Image from 'next/image';
import { db } from '@/lib/db';
type Props = {
params: { username: string }
searchParams: { [key: string]: string | string[] | undefined }
}
async function fetchUser(username: string) {
return await db.user.findFirst({
where: {
username: username
}
});
}
export async function generateMetadata(
{ params, searchParams }: Props,
parent: ResolvingMetadata
): Promise<Metadata> {
const username = params.username
const user = await fetchUser(username);
const previousImages = (await parent).openGraph?.images || []
const image = user?.image || "some-blabla.jpg"
return {
title: `${user?.name} blablabla ` || 'Default text',
openGraph: {
images: [image, ...previousImages],
},
}
}
const UserPage = async ({ params, searchParams }: Props) => {
const user = await fetchUser(params.username);
return (
<div>
{user?.email}
</div>
);
};
export default UserPage;Answered by Plott Hound
Use unstable_cache https://nextjs.org/docs/app/api-reference/functions/unstable_cache
1 Reply
Plott Hound
Use unstable_cache https://nextjs.org/docs/app/api-reference/functions/unstable_cache
Answer