1

My Root Layout contains my main navigation component which needs to have a header for example 'Library' on one page and 'Configuration' on a another. Is there a way to write my root layout such that the main navigation component inside it updates based on the page with a configurable header?

I've been trying to do it with metadata passing the title as prop to my nav component but that doesn't seem possible from that I've gathered from the docs and other stackoverflow posts.

Thanks in advance.

Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
codestomping
  • 133
  • 1
  • 6

1 Answers1

1

If you want to have different things in your layout depending on the path you are on, Next.js recommends the method explained in this thread (leveraging multiple layouts).

For smaller changes, you could make use of pathname with the help of a middleware as explained more in this thread:

// middleware.js

import { NextResponse } from "next/server";

export function middleware(request) {
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set("x-pathname", request.nextUrl.pathname);

  return NextResponse.next({
    request: {
      headers: requestHeaders,
    },
  });
}

// app/layout.js

import { headers } from "next/headers";

export default function RootLayout({ children }) {
  const headersList = headers();
  const pathname = headersList.get("x-pathname");
  return (
    <html lang="en">
      <body>
        <nav>
          {pathname === "/"
            ? "You are on the home"
            : pathname === "/about"
            ? "You are on about"
            : "You are elsewhere"}
        </nav>
        {children}
      </body>
    </html>
  )
}
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65