Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 266
funerr Avatar asked Sep 06 '25 11:09

funerr


2 Answers

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.

like image 104
funerr Avatar answered Sep 08 '25 11:09

funerr


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

like image 30
davidbonachera Avatar answered Sep 08 '25 12:09

davidbonachera