How can we change page title after we get the data from server and want to load in client side or server side component?

56 views Asked by At

I would like to update pages title when navigating. I could figure out the static version of it but how can we use it dynamically.

Exp: If we are navigating to and item and want to mention the item's name in the title.

I used the code below to update the metadata but would like to know how can we make it dynamic on page load?

I am using the code below for the static method before the server side component definition.

Exp: Metadata for contact page:

import type { Metadata } from "next";

export const metadata: Metadata = {
  title: "Contact Us",
  description:
    "Get in touch with us using our contact list. We will get back to you as soon as possible.",
};
1

There are 1 answers

0
Anatol Zakrividoroga On BEST ANSWER

From Next.js docs: https://nextjs.org/docs/app/building-your-application/optimizing/metadata

Dynamic Metadata

You can use generateMetadata function to fetch metadata that requires dynamic values.

import type { 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://.../${id}`).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) {}