Skip to content

Set Canonical URL in Next.js

Next.js/

To add a canonical URL in your Next.js application, you first need to get the current page route.

In short, to get current page route, use asPath property from useRouter hook.

It is important to clean up fragments (#) and query parameters (?param=1&abc=d) that asPath can include.

Get the cleaned up canonical URL by creating the following component.

import { useRouter } from 'next/router';

export default function CanonicalURL() {
  const siteUrl = 'https://www.your-website.com';
  const { asPath } = useRouter();
  const cleanPath = asPath.split('#')[0].split('?')[0];
  const canonicalUrl = `${siteUrl}` + (router.asPath === '/' ? '' : cleanPath);

  return (
    <link rel="canonical" href={canonicalUrl} />
  );
};

You can use ternary operator to check if asPath is returning the root page (/) and set the canonicalUrl to your base URL (siteUrl). Otherwise, append the cleaned up path of current page to the base URL.

Now it’s a matter of including this component inside <head> of any page you want.

You can update CanonicalURL component to insert the canonical URL into <head>. That can be done with Head component from next/head.

import Head from 'next/head';
import { useRouter } from 'next/router';

export default function CanonicalURL() {
  const siteUrl = 'https://www.your-website.com';
  const router = useRouter();
  const cleanPath = router.asPath.split('#')[0].split('?')[0];
  const canonicalUrl = `${siteUrl}` + (router.asPath === '/' ? '' : cleanPath);

  return (
    <Head>
      <link rel="canonical" href={canonicalUrl} />
    </Head>
  );
};

Now, import the component in any page where you want to set the canonical URL.

import CanonicalURL from 'src/components/CanonicalURL';

export default function Page() {
  return (
    <>
      <CanonicalURL />
      <h1>My page</h1>
    </>
  );
}

If you have a common component for SEO, like meta tags, you can set the canonical URL there instead.

import Head from 'next/head';
import CanonicalURL from 'src/components/CanonicalURL';

export default function SEO({ title, description }) {
  return (
    <Head>
      <title>{title}</title>
      <meta name="description" content={description} />
      {/* Other meta tags */}
      <CanonicalURL />
    </Head>
  );
}

export default SEO;