Note 20260824013954
In next.js, if you want to add metadata and avoid repeating it on other pages, for example, if your project is called Cool Dashboard and you want the name Cool Dashboard to appear on multiple pages, not just on a specific one, the most tedious method is usually:
// app/layout.tsx
import { Metadata } from 'next';
export const metadata: Metadata = {
title: 'Cool Dashboard',
description: 'My project that have a cool dashboard.',
metadataBase: new URL('https://cool-dashboard.com'),
};Then, on another page where you want the title to include "Cool Dashboard," you would have to write it out again:
// app/about.tsx
import { Metadata } from 'next';
export const metadata: Metadata = {
title: 'About | Cool Dashboard',
};While the method above is perfectly valid, it becomes problematic as your project grows; if you ever decide to rename your project, you would have to update the title on every single page.
Therefore, there is something easier, very suitable if our project pages are many, and if at some point our project changes name, we just need to change it in the root layout.
You can define the metadata in your root layout like this:
// app/layout.tsx
import { Metadata } from 'next';
export const metadata: Metadata = {
title: {
template: '%s | Cool Dashboard',
default: 'Cool Dashboard',
},
description: 'My project that have a cool dashboard.',
metadataBase: new URL('https://cool-dashboard.com'),
};In this code, you simply add a template property to the metadata object. The %s template will replace the specific page title, but if you don't fill in the title, it will automatically have the default title Cool Dashboard.
Then, for other pages where you want to include "Cool Dashboard" in the title, you simply do this:
// app/documentation.tsx
import { Metadata } from 'next';
export const metadata: Metadata = {
title: 'Documentation',
};You just need to set the title in the metadata object to the text that should replace the %s placeholder. For more information, visit the official Next.js documentation on Adding Metadata.