Build a SPA SEO adapter: router prefetch, head manager, canonical updates, and hydration…
- User
Build a SPA SEO adapter: router prefetch, head manager, canonical updates, and hydration guards.
Assistant
Build a SPA SEO adapter: router prefetch, head manager, canonical updates, and hydration guards.
The user wants to build a Single Page Application (SPA) SEO Adapter. This adapter needs to handle four specific things:
<title>, <meta> tags, etc., dynamically.rel="canonical" link is set.This is a system design and implementation task. I need to provide a conceptual architecture and a concrete code implementation (likely in TypeScript/JavaScript, framework-agnostic or using a lightweight helper approach, but usually React is the standard mental model for "hydration", so I'll stick to a React-like implementation but keep the logic modular).
Key Components:
Router Prefetch:
IntersectionObserver on links is the standard modern way (like Next.js).Head Manager:
<head>.Canonical Updates:
Hydration Guards:
Architecture Plan:
SeoAdapter (Singleton or Context).document.head.Step-by-Step Implementation Idea:
<head>.history that triggers head updates.IntersectionObserver to fetch data for visible links.Refining "Hydration Guards": Usually, this means preventing Google from seeing an empty page while JS loads.
data-html attributes to verify content presence, or simply a "Hydration Boundary" that waits for specific preloaded state before rendering the interactive island.Let's write the code. I'll use TypeScript. I'll make it framework-agnostic where possible, but maybe provide a React "glue" example since "hydration" is a very React/Vue term.
Detailed Specs:
Head Manager:
updateHead({ title, meta: [], links: [] })name="description") to remove old tags before adding new ones.Prefetcher:
queue(url)requestIdleCallback or setTimeout logic.Map.Canonical:
<link rel="canonical">.Hydration Guard:
window.__INITIAL_STATE__.Drafting the Response Structure:
Self-Correction/Refinement during thought process:
document.title is easy, but managing meta tags dynamically without duplication is tricky.data-meta="managed") to identify tags we control, so we can clear them before updating.fetcher function as a config option.Let's build a cohesive class SEOAdapter.
Module Structure:
HeadManager.tsPrefetcher.tsRouter.tsHydrationGuard.tsI will implement this as a cohesive TypeScript library structure.
Canonical URL logic: Must be absolute. window.location.origin + path.
Hydration Guard specific: I'll implement a "Render Gate". The app doesn't hydrate until the SEO requirements (data) are met.
Let's go.
Building a robust SEO adapter for a Single Page Application (SPA) involves synchronizing the browser's History API, the DOM's <head>, and the application's data loading state.
Below is a modular, framework-agnostic implementation in TypeScript (easily portable to JavaScript) that covers the Router, Head Manager, Prefetcher, and Hydration Guards.
<head> efficiently, managing titles, meta tags, and canonicals.IntersectionObserver to warm up the cache for links visible in the viewport.This module handles DOM mutations. It ensures we don't create duplicate meta tags and handles complex tasks like resetting the document title.
// HeadManager.ts
type MetaTag = { name?: string; property?: string; content: string };
export class HeadManager {
private readonly defaultTitle: string;
constructor(defaultTitle: string = 'My App') {
this.defaultTitle = defaultTitle;
}
/**
* Updates the page head based on route metadata
*/
public update(options: {
title?: string;
description?: string;
canonical?: string;
meta?: MetaTag[];
}) {
this.setTitle(options.title);
this.setCanonical(options.canonical);
this.setMetaTags(options.meta, options.description);
}
private setTitle(title?: string) {
document.title = title ? `${title} | ${this.defaultTitle}` : this.defaultTitle;
}
private setCanonical(url?: string) {
let linkEl = document.querySelector("link[rel='canonical']") as HTMLLinkElement;
if (!url) {
// Remove canonical if not provided
if (linkEl) linkEl.remove();
return;
}
if (!linkEl) {
linkEl = document.createElement('link');
linkEl.rel = 'canonical';
document.head.appendChild(linkEl);
}
linkEl.href = url;
}
private setMetaTags(tags?: MetaTag[], description?: string) {
// Handle specific description tag separately for convenience
if (description) {
this.updateTag('name', 'description', description);
}
// Handle generic meta tags
if (tags) {
tags.forEach(tag => {
const key = tag.name ? 'name' : 'property';
const value = tag.name || tag.property;
if (value) this.updateTag(key, value, tag.content);
});
}
}
private updateTag(keyAttr: string, keyValue: string, content: string) {
let el = document.querySelector(`meta[${keyAttr}="${keyValue}"]`);
if (!el) {
el = document.createElement('meta');
el.setAttribute(keyAttr, keyValue);
document.head.appendChild(el);
}
el.setAttribute('content', content);
}
}
This is the orchestrator. It intercepts navigation, fetches JSON data (simulating an API call), and ensures the UI only updates when the data is ready (hydration safety).
// SEOAdapter.ts
export type RouteMeta = {
path: string;
title: string;
description?: string;
getCanonical?: (params: Record<string, string>) => string;
// Simulate data fetching
loader?: (params: Record<string, string>) => Promise<any>;
};
export class SEOAdapter {
private headManager: HeadManager;
private routes: Map<string, RouteMeta>;
private cache: Map<string, any> = new Map();
constructor(routes: RouteMeta[], headManager: HeadManager) {
this.headManager = headManager;
this.routes = new Map(routes.map(r => [r.path, r]));
this.setupInterception();
}
/**
* Intercepts <a> clicks to handle SPA navigation
*/
private setupInterception() {
document.addEventListener('click', (e) => {
const target = (e.target as HTMLElement).closest('a');
if (!target) return;
// Only intercept internal links
if (target.origin === window.location.origin) {
e.preventDefault();
this.navigate(target.pathname);
}
});
}
/**
* Main Navigation Logic
*/
public async navigate(url: string, pushState: boolean = true) {
const route = this.matchRoute(url);
if (!route) {
window.location.href = url; // Fallback for non-SPA routes
return;
}
// 1. Hydration Guard: Check if data is ready
if (route.loader && !this.cache.has(url)) {
this.showLoadingBar(true); // Indicate loading
try {
const params = {}; // Logic to extract :id etc. from url would go here
const data = await route.loader(params);
this.cache.set(url, data);
} catch (err) {
console.error('Failed to load route data', err);
return; // Stop navigation
} finally {
this.showLoadingBar(false);
}
}
// 2. Update History
if (pushState) {
window.history.pushState({}, '', url);
}
// 3. Update SEO Head
this.headManager.update({
title: route.title,
description: route.description,
canonical: route.getCanonical ? route.getCanonical({}) : url,
});
// 4. Trigger Render (Conceptual)
// In a real app, this would update a framework state (React/Vue state)
console.log(`[Render] Rendering content for ${url}`);
}
private matchRoute(url: string): RouteMeta | undefined {
// Simple matcher. In prod, use 'path-to-regexp' or similar
return this.routes.get(url) || Array.from(this.routes.values()).find(r => r.path === '*');
}
private showLoadingBar(show: boolean) {
// Hook into a visual loading indicator to prevent UI jank
console.log(show ? 'Loading...' : 'Done');
}
/**
* Exposed for Prefetcher
*/
public async warmCache(url: string) {
const route = this.matchRoute(url);
if (route && route.loader && !this.cache.has(url)) {
const data = await route.loader({});
this.cache.set(url, data);
}
}
}
Google penalizes slow content. We use an IntersectionObserver to detect when links enter the viewport and fetch their data before the user clicks.
// Prefetcher.ts
export class Prefetcher {
private adapter: SEOAdapter;
constructor(adapter: SEOAdapter) {
this.adapter = adapter;
this.observeLinks();
}
private observeLinks() {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const link = entry.target as HTMLAnchorElement;
// Only prefetch same-origin
if (link.origin === window.location.origin) {
// Use requestIdleCallback to avoid impacting main thread
if ('requestIdleCallback' in window) {
(window as any).requestIdleCallback(() => {
this.adapter.warmCache(link.pathname);
});
} else {
setTimeout(() => this.adapter.warmCache(link.pathname), 200);
}
}
observer.unobserve(link); // No need to watch anymore
}
});
}, { rootMargin: '200px' }); // Start loading 200px before visible
// Watch all links
document.querySelectorAll('a').forEach(link => observer.observe(link));
// Re-observe on DOM changes (MutationObserver)
new MutationObserver((mutations) => {
mutations.forEach(m => {
m.addedNodes.forEach(node => {
if (node.nodeName === 'A') observer.observe(node as Element);
if ((node as Element).querySelectorAll) {
(node as Element).querySelectorAll('a').forEach(l => observer.observe(l));
}
});
});
}).observe(document.body, { childList: true, subtree: true });
}
}
This component prevents the "Empty Content" SEO issue. If a user lands directly on a deep link, the SPA must wait for data before rendering meaningful HTML.
This logic is integrated into the SEOAdapter logic above, but here is the explicit "Render Gate" logic you would use in your view layer.
// HydrationGuard.ts (Conceptual View Logic)
export class HydrationGuard {
private appRoot: HTMLElement;
constructor(appRootId: string) {
this.appRoot = document.getElementById(appRootId)!;
this.handleInitialLoad();
}
/**
* Handles the initial page load (Direct access or Refresh)
*/
private async handleInitialLoad() {
// 1. Check if Server Side Rendering (SSR) already populated data
// Often looks for window.__INITIAL_STATE__
const isPreHydrated = !!(window as any).__INITIAL_STATE__;
if (isPreHydrated) {
console.log('[Hydration] SSR content detected. Hydrating...');
// Trigger framework hydration (e.g., ReactDOM.hydrate)
return;
}
// 2. No SSR? We must fetch data BEFORE rendering to ensure SEO bots see content.
// NOTE: Ideally, this logic sits inside the Router's 'navigate' function called on init.
// But conceptually, the guard prevents "White Screen" or "Empty Shell".
// Example Flow:
// 1. Read current URL
// 2. Fetch Data
// 3. Render App
console.log('[Hydration] No SSR. Waiting for client data fetch...');
}
}
Here is how you wire it all together in your application entry point (main.ts).
import { HeadManager, SEOAdapter, RouteMeta, Prefetcher } from './seo';
// 1. Define Routes
const routes: RouteMeta[] = [
{
path: '/',
title: 'Home',
description: 'Welcome to our SPA',
loader: async () => {
console.log('Fetching Home Data...');
return { featured: [] };
}
},
{
path: '/about',
title: 'About Us',
description: 'Learn more about our team',
getCanonical: () => 'https://mysite.com/about',
loader: async () => ({ team: [] })
}
];
// 2. Initialize Managers
const headManager = new HeadManager('MyAwesomeSPA');
const router = new SEOAdapter(routes, headManager);
const prefetcher = new Prefetcher(router);
// 3. Boot Application
document.addEventListener('DOMContentLoaded', () => {
// Handle initial route load
router.navigate(window.location.pathname, false);
// Handle Browser Back/Forward buttons
window.addEventListener('popstate', () => {
router.navigate(window.location.pathname, false);
});
});
HeadManager explicitly handles <link rel="canonical">. This prevents duplicate content penalties if your content is accessible via multiple URLs (e.g., query parameters).SEOAdapter ensures that the loader (data fetch) completes before updating the history state or finalizing the view. This ensures that if a search engine snapshots the page, the data is present.Prefetcher uses requestIdleCallback and IntersectionObserver. This ensures that prefetching SEO data never blocks the main thread or the user's interaction with the current page.