Adding Canonical URL in NextJS 🌐
Blog / Adding Canonical URL in NextJS 🌐
2 Minutes Read
By @akash_dathan

Adding Canonical URL in NextJS 🌐

Canonical url is really important for SEO, especially if you are publishing your content in multiple places. Google recommends that you add canonical link to all the pages .


There are three points to consider for canonical URL

  1. Unique Hostname
  2. Trim Trailing Slash
  3. Remove Query Params

Decide On a Unique Hostname

Firstly HOSTNAME has to be decided, you can have a hostname with both www and one without it. for example the following two urls points to the same site.

  1. https://www.firegolem.co
  2. https://firegolem.co

But google considers these urls as two different unique urls, so if you don’t have a canonical tag, your SEO rankings are going to plummet.


Trim the Trailing Slash (/)

Similar two hostname with www prefix, urls with tailing ’/’ is also considered as unique URLs. So the following URLs are considered two different URls

  1. https://firegolem.co/blog
  2. https://firegolem.co/blog/

Remove Query Params

Query params in your urls can also effect your SEO, you need to have the root url without the query params, so that Google knows that all the different urls with varying query params are in fact one unique URL.


Following is how you can add canonical url in NextJs

  • Add the following code to the _app.tsx file
import { useRouter } from 'next/router';
import Head from 'next/head';

// 1. Unique Hostname
const HOSTNAME = 'https://firegolem.co';

function MyApp({ Component, pageProps }) {
  const router = useRouter();
  
  // 2. Remove trailing slash
  const formattedPath = router.asPath.replace('/', '')
  
  // 3. Remove Query Params
  const canonicalUrl = (
    HOSTNAME + formattedPath
  ).split("?")[0];


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

export default MyApp;

That’s all folks, happy hacking πŸ™Œ