/**
* EDGE SEO REDIRECT FRAMEWORK
* Environment: Cloudflare Workers / Vercel Edge / Deno
*/
// --- 1. Types & Configuration ---
type GeoRouteRule = {
countries: string[]; // ISO 3166-1 Alpha-2 codes (e.g., "US", "GB")
pathPrefix: string; // e.g., "/us", "/eu"
};
type SEOConfig = {
canonicalDomain: string; // The primary SEO domain (e.g., "www.example.com")
defaultLanguage: string; // e.g., "en"
supportedLanguages: string[]; // e.g., ["en", "fr", "de"]
ignoreQueryParams: string[]; // Params to strip (e.g., "utm_source", "fbclid", "msclkid")
geoRules: GeoRouteRule[];
enableCaseNormalization: boolean;
};
const DEFAULT_CONFIG: SEOConfig = {
canonicalDomain: "www.example.com",
defaultLanguage: "en",
supportedLanguages: ["en", "fr", "de"],
ignoreQueryParams: ["utm_source", "utm_medium", "utm_campaign", "gclid", "fbclid"],
geoRules: [
{ countries: ["US", "CA"], pathPrefix: "/na" },
{ countries: ["DE", "FR"], pathPrefix: "/eu" },
],
enableCaseNormalization: true,
};
// --- 2. The Framework Class ---
export class EdgeSEORouter {
private config: SEOConfig;
constructor(config: Partial<SEOConfig> = {}) {
// Deep merge user config with defaults
this.config = { ...DEFAULT_CONFIG, ...config };
}
/**
* Main Entry Point
*/
public async handle(request: Request): Promise<Response> {
const url = new URL(request.url);
// 1. Guardrails: Check for infinite loops or Bot exclusion
if (this.isLoopDetected(request)) {
return this.next(request); // Break loop, proceed to origin
}
// 2. Hygiene & Canonicalization (301 Permanent Redirects)
const hygieneRedirect = this.checkHygiene(url);
if (hygieneRedirect) return hygieneRedirect;
// 3. Localization & Geo Logic (302 Temporary or 301 depending on strategy)
// Note: We use 302 for Geo to allow users to change preferences if they travel,
// but 301 for strict Language path enforcement if missing.
const routingRedirect = await this.checkRouting(request, url);
if (routingRedirect) return routingRedirect;
// 4. Metrics Injection (For downstream logging)
const modifiedRequest = this.injectMetrics(request);
// 5. Proceed to Origin
return this.next(modifiedRequest);
}
/**
* STEP 1: Hygiene & Canonical Normalization
* - Enforces HTTPS
* - Enforces Lowercase Path
* - Strips Tracking Params
* - Enforces Canonical Domain
*/
private checkHygiene(url: URL): Response | null {
let shouldRedirect = false;
const cleanUrl = new URL(url.toString());
// A. Domain Canonicalization
if (url.hostname !== this.config.canonicalDomain) {
cleanUrl.hostname = this.config.canonicalDomain;
shouldRedirect = true;
}
// B. Case Normalization (Path only)
if (this.config.enableCaseNormalization && url.pathname !== url.pathname.toLowerCase()) {
cleanUrl.pathname = url.pathname.toLowerCase();
shouldRedirect = true;
}
// C. UTM / Query Stripping
const params = url.searchParams;
let paramsChanged = false;
this.config.ignoreQueryParams.forEach((param) => {
if (params.has(param)) {
params.delete(param);
paramsChanged = true;
}
});
if (paramsChanged) {
cleanUrl.search = params.toString();
shouldRedirect = true;
}
if (shouldRedirect) {
return this.redirect(cleanUrl.toString(), 301, "Canonical Normalization");
}
return null;
}
/**
* STEP 2: Language & Geo Routing
*/
private async checkRouting(request: Request, url: URL): Promise<Response | null> {
// A. Do not geo-route bots (SEO best practice: serve the canonical content)
if (this.isCrawler(request)) {
return null;
}
// B. Extract Geo Data (Cloudflare Specific)
const country = (request as any).cf?.country || "US";
const langHeader = request.headers.get("Accept-Language") || "";
// C. Language Path Validation
// If URL is /about, and user is in France, should we send to /fr/about?
// Logic: Check if path already has a lang prefix.
const hasLangPrefix = this.config.supportedLanguages.some(lang =>
url.pathname.startsWith(`/${lang}/`) || url.pathname === `/${lang}`
);
if (hasLangPrefix) {
return null; // URL is already localized, proceed.
}
// D. Determine Target
let targetPrefix = "";
// Priority 1: Geo Rules (Storefront logic)
const geoRule = this.config.geoRules.find(r => r.countries.includes(country));
if (geoRule) {
targetPrefix = geoRule.pathPrefix;
} else {
// Priority 2: Accept-Language Header
// Very basic matching logic
if (langHeader.includes("fr")) targetPrefix = "/fr";
else if (langHeader.includes("de")) targetPrefix = "/de";
else targetPrefix = `/${this.config.defaultLanguage}`;
}
// E. Construct Redirect
// Only redirect if we determined a prefix is needed for the root/path
if (targetPrefix) {
const newUrl = new URL(url.toString());
// Prevent double slashes
newUrl.pathname = `${targetPrefix}${url.pathname}`.replace(/\/+/g, '/');
// We use 302 (Found) for Geo/IP routing because IP location changes,
// and we don't want Google to cache "All German users must go to /de"
// permanently if our logic changes.
return this.redirect(newUrl.toString(), 302, "Geo/Language Routing");
}
return null;
}
// --- Helpers ---
private redirect(location: string, code: 301 | 302, reason: string): Response {
// Metrics: We pass the reason in the headers for observability
return new Response(null, {
status: code,
headers: {
"Location": location,
"X-Edge-SEO-Action": reason,
"X-Edge-SEO-Destination": location
},
});
}
private next(request: Request): Response {
// In a real worker, this would be fetch(request)
// Here we simulate passing to origin
return new Response("Proceeding to origin", {
status: 200,
headers: { "X-Edge-SEO-Status": "Passed" }
});
}
private isLoopDetected(request: Request): boolean {
// If we just redirected here, stop.
return request.headers.get("X-Edge-SEO-Action") !== null;
}
private isCrawler(request: Request): boolean {
const ua = request.headers.get("User-Agent")?.toLowerCase() || "";
return ["googlebot", "bingbot", "slurp", "duckduckbot"].some(bot => ua.includes(bot));
}
private injectMetrics(request: Request): Request {
// Clone request to add headers for origin logging
const headers = new Headers(request.headers);
const cf = (request as any).cf;
if (cf) {
headers.set("X-Edge-Geo-Country", cf.country);
headers.set("X-Edge-Geo-City", cf.city);
}
return new Request(request.url, { ...request, headers });
}
}
// --- Usage Example ---
// This is what the fetch handler in a Worker looks like
export default {
async fetch(request: Request, env: any, ctx: any): Promise<Response> {
const router = new EdgeSEORouter({
canonicalDomain: "www.brand.com",
geoRules: [
{ countries: ["US"], pathPrefix: "/us" },
{ countries: ["GB"], pathPrefix: "/uk" },
]
});
return router.handle(request);
},
};