Complete the code to add a canonical link tag in a Next.js Head component.
import Head from 'next/head'; export default function Page() { return ( <Head> <link rel="canonical" href=[1] /> </Head> ); }
The href attribute in the link tag must be a string URL representing the canonical page address.
Complete the code to dynamically set the canonical URL using Next.js useRouter hook.
import Head from 'next/head'; import { useRouter } from 'next/router'; export default function Page() { const router = useRouter(); const canonicalUrl = (`https://example.com$[1]`).split('?')[0]; return ( <Head> <link rel="canonical" href={canonicalUrl} /> </Head> ); }
router.asPath gives the full path including query strings, so splitting at '?' removes queries for the canonical URL.
Fix the error in the canonical URL generation by choosing the correct method to get the current path in Next.js.
import Head from 'next/head'; import { useRouter } from 'next/router'; export default function Page() { const router = useRouter(); const canonicalUrl = `https://example.com$[1]`; return ( <Head> <link rel="canonical" href={canonicalUrl} /> </Head> ); }
router.asPath returns the actual path shown in the browser, including dynamic segments and query strings, which is best for canonical URLs.
Fill both blanks to create a canonical URL that removes query parameters and hash fragments.
import Head from 'next/head'; import { useRouter } from 'next/router'; export default function Page() { const router = useRouter(); const cleanPath = router.asPath.split([1])[0].split([2])[0]; const canonicalUrl = `https://example.com${cleanPath}`; return ( <Head> <link rel="canonical" href={canonicalUrl} /> </Head> ); }
/ which breaks the path& which is part of query, not separatorSplitting first by "?" removes query parameters, then splitting by "#" removes hash fragments from the URL path.
Fill all three blanks to create a Next.js component that sets a canonical URL using useRouter and cleans query and hash.
import Head from 'next/head'; import { useRouter } from 'next/router'; export default function Canonical() { const router = useRouter(); const path = router.[1]; const cleanPath = path.split([2])[0].split([3])[0]; const canonicalUrl = `https://example.com${cleanPath}`; return ( <Head> <link rel="canonical" href={canonicalUrl} /> </Head> ); }
Use router.asPath to get the full path, then split by "?" and "#" to remove query and hash parts for the canonical URL.