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
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.
https://www.firegolem.co
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
https://firegolem.co/blog
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 π