javascriptreactjsnext.js

Next.js (app directory) - Access page metadata in Layout


I am using the new app folder structure with Next.js 13 project, and I would like to display a subheader in the RootLayout containing the value of the Page title (I'm using metadata on each page to configure the head title).

Is there any way to directly access that value with SSR?

Example layout.js:

export default function RootLayout({ children) {
    const pageTitle = "???"; // How to get this value?
    return (
      <html>
        <body>
          <HeaderComponent />
          <div className="subheader">
            <h3>{pageTitle}</h3>        <------ HERE
          </div>
          <div className="content">{children}</div>
          <FooterComponent />
        </body>
      </html>
    )
);

Example page.js:

export const metadata = {
    title: "Login"
};

export default function Login() {
    return (
        <div>Login form</div>
    );
}

Solution

  • No, you cannot get that metadata in the layout with SSR, at least so far. A layout in the app folder gets passed an object that contains children and params when a dynamic route is used. That's it.

    Its role is to wrap all components of a route segment, not only page.js, but also loading.js, not-found.js...

    Anything specific to a component should be in it directly. A page title should be in page.js itself. Next.js decided that a project should be structured so.