Skip to content
JAVASCRIPT

How to Dynamically Set a Canonical Tag for Dynamic URLs in JavaScript

A
Author
Apr 3, 2023 · 8 min read
How to Dynamically Set a Canonical Tag for Dynamic URLs in JavaScript

In the world of modern web development, ensuring that your website is search-engine-friendly is paramount. One of the key elements in SEO (Search Engine Optimization) is the proper use of canonical tags. These tags help search engines understand the preferred version of a page, particularly when duplicate content exists or when URLs are dynamically generated.

In this blog post, we’ll dive deep into the concept of canonical tags, why they’re important, and how you can dynamically set a canonical tag for dynamic URLs using JavaScript.

What is a Canonical Tag?

A canonical tag (<link rel="canonical" href="URL" />) is an HTML element that specifies the preferred version of a webpage. This is particularly useful in situations where there are multiple URLs that display the same or similar content, which can confuse search engines and dilute your page’s ranking potential.

For example, if your website has a page that can be accessed via multiple URLs (e.g., www.example.com/product?id=123 and www.example.com/product/123), the search engine may see these as separate pages, leading to duplicate content issues. By using a canonical tag, you can tell search engines which version is the authoritative one.

The canonical tag looks something like this:

<link rel="canonical" href="https://www.example.com/product/123" />

This informs search engines that the page at www.example.com/product/123 is the preferred URL for indexing and ranking purposes.

Why is a Canonical Tag Important for SEO?

Canonical tags are essential for managing duplicate content and ensuring that search engines correctly index your web pages. Here are some key reasons why canonical tags are crucial:

1. Avoid Duplicate Content Issues

Duplicate content can arise when the same or similar content is available under multiple URLs. This can happen with parameters in URLs (like search filters, pagination, or session identifiers), or if your website allows different paths to the same resource. If search engines index these as separate pages, it could negatively affect your SEO rankings. The VPS hosting runs on premium hardware designed to provide customer-chosen configurations.

2. Consolidate Link Equity

If a webpage has links pointing to multiple URLs that contain the same or similar content, the link equity (or “link juice”) might be spread out across those URLs. This dilutes the potential ranking power of the page. The canonical tag allows you to consolidate link equity to a single URL, ensuring that all backlinks contribute to the same page.

3. Improve Crawl Efficiency

Search engines have a limited budget for crawling each site. By properly using canonical tags, you can help search engines focus on the most important versions of your pages, which enhances crawl efficiency.

4. Prevent Indexing of Low-Value Pages

Some pages (such as login pages, thank-you pages, or session-based pages) don’t add value to search engines and should not be indexed. By using canonical tags, you can prevent these pages from being indexed by specifying a preferred, valuable URL.

Setting Canonical Tags Dynamically

In web development, the challenge arises when your website generates URLs dynamically. This is especially common in single-page applications (SPAs), e-commerce websites, and content management systems (CMS) where URLs change based on user interaction, filters, or search queries.

For example, an e-commerce site might display a product page using a URL like:

https://www.example.com/product?id=123

However, a canonical version of this page might be:

https://www.example.com/product/123

To handle this scenario, the canonical tag must be dynamically updated based on the URL. This ensures that no matter what parameters are present in the URL, search engines will always index the correct version of the page.

How to Dynamically Set the Canonical Tag in JavaScript

You can dynamically set the canonical tag using JavaScript by modifying the <head> section of the page and adding the appropriate <link rel="canonical" /> tag. Here’s how you can do it:

<link rel="canonical" href="">

<script type='text/javascript'>
  var link = !!document.querySelector("link[rel='canonical']") ? document.querySelector("link[rel='canonical']") : document.createElement('link');
  link.setAttribute('rel', 'canonical');
  link.setAttribute('href', location.protocol + '//' + location.host + location.pathname);
  document.head.appendChild(link);
</script>

