next.jsmeta-tagsnext.js13

How to set canonical tag in Nextjs 13


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.


Solution

  • 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