Search code examples
next.js

How to make a single request with next js and generate metadata?


I have been testing Next.js App routes, and it's making two requests. It may seem obvious, but I'm struggling to find sufficient documentation to only make one request to fetch product information and pass it to both the page and generateMetadata function.

import { Metadata, ResolvingMetadata } from "next"
import Product from "@/components/Product/product.component"

type Props = {
    params: { ean: string }
}

async function getProduct(ean: string) {
    const res = await fetch(process.env.API_URL + `/v1/products/${ean}`)
    return res.json()
}

export async function generateMetadata({ params: { ean } }: Props, parent: ResolvingMetadata
): Promise<Metadata> {
    const productData = getProduct(ean)

    const [product] = await Promise.all([productData])

    return {
        title: product.name,
    }
}

export default async function Page({ params: { ean } }: Props) {
    const productData = getProduct(ean)

    const [product] = await Promise.all([productData])

    return <Product product={product} />
}

I need to know if this is the best possible solution or if there is a better one


Solution

  • Edit: I probably did not read the question carefully. My answer below has nothing to do with the question and should be disregarded.

    It's not a bug, it's a feature.

    ...help you find accidentally impure code, Strict Mode calls some of your functions (only the ones that should be pure) twice in development. This includes...

    You can read more about this here

    Fixing bugs found by double rendering in development

    If you disable Strict Mode (not recommended), it should go away. In production mode it should also go away. To do a quick check, run next build; next start