I am working on a Next.js project and trying to set dynamic metadata for different pages. I want my homepage title to show as Home | My Website, but it’s only showing Home. Here’s how I configured the metadata for the layout and the homepage:
Layout:
export const metadata: Metadata = {
title: {
template: "%s | My Website",
default: "My Website",
},
description: "My Website",
};
Home Page:
export const metadata: Metadata = {
title: "Home",
};
I expected the homepage title to use the template and show "Home | My Website", but it only shows "Home". How can I ensure the template is applied correctly to the homepage title?
Next.js v14.2.7
2
Answers
The docs state this:
Which means you can’t use it on the same segment, you can use it on child segments for example
app/about/page.tsx
orapp/blog/layout.tsx
To ensure that the title template ("%s | My Website") is applied correctly for your homepage, you need to understand how the title configuration works in Next.js. The issue arises because when you define the metadata in both the Layout and the Home page, the title on the page level will override the template from the Layout.
Here’s how you can make the template work as expected:
Solution
Instead of setting the title directly in the Home page metadata, you
can just use the title: "Home", and the template from the layout
will be applied automatically.
page-specific metadata with the layout-level metadata by default,
but explicitly overriding the title in the page might cause it to
ignore the template.
Modify the homepage to not override the metadata title like this:
Layout (as you already have it):
Home Page (do not override title template):
Explanation:
automatically applies the title.template defined in the layout.
turned into "Home | My Website", as defined in the layout’s
title.template.
This should fix the issue, and your homepage title will now correctly show "Home | My Website".