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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With