← Back to Journal
· 5 min read

One Default Value Sent 124 hreflang Tags to My Homepage

A single fallback argument in a layout component made every English and Chinese page claim its alternate version was the homepage. Google reported 124 errors. Here is the audit script that catches it, and the rule that prevents it.

TL;DR

TL;DR hreflang bugs are rarely translation problems. They are plumbing problems: a default parameter, a missing page, a template that renders alternates from the wrong variable. On a bilingual site I run, a fallback alt = "/" in the layout meant every page output hreflang="en" href="/" and hreflang="zh" href="/", so all 124 pages described the homepage as their own alternate. Search Console called them reciprocal and self-reference errors; the fix was five lines. The audit below is 90 lines of stdlib Python and checks the four things that actually break: self-reference, reciprocity, x-default, and two languages pointing at the same URL.

A default argument is a quiet thing. It sits in a component signature, fires only when a caller forgets to pass a value, and does exactly what it says. Mine said the alternate URL was /.

On a bilingual site I run, every page renders a small block of alternate links:

<link rel="alternate" hreflang="en" href="/posts/some-slug/" />
<link rel="alternate" hreflang="zh" href="/zh/posts/some-slug/" />

The href came from a computed variable. That variable came from a layout prop. When a page did not pass it, the prop defaulted to /. Most pages did pass it. The ones that did not still rendered the block, with the homepage as the alternate. Then, because the fallback was applied before the language logic, both language tags inherited it.

Result: 124 pages telling Google that their English version was the homepage, their Chinese version was also the homepage, and by the way the homepage is its own alternate for every language on the site.

Search Console reported 124 errors split across self-reference and reciprocity. The site’s health score, which I had been treating as mostly noise, dropped from 99 to 54. That number was not noise. It was a template saying something false at scale.

Why hreflang breaks this way

The specification is simple. Each language version of a page must list all versions, including itself, and each listed URL must list back. Google’s documentation states the three requirements plainly: the set must be complete, each page must reference itself, and the references must be reciprocal (Google Search Central).

That is a graph problem, not a translation problem. A cluster is valid only if every node points to every other node, including itself. Any template that generates the edges from local data will be correct only if the local data is correct for every page. One fallback value that is wrong for one page is wrong for every page that uses it.

There are four ways this fails in practice:

  1. Missing self-reference. The template emits alternates for the other language only, forgetting the page’s own tag.
  2. Broken reciprocity. English lists Chinese, but Chinese does not list English, usually because the two templates were written at different times.
  3. Fallback to the homepage. The bug above. A missing translation silently points at /, which is never the alternate of a specific article.
  4. hreflang pointing at a non-canonical URL. The tag says /posts/x/ but the page canonicals to /posts/x/?ref=... or to a category page. The annotation and the canonical disagree, so the signal is dropped.

None of these produce a visible error for a reader. The page looks fine, the content is fine, the language switcher works. The only symptom is a Search Console report and, eventually, the wrong page ranking in the wrong market.

The rule that prevents it

The fix is smaller than the bug. Do not compute the alternate from a fallback. Compute it from the page’s own identity, and emit nothing when the counterpart does not exist.

Concretely:

  • Pass the current language and the current path to the layout as required arguments, not optional defaults.
  • Derive the alternate path by transformation, not by lookup: for a two-language site, /posts/x/ maps to /zh/posts/x/ and back. No table, no fallback.
  • Before rendering, check that the counterpart page exists in the content collection. If it does not, render no hreflang block at all, and hide the language switcher, rather than pointing at a default.
  • Assert in the build that every rendered cluster is reciprocal. A build-time check is worth more than a crawl you run next month.

On my site, that meant four changes: required props, path transformation instead of a map, an existence check against the collection, and a x-default that points at whichever version actually exists.

Five lines of real logic. The interesting part is not the fix, it is that the site had been “audited” twice before while carrying the bug, because both audits checked whether hreflang tags existed, not whether they described a valid graph.

The 90-line audit

This script fetches a sitemap, extracts every hreflang annotation from every page, and checks the four conditions that matter. It uses only the standard library, so it runs anywhere Python runs, including a CI job.

#!/usr/bin/env python3
"""Audit hreflang clusters: self-reference, reciprocity, x-default, sample coverage."""
import re
import sys
import time
import urllib.request
from collections import defaultdict
from urllib.parse import urljoin, urlparse

UA = {"User-Agent": "Mozilla/5.0 (compatible; hreflang-audit/1.0)"}
LINK_RE = re.compile(r"<link\b[^>]*>", re.I)
ATTR_RE = re.compile(r'(\w[\w:-]*)\s*=\s*["\']([^"\']*)["\']')

def fetch(url, timeout=20):
    req = urllib.request.Request(url, headers=UA)
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return r.read().decode("utf-8", "replace")

def sitemap_urls(sitemap, limit=300):
    xml = fetch(sitemap)
    urls = re.findall(r"<loc>\s*([^<\s]+)\s*</loc>", xml)
    if sitemap.endswith((".xml", ".xml.gz")) and any(
        u.endswith(".xml") for u in urls
    ) and "<sitemapindex" in xml:
        out = []
        for child in urls:
            if child.endswith(".xml"):
                out.extend(re.findall(r"<loc>\s*([^<\s]+)\s*</loc>", fetch(child)))
        urls = out
    return urls[:limit]

