4

before next js 13 we used to do dynamic head as an import. but in Next JS 13 they introduced the head.js class. this works when using a static page, but when loading a dynamic how can we change the title and desc in the head? i directly imported the next/head and then assign the data but it didn't change the head.

export default function DetailPage({ params: { itemid } }) {

const [datas, setDatas] = useState({});

  const getData = async () => {
    const docRef = doc(db, "items", itemid);
    const docSnap = await getDoc(docRef);
    setDatas(docSnap.data());
  };

  useEffect(() => {
    if (Object.keys(datas).length == 0) {
      getData();
    }
  }, [datas]);

return (

<>
<Head>
        <title>{datas.title}</title>
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <meta
          name="keywords"
          content="some contents"
        />
        <meta
          name="description"
          content={datas.desc}
        />
      </Head>

  <section>...</section>

</>

)

}
2
  • When you print datas.title did you get the real value ?
    – dom1
    May 15 at 15:47
  • @dom1 yes it prompts May 15 at 16:03

1 Answer 1

6

I am guessing you are using the app directory, the Head component has been replaced by the generateMetadata API. Usage could use something like this inside your page:

import type { Metadata } from "next";

export function MyPage(): Promise<JSX.Element> {
  return <></>;
}

export async function generateMetadata(): Promise<Metadata> {
  const data = await getMyData();
  return {
    // return your metadata here
  };
}

You can find a full API reference and a method for static metadata inside the official docs.

7
  • 2
    thats not working either. i've tried statically and dynamically but nothing May 16 at 8:13
  • I'm using firebase and i'm storing the fetched value inside useState. but the metadata only works in server side May 16 at 10:00
  • 1
    it was my version, after upgrading it to the latest version it works May 16 at 11:10
  • 2
    ... so now you have to make the same request twice if you wanted that data in your page? -1 Jun 24 at 1:28
  • 1
    Poorly doucmented and not expressive enough. Next.js. Aug 11 at 7:20

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.