Performance: Canonical URLs
Canonical URLs affect page load speed by preventing duplicate content indexing and reducing unnecessary server requests for SEO, indirectly improving user experience.
import Head from 'next/head'; export default function Page() { const canonicalUrl = 'https://example.com/page'; return ( <> <Head> <link rel="canonical" href={canonicalUrl} /> </Head> <main>Page content</main> </> ); }
import Head from 'next/head'; export default function Page() { return ( <> <Head> <link rel="canonical" href={window.location.href} /> </Head> <main>Page content</main> </> ); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Dynamic canonical URL using window.location.href | Injects link tag after hydration | Triggers 1 reflow due to late insertion | Minimal paint cost but causes CLS | [X] Bad |
| Static canonical URL in Head component | Link tag present in initial HTML | No reflows triggered | No extra paint cost | [OK] Good |
<Head> component?<Head> in Next.js allows adding a <link rel="canonical"> tag for SEO purposes.<Head> component is used to add tags inside the HTML head.<link rel="canonical" href="URL" /> syntax.<head> tag?
import Head from 'next/head';
export default function Page() {
return (
<>
My Page
Content here
</>
);
}<title> and a <link rel="canonical"> with full URL.<Head> as HTML head children.import Head from 'next/head';
export default function Page() {
return (
);
}<Head> can contain <link> tags, and rel="canonical" is correct./blog/post1 and /blog/post1?ref=twitter. To avoid duplicate content issues, how should you add canonical URLs in both pages?Pass the test and this pattern moves unknown