implement canonical URL handling with server and client-side support, add middleware for pathname access, and create hooks for dynamic canonical URL injection

This commit is contained in:
2025-10-08 10:26:22 +03:30
parent e6893846bd
commit 8de14fd3c0
5 changed files with 210 additions and 1 deletions
+36
View File
@@ -0,0 +1,36 @@
'use client';
import { useEffect } from 'react';
import { getCanonicalUrlClient } from '@/lib/getCanonicalUrl';
/**
* Client-side canonical URL handler
* Use this component in pages that need dynamic canonical URLs
* that can't be determined at build time or in generateMetadata
*/
export default function CanonicalHandler() {
useEffect(() => {
// Only run on client side
if (typeof window === 'undefined') return;
const canonicalUrl = getCanonicalUrlClient();
if (canonicalUrl) {
// Check if canonical link already exists
let canonicalLink = document.querySelector('link[rel="canonical"]');
if (canonicalLink) {
// Update existing canonical link
canonicalLink.href = canonicalUrl;
} else {
// Create new canonical link
canonicalLink = document.createElement('link');
canonicalLink.rel = 'canonical';
canonicalLink.href = canonicalUrl;
document.head.appendChild(canonicalLink);
}
}
}, []);
return null; // This component doesn't render anything
}