Reputation: 8176
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.
Upvotes: 26
Views: 23629
Reputation: 5730
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
Upvotes: 33
Reputation: 1
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: "/",
},
Upvotes: 0
Reputation: 21
<Head>
<link rel="canonical" href="https://www.website.com/" />
</Head>
Upvotes: -5
Reputation: 8176
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.
Upvotes: 49