Canonical URLs tell search engines which page is the main version when there are similar pages. This helps avoid confusion and improves SEO.
0
0
Canonical URLs in NextJS
Introduction
When you have multiple pages with similar content and want to point to the main one.
When your site supports different URLs for the same page, like with or without query parameters.
When you want to prevent duplicate content penalties from search engines.
When you share content on social media and want consistent links.
When you want to improve your website's search ranking by consolidating page authority.
Syntax
NextJS
import Head from 'next/head'; export default function Page() { return ( <> <Head> <link rel="canonical" href="https://example.com/page" /> </Head> <main> {/* Page content here */} </main> </> ); }
The <Head> component from Next.js lets you add elements to the HTML <head> section.
The rel="canonical" link tells search engines the preferred URL for the page.
Examples
Basic example setting the canonical URL for the homepage.
NextJS
import Head from 'next/head'; export default function Home() { return ( <> <Head> <link rel="canonical" href="https://mysite.com/" /> </Head> <h1>Welcome to my site</h1> </> ); }
Using a variable to set the canonical URL dynamically.
NextJS
import Head from 'next/head'; export default function BlogPost() { const canonicalUrl = 'https://mysite.com/blog/post-1'; return ( <> <Head> <link rel="canonical" href={canonicalUrl} /> </Head> <article>Blog post content here</article> </> ); }
Setting canonical URL for a product page to avoid duplicate URLs with filters or tracking parameters.
NextJS
import Head from 'next/head'; export default function ProductPage() { return ( <> <Head> <link rel="canonical" href="https://mysite.com/products/widget" /> </Head> <section>Product details here</section> </> ); }
Sample Program
This component sets a canonical URL for the About page to tell search engines this is the main URL for this content.
NextJS
import Head from 'next/head'; export default function About() { return ( <> <Head> <title>About Us - MySite</title> <link rel="canonical" href="https://mysite.com/about" /> </Head> <main> <h1>About Us</h1> <p>Learn more about our company and values.</p> </main> </> ); }
OutputSuccess
Important Notes
Always use absolute URLs (including https://) in canonical links.
Make sure the canonical URL matches the main content page exactly.
Using canonical URLs helps prevent SEO issues with duplicate content.
Summary
Canonical URLs tell search engines which page is the main one.
Use Next.js <Head> to add canonical links easily.
This improves SEO and avoids duplicate content problems.