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
+57
View File
@@ -0,0 +1,57 @@
'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 };
}