57 lines
1.7 KiB
JavaScript
57 lines
1.7 KiB
JavaScript
'use client';
|
|
|
|
import { useEffect, useState } from 'react';
|
|
import { getCanonicalUrlClient } from '@/lib/getCanonicalUrl';
|
|
|
|
/**
|
|
* Custom hook to get canonical URL on client side
|
|
* Useful for client components that need to know the canonical URL
|
|
*/
|
|
export function useCanonicalUrl() {
|
|
const [canonicalUrl, setCanonicalUrl] = useState(null);
|
|
const [isLoaded, setIsLoaded] = useState(false);
|
|
|
|
useEffect(() => {
|
|
const canonical = getCanonicalUrlClient();
|
|
setCanonicalUrl(canonical);
|
|
setIsLoaded(true);
|
|
}, []);
|
|
|
|
return { canonicalUrl, isLoaded };
|
|
}
|
|
|
|
/**
|
|
* Hook to automatically inject canonical URL into document head
|
|
* Use this in client components where you need automatic canonical URL injection
|
|
*/
|
|
export function useCanonicalUrlInjection() {
|
|
const { canonicalUrl, isLoaded } = useCanonicalUrl();
|
|
|
|
useEffect(() => {
|
|
if (!isLoaded || !canonicalUrl) return;
|
|
|
|
// 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);
|
|
}
|
|
|
|
// Cleanup function
|
|
return () => {
|
|
const link = document.querySelector(`link[rel="canonical"][href="${canonicalUrl}"]`);
|
|
if (link) {
|
|
link.remove();
|
|
}
|
|
};
|
|
}, [canonicalUrl, isLoaded]);
|
|
|
|
return { canonicalUrl, isLoaded };
|
|
} |