How do I set a canonical tag in Nextjs 13?
I used to use the <head>
tag, but now it seems deprecated and the generateMetadata
has no information about the canonical meta tag.
How do I set a canonical tag in Nextjs 13?
I used to use the <head>
tag, but now it seems deprecated and the generateMetadata
has no information about the canonical meta tag.
Per the last NextJS 14.2, you need to define the alternate directly in your root layout.tsx
to get automatically generated canonical for all your URLs according to the format.
export const metadata: Metadata = {
metadataBase: new URL(`https://www.mywebsite.com`),
title: {
template: '%s | My Website',
default: ` My Website`,
},
alternates: {
canonical: './',
}
};
It's important to have the './'.
You can find all the URL formats here: https://nextjs.org/docs/app/api-reference/functions/generate-metadata#url-composition
I figured out a way:
export async function generateMetadata({
params,
}: {
params: { slug: string };
}) {
const { slug} = params;
const siteURL = 'https://example.com';
return {
title: `Your title`,
description: `Your meta description`,
alternates: {
canonical: `${siteURL}/yourSlug/${slug}`,
},
};
}
Edit: Check the comments if you don't want to provide the absolute path for the canonical URL.
metadataBase
in your root layout, then you do not need to provide absolute path for the canonical
URL. Next.js will generate it for you. –
Smelly Per the last NextJS 14.2, you need to define the alternate directly in your root layout.tsx
to get automatically generated canonical for all your URLs according to the format.
export const metadata: Metadata = {
metadataBase: new URL(`https://www.mywebsite.com`),
title: {
template: '%s | My Website',
default: ` My Website`,
},
alternates: {
canonical: './',
}
};
It's important to have the './'.
You can find all the URL formats here: https://nextjs.org/docs/app/api-reference/functions/generate-metadata#url-composition
?ok=ok
will be removed. –
Sheepfold Set the default tags in the layout.tsx
file in the app
directory. Then use the metaDataBase to create a base url
. Then with the alternates
property you should be able to create canonical URLs for different routes of your website.
alternates: {
canonical: "/",
},
<Head>
<link rel="canonical" href="https://www.website.com/" />
</Head>
© 2022 - 2025 — McMap. All rights reserved.
?ok=ok
will be removed. – Sheepfold