Explanation of the Code

  • document.querySelector("link[rel='canonical']"): This checks if the canonical tag already exists in the <head> section of the page. If it does, it selects the existing tag.
  • document.createElement('link'): If the canonical tag does not exist, this creates a new <link> element.
  • link.setAttribute('rel', 'canonical'): Sets the rel attribute of the link to canonical. This tells search engines that the URL specified is the preferred version.
  • link.setAttribute('href', location.protocol + '//' + location.host + location.pathname): Sets the href attribute to the current URL without any query parameters. The location.protocol, location.host, and location.pathname combine to create the URL of the current page, ensuring that the correct version of the page is set as canonical.
  • document.head.appendChild(link): Finally, the new or modified canonical link tag is appended to the <head> section of the document, allowing search engines to see the correct canonical URL.

Handling Dynamic URLs with Parameters

If your website uses dynamic URLs with query parameters (e.g., product?id=123), you can customize the canonical URL by stripping out unnecessary query parameters and only including the base path.

<script type='text/javascript'>
  var link = !!document.querySelector("link[rel='canonical']") ? document.querySelector("link[rel='canonical']") : document.createElement('link');
  link.setAttribute('rel', 'canonical');
  
  // Get the base URL without any query parameters
  var baseUrl = location.protocol + '//' + location.host + location.pathname;
  
  // If necessary, add logic to clean up or format the URL
  link.setAttribute('href', baseUrl);
  
  document.head.appendChild(link);
</script>

In this example, we’re using the location.pathname property, which gives us the part of the URL that comes after the domain name (i.e., the path). This ensures that we get the canonical URL without query parameters like ?id=123.

If your URLs include different query parameters (like ?sort=asc or ?page=2), you may want to modify the code to handle this by either stripping the parameters or selectively including them based on your SEO strategy.

Why Should You Use JavaScript for Dynamic Canonical Tags?

In some cases, you might wonder why JavaScript is necessary for setting the canonical tag. Let’s explore a few reasons why this method is beneficial:

  1. Dynamic Content and Single-Page Applications (SPAs) Websites that rely on JavaScript frameworks (like React, Angular, or Vue) often use dynamic content rendering. In these scenarios, the URL might change without a full page reload, making it difficult to update the canonical tag server-side. By using JavaScript, you can dynamically adjust the canonical tag in response to changes in the URL.
  2. User Interaction In many websites, user interactions such as applying filters or searching can alter the URL (e.g., ?filter=color&sort=price). JavaScript allows you to update the canonical tag whenever the URL changes, ensuring that the search engines always see the most accurate version of the page.
  3. Flexibility By using JavaScript, you have complete control over how the canonical tag is set. You can customize it based on specific URL structures, page content, or other factors, ensuring that it aligns perfectly with your SEO needs.
  4. Avoiding Server-Side Overhead Dynamically setting the canonical tag via JavaScript can save server resources. Instead of generating the correct canonical URL server-side for every page request, you can handle it client-side, reducing the load on the server and improving performance.

Best Practices for Setting Canonical Tags

While using JavaScript to set the canonical tag is powerful, there are a few best practices to ensure that you’re using it correctly:

  1. Ensure the Canonical Tag is Set Early The canonical tag should be set as early as possible in the page load process, ideally in the <head> section. This ensures that search engines can find and respect the canonical tag before they start indexing the page.
  2. Handle Edge Cases Consider edge cases where URLs might change but shouldn’t have a canonical tag applied. For example, pagination pages might need to point to the main product category page as the canonical version, rather than their individual URLs.
  3. Test Your Canonical Tags After implementing dynamic canonical tags, make sure to test them. You can use tools like Google Search Console’s “URL Inspection Tool” to verify that Google is recognizing the correct canonical version of your pages.
  4. Avoid Multiple Canonical Tags Make sure that only one canonical tag exists on each page. Multiple canonical tags pointing to different URLs can confuse search engines and result in indexing issues.

Conclusion

Setting a dynamic canonical tag is a crucial technique in modern web development, particularly for websites with dynamic URLs. By using JavaScript, you can ensure that search engines always have the correct URL for indexing and ranking, even when URLs change due to user interaction or dynamic content.

A
Author

Author at The Creative Coders.

The monthly build log

One email a month. New posts, lessons, and the occasional strong opinion. No spam.