How to Change the Title and Description for Each Page in Next.js


In Next.js, by default, you can define metadata (like the title and description) in the app/layout.js
or app/page.js
file. This metadata is shared across your entire application unless you specify different metadata for individual pages. Here's how to customize metadata on a per-page basis.
Default Metadata in layout.js
When you create a Next.js project, you usually have a layout.js
file where you can define global metadata. This metadata will apply to all pages unless overridden.
Example: Default Metadata
// app/layout.js
export const metadata = {
title: "My Awesome Blog",
description: "Welcome to my awesome blog! Discover great content about web development.",
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
In this example, every page will use the title
and description
defined in layout.js
unless you specify different metadata on a per-page basis.
Custom Metadata for Specific Pages
If you want a specific title or description for individual pages, you can add an export const metadata
object in the page file. This will override the default metadata for that page.
Example: Setting Metadata for the Homepage
// app/page.js
export const metadata = {
title: "My Awesome Blog - Homepage",
description: "Welcome to my awesome blog where I share tips and tutorials about web development.",
};
export default function HomePage() {
return (
<main>
<h1>Welcome to My Awesome Blog</h1>
<p>Discover amazing content about coding and web development.</p>
</main>
);
}
In this example, the homepage will have a unique title and description that override the default metadata in layout.js
.
Example: Setting Metadata for a Blog Post
For dynamic routes, like a blog post page, you can also define custom metadata by using dynamic parameters. Here's how:
// app/blog/[slug]/page.js
export const metadata = {
title: "Dynamic Blog Post - My Awesome Blog",
description: "This is a blog post about dynamic content in Next.js.",
};
export default function BlogPostPage({ params }) {
const { slug } = params;
return (
<article>
<h1>Post Title for {slug}</h1>
<p>This is the blog post content.</p>
</article>
);
}
Key Points
Default Metadata: Defined in
layout.js
, applied globally unless overridden.Custom Metadata: Use
export const metadata
in individual page files to override the default.
Conclusion
Next.js makes it straightforward to manage metadata for your application. Use default metadata for global settings and override it for specific pages as needed. This approach ensures your app is SEO-friendly and provides a great user experience.
Subscribe to my newsletter
Read articles from AmmarSyedK directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
