nextjs14

Meta Title description in another pages in next js


My next js is in 14.0.4. I have developing for static site generator from NextJS. Here, I am trying to set meta title in different pages with different value. But not working any more from my side. my layout,page,contact are as follows:

app/layout.tsx

import type { Metadata } from 'next';
import './globals.css';

export const metadata: Metadata = {
  title: 'My Title',
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <head>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
      </head>
      <body>
        {children}
      </body>
    </html>
  );
}

app/page.tsx

"use client";

export default function Home() {
  return (
    <>    
      <h1>This is my home page</h1>
    </>
  );
}

app/contact.tsx

"use client";

export default function Home() {
  return (
    <>    
      <h1>This is the contact page</h1>
    </>
  );
}

Here, in home page and contact page it display meta title "My Title" but I want to display different meta title in contact page. But, I could not find solution for it. Your small hint is required . plz


Solution


  • Metadata should be defined only in page.tsx or layout.tsx files. It must be a Server Component, so it won't work with the "use client" directive.

    Regarding file structure:

    Note: For component files, it's a common convention to use PascalCase (e.g., Contact.tsx or Button.tsx).


    Correct code for app/page.tsx:

    // NO "use client" NEEDED
    import type { Metadata } from "next";
    
    export const metadata: Metadata = {
      title: 'Home Title',
    };
    
    export default function Home() {
      return (
        <>    
          <h1>This is my home page</h1>
        </>
      );
    }
    

    For reference, see the official documentation:
    Next.js Metadata Documentation