Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access canonical URL in Next.js with Automatic Static Optimization turned on?

Tags:

next.js

I'm working on SEO component which needs a canonical URL.

How can I get URL of static page in Next.js with Automatic Static Optimization turned on?

like image 386
curious Avatar asked May 03 '20 12:05

curious


1 Answers

Building on fzembow's comment about useRouter().asPath and GorvGoyl's answer, here's an implementation which manages to handle both dynamic routes and excludes anchor and query param URL extensions:

import { useRouter } from "next/router";

const CANONICAL_DOMAIN = 'https://yoursite.com';

const router = useRouter();
const _pathSliceLength = Math.min.apply(Math, [
    router.asPath.indexOf('?') > 0 ? router.asPath.indexOf('?') : router.asPath.length,
    router.asPath.indexOf('#') > 0 ? router.asPath.indexOf('#') : router.asPath.length
]);
const canonicalURL= CANONICAL_DOMAIN + router.asPath.substring(0, _pathSliceLength);

<Head>
  <link rel="canonical" href={ canonicalURL } />
</Head>
like image 118
bsplosion Avatar answered Sep 23 '22 14:09

bsplosion