def hreflang_map(html, base):
    """Return {lang: canonicalised absolute url} for one page."""
    found = {}
    for tag in LINK_RE.findall(html):
        attrs = dict(ATTR_RE.findall(tag))
        if attrs.get("rel", "").lower() != "alternate":
            continue
        lang = attrs.get("hreflang", "").strip().lower()
        href = attrs.get("href", "").strip()
        if lang and href:
            found[lang] = urljoin(base, href).split("#")[0]
    return found

def main(sitemap, limit=300, delay=0.3):
    pages = sitemap_urls(sitemap, limit)
    clusters = {}
    print(f"pages to check: {len(pages)}")

    for url in pages:
        try:
            html = fetch(url)
        except Exception as e:
            print(f"FETCH_FAIL {url} {e}")
            continue
        clusters[url] = hreflang_map(html, url)
        time.sleep(delay)  # be polite

    issues = defaultdict(list)
    for url, links in clusters.items():
        if not links:
            issues["no_hreflang"].append(url)
            continue

        # 1. self-reference
        own = None
        for lang, target in links.items():
            if target.rstrip("/") == url.rstrip("/"):
                own = lang
        if own is None:
            issues["missing_self_reference"].append(url)

        # 2. x-default present
        if "x-default" not in links:
            issues["missing_x_default"].append(url)

        # 3. every target must list this page back
        for lang, target in links.items():
            if lang == "x-default":
                continue
            other = clusters.get(target)
            if other is None:
                issues["target_not_fetched"].append(f"{url} -> {target}")
                continue
            back = [u for u in other.values() if u.rstrip("/") == url.rstrip("/")]
            if not back:
                issues["broken_reciprocity"].append(f"{url} -> {target}")

        # 4. duplicates: two languages, same target
        seen = defaultdict(list)
        for lang, target in links.items():
            if lang != "x-default":
                seen[target].append(lang)
        for target, langs in seen.items():
            if len(langs) > 1:
                issues["duplicate_target"].append(f"{target}: {', '.join(langs)}")

    print("\n== results ==")
    ok = not any(issues.values())
    for key, rows in issues.items():
        print(f"\n{key}: {len(rows)}")
        for row in rows[:10]:
            print(f"  {row}")
        if len(rows) > 10:
            print(f"  ... and {len(rows) - 10} more")
    print("\nOK" if ok else "\nISSUES FOUND")
    return 0 if ok else 1

if __name__ == "__main__":
    if len(sys.argv) < 2:
        sys.exit("usage: hreflang_audit.py https://example.com/sitemap.xml [limit]")
    limit = int(sys.argv[2]) if len(sys.argv) > 2 else 300
    sys.exit(main(sys.argv[1], limit))

Two notes on using it. First, it fetches pages serially and sleeps between requests; on a 500-page site that is a few minutes, which is fine for a weekly check and rude to skip if you point it at someone else’s site. Second, target_not_fetched is not a bug by itself. It means the alternate lives outside the sitemap you gave the script, for example a subdomain or a language directory excluded from the sitemap, so those URLs never entered the cluster map.

What the output told me

On my site the first run produced 124 missing_self_reference and 124 broken_reciprocity rows, plus x-default on every page pointing at /. That last one was technically a valid URL and completely wrong semantically: every page claimed the homepage was the fallback for unmatched languages.

The fix took less time than writing the audit. The point of writing it down is that the bug survived two previous audits, a design review, and a rebuild, because none of them tested the graph. They tested for tags.

Checks like this belong in the build, not in a quarterly crawl. If the layout can emit a cluster, the build should assert the cluster is closed. That is cheaper than discovering you told Google 124 times that your homepage is the Chinese version of an article about commit graphs.

If you want the wider crawl-side checklist, the technical SEO audit guide covers what else to pull from a sitemap and a set of pages. hreflang is one chapter in that book, and it is the chapter most likely to be broken while looking finished.

Both checks are shipped as commands in the SEO CLI tool: one for the hreflang graph, one for everything else in the build.

FAQ

What is an hreflang self-reference error?
Every page in a language cluster must include an hreflang tag pointing to itself, with its own language code and its own URL. If the English page omits the en tag, or points the en tag at a different URL, Google reports a missing self-reference. It is a strong signal that the cluster is malformed, because the page is effectively saying 'the English version of me is somewhere else'.
What does reciprocity mean in hreflang?
If page A lists page B as its French alternate, page B must list page A as its English alternate. Links must go both ways. A one-way annotation is ignored, and if enough of them exist Google may ignore the entire cluster. Reciprocity is the single most common hreflang failure in sites assembled from templates.
Do hreflang tags need to match the canonical URL?
Yes. The URL in each hreflang tag should be the canonical, indexable version of that page. Pointing hreflang at a URL that canonicals elsewhere, or at a redirect, splits the signal and usually produces a 'no return tags' or 'different canonical' warning in Search Console.
Is x-default required?
Not required, but recommended. x-default marks the page served when no language matches the user, typically a language selector or the English version. A cluster without x-default still works, but you lose control over which page Google shows to unmatched users.
Can I just let the CMS generate hreflang tags?
You can, and it usually works until the day a page has no translation. At that point most CMS setups either omit the alternate (fine) or fall back to the homepage (not fine). The fallback is where clusters break, so the audit matters more than the generator.

Want to run this analysis on your own site?

ZensInk Pro automates this pipeline. One command, from seed keywords to content plan.

Get Pro →