Currently, I am developing a project in NextJs 14 and utilizing the App Router. In my server component app/blogs/[slug]/page.tsx
, I have written the following code:
import { Metadata } from "next";
type GenerateMetadataProps = {
params: { slug: string };
};
export async function generateMetadata({ params }: GenerateMetadataProps): Promise<Metadata> {
// First database query
const blog = await prisma.blog.findFirst({
where: { slug: params.slug },
});
return {
title: `${blog?.title} | Blog - MyWebsite`,
description: blog?.subtitle,
}
}
type BlogDetailPageProps = {
params: { slug: string };
searchParams?: { [key: string]: string | string[] | undefined };
}
const BlogDetailPage = async ({ params, searchParams }: BlogDetailPageProps) => {
const { slug } = params;
// Second database query. A bit redundant to call twice 😥
const blog = await prisma.blog.findFirst({
where: { slug },
});
...
return (
<>
...
</>
);
};
export default BlogDetailPage;
The issue at hand is that I need to make two separate queries to the database to fetch data for the dynamic metadata (generateMetadata
) and the dynamic component (BlogDetailPage
). This approach seems inefficient as it involves repeating the same query.
I am wondering if there is a way in NextJs to optimize this process by fetching the blog data from the database only once and then using it in both the generateMetadata
function and the BlogDetailPage
component?