Help me implement hreflang for a multilingual headless site: locale mapping, canonicalization rules, sitemap strategy, non-HTML assets, QA automation, and rollout checkpoints.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The user wants a comprehensive guide and implementation plan for hreflang on a multilingual headless website.
The request covers specific areas:
Locale Mapping: How languages map to regions/content.
Canonicalization Rules: Handling rel="canonical" in a multilingual context.
Sitemap Strategy: How to generate sitemaps for hreflang.
Non-HTML Assets: Handling images/PDFs (though hreflang is mostly HTML/HTTP header focused, assets have nuances).
QA Automation: How to test this automatically.
Rollout Checkpoints: The step-by-step deployment plan.
Constraint Analysis & Approach:
Context: Headless CMS (e.g., Contentful, Strapi, Sanity) + Frontend Framework (e.g., Next.js, Nuxt, React). This means server-side rendering (SSR) or static site generation (SSG) is likely involved. The implementation details will vary slightly by tech stack, but the principles remain the same.
Complexity: hreflang is tricky. Common mistakes include missing return tags, wrong language codes, and conflicting canonical tags. I need to address these explicitly.
Tone: Technical, authoritative, structured, and actionable.
Drafting the Content - Section by Section:
1. Locale Mapping (The Foundation):
Need to define the difference between Language (en) and Locale (en-US, en-GB).
Strategy: x-default is crucial for international sites.
Structure: A matrix or JSON object representation.
2. Canonicalization Rules (The Gotcha):
Rule #1: Self-referencing canonicals are mandatory in most modern SEO strategies (Yandex/Google prefers it).
Rule #2: Canonicals should point to the current page's locale, not the root or another language.
Conflict: hreflang tells Google "these are alternatives." Canonical tells Google "this is the master." If hreflang points to A and B, but A canonicalizes to B, A is effectively deleted.
3. Sitemap Strategy (The Scalability):
Sitemaps are often easier to manage than HTML <head> tags in headless environments, though doing both is best practice.
Structure: One main index file or distinct sitemaps per language?
Content: xhtml:link tags are required here.
4. Non-HTML Assets (The Edge Case):
PDFs: Can use HTTP headers for Link: rel="alternate".
Images: hreflang doesn't apply to images directly. The page containing the image gets the tag.
5. Implementation in Headless (The "How-To"):
Where does logic live? Middleware? getServerSideProps?
Code snippets: I should provide a generic TypeScript/Next.js style example since Next.js is the dominant headless framework.
6. QA Automation (The Safety Net):
Tools: Screaming Frog is the manual standard, but automation implies CI/CD.
Scripting: Python (Requests/BeautifulSoup) or specialized SEO linting tools (like react-snap or custom scripts).
Checks: 200 status, return tags existence, language code validity.
7. Rollout Checkpoints (The Plan):
Dev -> Staging -> Production.
Incremental rollout vs. Big Bang.
Refining the Details:
Locale Mapping: Make sure to emphasize valid ISO codes (en-US vs en-us).
Canonicals: Emphasize that canonical must match the hreflang target for that specific page.
Sitemap: Explain the xmlns:xhtml namespace requirement.
Non-HTML: Be clear that PDFs are the main concern here.
Self-Correction during drafting:
Initial thought: Suggesting plugins.
Correction: It's a headless site. Plugins might not exist or be server-side. Better to suggest architectural patterns.
Initial thought: Focus heavily on HTTP headers for assets.
Correction: Keep it brief; the user is likely focused on the main site content.
Let's write it out.
Implementing hreflang in a headless architecture requires shifting the logic from the web server (like Apache/Nginx) to your application layer (Next.js, React, etc.) or your CDN edge logic.
Here is a comprehensive implementation guide covering locale mapping, canonicalization, sitemap strategies, and QA automation.
1. Locale Mapping Strategy
Before writing code, you must define your URL structure and locale hierarchy. In a headless CMS, content nodes usually have a unique ID but different localized fields.
A. URL Structure Selection
Choose one of two standard structures:
Subdirectories (Recommended for Domain Authority):example.com/en/, example.com/fr/
Subdomains:en.example.com, fr.example.com
Note: ccTLDs (example.fr) are harder to manage in headless setups due to cross-domain tracking and separate DNS configurations.
B. The Locale Object
Create a centralized configuration object in your codebase (not hardcoded in components) to map ISO codes to URL segments.
C. The "x-default" Rule
Google explicitly requires x-default to tell them which page to show when no other language match exists (e.g., a user in Brazil visiting a site with only EN/FR).
Action: Map x-default to your main "gateway" page (usually the English version or a language selector).
2. Canonicalization Rules
In a multilingual setup, canonical tags and hreflang tags work together to prevent duplicate content penalties (e.g., en-US vs en-GB).
The Golden Rules:
Self-Referencing Canonicals: Every page must have a canonical tag pointing to itself. Do not point en-GB canonical to en-US.
Mutual Recognition: If Page A links to Page B via hreflang, Page B must link back to Page A.
For headless sites, the sitemap should be generated dynamically via a serverless function or a build script that queries the CMS.
A. The Structure
Use a single sitemap index file that lists individual sitemaps per locale, or one massive sitemap with xhtml:link attributes embedded.
B. The "XHTML" Namespace
Your sitemap must define the XHTML namespace to validate.
C. Headless Edge Case: Content Gaps
If the French translation for "Product 1" does not exist in the CMS, do not output the French hreflang link in the sitemap. Pointing to a 404 or redirect in a sitemap is a critical error.
4. Non-HTML Assets (PDFs, Images)
Headless sites often serve documents (PDFs/Docx) that are also localized.
A. The Problemhreflang applies to HTML documents (text/html). It does not apply to application/pdf.
B. The Strategy
HTTP Headers (Preferred): Configure your CDN (Cloudflare, Vercel, AWS) to serve Link headers for binary files.
Content Negotiation: If you cannot change headers for PDFs, rely on the parent page. The HTML page embedding the PDF link should have the correct hreflangs. Google generally crawls the parent page to understand the context of the asset.
Sitemaps: You can include PDFs in sitemaps, but you cannot add hreflang attributes to them in the sitemap standard. Stick to standard <loc> tags for PDFs.
5. QA Automation
Do not rely on manual checking. Integrate hreflang validation into your CI/CD pipeline (GitHub Actions, Jenkins).
A. Automated Validation Script (Node.js Example)
Create a script that runs post-build or against the live URL.
javascript
const axios = require('axios');
const cheerio = require('cheerio');
const validIsoCodes = require('./config/i18n').locales.map(l => l.code);
async function validateHreflang(url) {
try {
const { data } = await axios.get(url);
const $ = cheerio.load(data);
const errors = [];
// 1. Check for Self-Canonical
const canonical = $('link[rel="canonical"]').attr('href');
if (canonical !== url) errors.push(`Canonical mismatch: ${canonical}`);
// 2. Check Hreflang presence
$('link[rel="alternate"][hreflang]').each((i, el) => {
const hreflang = $(el).attr('hreflang');
const href = $(el).attr('href');
// Check valid ISO code
if (!validIsoCodes.includes(hreflang) && hreflang !== 'x-default') {
errors.push(`Invalid hreflang code: ${hreflang}`);
}
// Check for http/https consistency
if (!href.startsWith('http')) {
errors.push(`Relative URL used in hreflang: ${href}`);
}
});
// 3. Check Reciprocal (Return Tag) - (Simplified logic)
// In a real scenario, you would fetch the 'href' URL and check if it links back.
return errors.length ? { url, status: 'FAIL', errors } : { url, status: 'PASS' };
} catch (err) {
return { url, status: 'ERROR', message: err.message };
}
}
B. Key QA Checks
Return Tags: If Page A says Page B is the French version, Page B must say Page A is the English version.
404 Checks: Ensure no hreflang points to a non-existent route.
Indexability: Ensure the pages linked in hreflang are not blocked by robots.txt or noindex tags.
6. Rollout Checkpoints
Do not enable this globally on day one.
Phase 1: The Pilot (Staging)
Scope: 1 locale pair (e.g., English and French).
Action: Implement logic in staging environment.
Test: Use Google Search Console (GSC) URL Inspection Tool on staging (if accessible) or local tools. Validate the HTML renders the <head> tags correctly.
Phase 2: Partial Production Rollout
Scope: Low-traffic sections (e.g., "About Us" or "Blog").
Action: Deploy to production.
Verification: Submit the specific sitemap via GSC. Wait 48 hours. Check the Page Indexing report for "Alternate page with proper canonical tag" warnings.
Phase 3: Full Deployment
Scope: Entire site.
Action: Roll out to product pages and homepage.
Monitor: Watch Core Web Vitals. Generating 20+ hreflang tags per page can increase HTML payload size slightly.
Summary Checklist
Component
Requirement
Tags
link rel="alternate" hreflang="x" present in <head>.
Canonical
Self-referencing (Points to the current URL).
Reciprocal
All links validated both ways (A->B implies B->A).
x-default
Present on every page, usually pointing to the global/en version.
Sitemaps
Includes xhtml:link attributes for all alternates.