How to use metadata when using “use client” in next Js 14
When working with metadata or a consistent UI across multiple pages, Next.js uses layout.js
files. Here’s how it works and how it applies to use metadata scenario:
- The
layout.js
file defines a consistent layout for any pages within the same route segment (folder). It is shared across the pages nested in that directory. - This allows you to define common elements (like headers, footers, and sidebars) that will appear across multiple pages.
- here we are using layout.js file for our pages.
Example with Metadata in Layout.js
follow this structure:
/app /home layout.js page.js /about layout.js page.js
Here’s how you’d configure the metadata for each page:
1. Home Layout (app/home/layout.js
):
// app/home/layout.js export const metadata = { title: 'Home Page', description: 'Welcome to the home page of our website!', }; export default function HomeLayout({ children }) { return ( <div> <header>Home Page Header</header> <main>{children}</main> <footer>Home Footer</footer> </div> ); }
- metadata: This sets the title and description for the entire home section.
- Layout: It wraps the
children
(the content ofpage.js
for home) with a header, footer, etc.
2. About Layout (app/about/layout.js
):
// app/about/layout.js export const metadata = { title: 'About Us', description: 'Learn more about us on this page.', }; export default function AboutLayout({ children }) { return ( <div> <header>About Page Header</header> <main>{children}</main> <footer>About Footer</footer> </div> ); }