To add meta tags for a specific page in a Next.js app using the app router (introduced in Next.js 13), you will typically use the Head component from next/head. However, with the app router, the way you structure your pages and handle meta tags can differ slightly from the pages router.
Here's a basic example of how to add meta tags for a specific page in an app that uses the app router. Let's assume you have a page named about located at app/about/page.js.
// app/about/page.js
import Head from 'next/head';
export default function AboutPage() {
return (
<>
<Head>
<title>About Us</title>
<meta name="description" content="This is the about page" />
<meta property="og:title" content="About Us" />
<meta property="og:description" content="This is the about page" />
</Head>
<main>
<h1>About Page</h1>
{/* Your page content here */}
</main>
</>
);
}
In this example, the Head component is used within the AboutPage component to specify the meta tags for the about page. This approach works well for static metadata.
However, if your meta tags are dynamic and depend on server-side rendering (SSR) or other asynchronous data, you might need to use getServerSideProps (for SSR) or fetch data using useEffect or a library like React Query.
For server-side rendered (SSR) pages, where you might need to pre-render meta tags:
// app/about/page.js
import Head from 'next/head';
export default function AboutPage({ data }) {
return (
<>
<Head>
<title>{data.title}</title>
<meta name="description" content={data.description} />
</Head>
<main>
<h1>{data.title}</h1>
{/* Your page content here */}
</main>
</>
);
}
export async function GET() {
const data = await fetchDataFromAPI(); // Replace with your actual data fetching logic
return NextResponse.json(data, {
status: 200,
});
}
And then, ensure you handle the data appropriately in your component.
Remember, when using the app router and handling metadata, the approach can vary based on your specific needs, such as static site generation (SSG), server-side rendering (SSR), or using internationalized routing. Always refer to the latest Next.js documentation for the most current best practices and features.