Search code examples
reactjsnext.jsnext.js13app-router

Reset title to metadata value after changing it dynamically


In my Next.js project, I change the page title dynamically in reaction to an event:

if (unread_count === 0) {
  document.title = "Flow Chat";
} else {
  document.title = `Flow Chat - ${unread_count} unread messages`;
}

The default title of the page is set in the layout.tsx:

export const metadata: Metadata = {
  title: "Flow Chat",
  description: [...],
};

Is it possible to reset the page title to the one set in metadata instead of hardcoding the text a second time?


Solution

  • The obvious thing here is to simply import the defined metadata from your layout.tsx into the file you want to use it, however this is not possible if you want to use it in a "use client" file.

    You can solve this by creating some kind of separate file where you declare your metadata, say constants/metadata.

    export const defaultMetadata: Metadata = {
      title: "Flow Chat",
      description: [...],
    };
    

    This you can import into the layout.tsx

    import { defaultMetadata } from "@/constants/metadata";
    
    export const metadata = defaultMetadata;
    

    and your client.tsx

    "use client"
    
    import { defaultMetadata } from "@/constants/metadata";
    
    if (unread_count === 0) {
      document.title = defaultMetadata.title;
    } else {
      document.title = `Flow Chat - ${unread_count} unread messages`;
    }