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:
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user