Dynamic Canonicals in SPAs
You'll learn how to manage canonical URLs in single-page applications where the URL changes without full page reloads.
The Challenge
In traditional multi-page applications, your server sends a complete HTML document with the canonical tag already in the <head> for every route. But in SPAs with client-side routing (like React Router or Vue Router), the initial HTML loads once, and JavaScript handles navigation by updating the URL and content without requesting new HTML from the server.
The problem? Search engine crawlers typically see only the initial HTML. If your canonical tag stays static while your routes change, you're telling search engines the wrong information about which URL represents each page.
The Solution
You must dynamically update the canonical tag whenever the route changes, just like you update the title and meta description. This typically happens in your routing logic or a dedicated SEO component.
Basic approach:
// React example - inside route component or effect
useEffect(() => {
let canonicalLink = document.querySelector('link[rel="canonical"]');
if (!canonicalLink) {
canonicalLink = document.createElement('link');
canonicalLink.setAttribute('rel', 'canonical');
document.head.appendChild(canonicalLink);
}
const canonicalUrl = `https://example.com${window.location.pathname}`;
canonicalLink.setAttribute('href', canonicalUrl);
}, []);
This finds or creates the canonical link element and updates its href to match the current page's full URL. Run this logic on every route change to keep canonicals synchronized with your content.
Key Takeaway: In SPAs, canonical tags must be programmatically updated on every route change to accurately reflect the current page's canonical URL, preventing search engines from indexing the wrong URL or treating different routes as duplicates.