Next.js Discord

Discord Forum

it is possible to call server api once and share data into Metadata & Component?

Unanswered
Giant panda posted this in #help-forum
Open in Discord
Giant pandaOP
As nextjs doc suggested, we can generate dynamic metadata with the help of "generateMetadata" function.

If we want to generate dynamic metadata we need to call API inside generateMetadata function to get data which are required to form metadata.

At the same time we are calling same API for Page also because we need to get data which are required to display in page.

so if there any way to share already received data inside generateMetadata from server with the help of API inside page as a props ?

so we can share same data in to place. this prevent from calling same API inside page component.

Dynamic metadata Example:

import { Metadata, ResolvingMetadata } from 'next'

type Props = {
params: { id: string }
searchParams: { [key: string]: string | string[] | undefined }
}

export async function generateMetadata(
{ params, searchParams }: Props,
parent: ResolvingMetadata
): Promise<Metadata> {
// read route params
const id = params.id

// fetch data
const product = await fetch(https://.../$%7Bid%7D%60).then((res) => res.json())

// optionally access and extend (rather than replace) parent metadata
const previousImages = (await parent).openGraph?.images || []

return {
title: product.title,
openGraph: {
images: ['/some-specific-page-image.jpg', ...previousImages],
},
}
}

export default function Page({ params, searchParams }: Props) {}

0 Replies