How to add Canonical Meta Tags automatically to all pages with Next.js?
I'm building a Next.js application and need to add canonical meta tags to all pages automatically. How can I implement this without manually adding the tag to every single page?
I want to ensure proper SEO and avoid duplicate content issues and I've read that adding canonical meta tag to self page is a good practice. What is the best way to do this?
Solution
You can automatically add canonical meta tags to all pages in Next.js using several approaches.
The most easy and effective method is to configure metadataBase
and alternate.canonical
parameter in layout.tsx
file.
Here is an example of a metadata object configured to achieve this:
export const metadata: Metadata = {
title: {
template: "%s | Your Site",
default: "Your Site",
},
metadataBase: new URL("https://yoursite.com"),
alternates: {
canonical: './',
}
};
Configuring metadataBase
will allow you to use relative paths in all your metadata object, so the URL you add here will be used as a prefix for all your pages.
Setting alternates.canonical
to ./
will make all your pages their own route as canonical URL, their slug will be added automatically.
If you need to modify the canonical URL for a specific page, you can do it by overriding the metadata
object in the page component.
In my opinion, this is the best approach to add canonical meta tags as it's extremely simple, requires low code and no maintenance.
Alternative #1
If you're using server-side rendering, you can use the generateMetadata
function to override the canonical URL for a specific page,
and get the slug of the page from the params
object.
export async function generateMetadata({params}) {
return {
alternates: {
canonical: `https://example-site.com'/${params.slug}`,
},
};
}
Also, if you want to provide only the relative path, you can configure metadataBase
in the root layout.
Alternative #2
Another solution is to manually add the canonical meta tag to the root layout inside <head>
tag
export default function RootLayout({children}) {
const pathname = usePathname();
return (
<html lang="en">
<head>
<link rel="canonical" href={`https://example-site.com${pathname}`} />
</head>
<body>
{children}
</body>
</html>
);
}
However, this solution is not recommended as the latest versions of Next.js allow to define the canonical url directly in the metadata
object
or through the generateMetadata
function. I would use this only as a fallback solution for older versions of Next.js.