In short
Automating hreflang and canonical tests means having a machine check, every day and after every deployment, that each page in each language declares a canonical pointing to itself and lists all its versions with valid codes and absolute URLs, and that each of those versions returns a 200, is indexable and links back. An error makes the check fail and alerts the team. Once this is in place, a regression introduced by a template, a plugin or a migration shows up within hours, not at the next audit.
Why it matters
hreflang annotations break silently. A plugin update changes the URL format, a new template forgets the self-referencing tag, an unpublished translation leaves links to a 404 page, a canonical copied from the French version points to it from the German version. The site displays normally; only search engines see the problem.
Google's rules are strict. Each version must list itself and all the others; if two pages do not point to each other, the annotations are ignored; URLs must be absolute, including the protocol; only ISO 639-1 language codes and ISO 3166-1 alpha-2 region codes are supported. A canonical pointing to another language is even more serious: it asks for the translation not to be indexed. See align hreflang and canonical (opens in a new tab).
Search Console has no dedicated report for hreflang errors. Without an automated test, these errors are discovered through a drop in traffic for a language, weeks later.
What it improves
- Indexing of every version No translation excluded by a wrong canonical.
- Targeting The right language version appears in the results of each country.
- Detection time for regressions: hours instead of weeks.
- Peace of mind when deploying The check runs before or right after each release.
- Generative engines Indirect and undocumented effect; correctly indexed versions are sources available in each language.
How to check
Run the script from the next section on a sample:
python3 controle_hreflang.py https://example.com/sitemap.xml --sample 50
Compliant result: the last line reports zero problems and the exit code is 0. Then check that a check actually runs on a schedule: last run less than 24 hours ago, and an alert received during a deliberate test (a self-referencing tag removed on staging, for example).
How to implement
Before you start
The checks to automate, in order of severity:
| Check | Severity | Rule |
|---|---|---|
| Sitemap page returns 200 | Blocking | Every listed URL returns 200, with no redirect |
| Single, self-referencing canonical | Blocking | A single tag, pointing to the URL itself |
| Canonical to another language | Blocking | Never |
| Self-referencing annotation | Blocking | The page appears in its own hreflang list |
| Targets return 200, indexable, canonical | Blocking | Each declared URL returns 200, without noindex, with its own canonical |
| Reciprocity | Blocking | Each target lists the page in return |
| Absolute URLs | Blocking | https://…, never /de/… |
| Valid codes | Blocking | de, de-AT, zh-Hant, x-default; never en-UK (the country code is GB) |
| Code declared twice for two URLs | Blocking | A single URL per code |
Test the sitemap URLs: they are the ones you ask search engines to index. On a large site, a random sample of a few hundred URLs per run is enough to spot a template regression, which affects every page of the same type.
The check script
This Python script, with no external dependencies, reads the sitemap (or sitemap index), applies every check in the table and exits with an error if it finds a problem. It does not follow redirects: a redirect is reported as such.
#!/usr/bin/env python3
"""hreflang and canonical check on the URLs of a sitemap."""
import argparse
import random
import re
import sys
import time
import urllib.error
import urllib.request
import xml.etree.ElementTree as ET
from html.parser import HTMLParser
from urllib.parse import urljoin
SITEMAP_NS = "{http://www.sitemaps.org/schemas/sitemap/0.9}"
CODE = re.compile(r"^(x-default|[a-z]{2}(-[a-z]{4})?(-[a-z]{2})?)$", re.IGNORECASE)
USER_AGENT = "controle-hreflang/1.0"
PAGES = {}
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None
OPENER = urllib.request.build_opener(NoRedirect)
class HeadParser(HTMLParser):
def __init__(self):
super().__init__()
self.canonicals = []
self.alternates = []
self.robots = ""
def handle_starttag(self, tag, attrs):
attributes = {name: value or "" for name, value in attrs}
rel = attributes.get("rel", "").lower().split()
if tag == "link" and "canonical" in rel:
self.canonicals.append(attributes.get("href", ""))
if tag == "link" and "alternate" in rel and attributes.get("hreflang"):
self.alternates.append((attributes["hreflang"], attributes.get("href", "")))
if tag == "meta" and attributes.get("name", "").lower() in ("robots", "googlebot"):
self.robots += " " + attributes.get("content", "").lower()
def read_sitemap(url):
request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
with urllib.request.urlopen(request, timeout=30) as response:
root = ET.fromstring(response.read())
urls = []
for loc in root.iter(f"{SITEMAP_NS}loc"):
if root.tag == f"{SITEMAP_NS}sitemapindex":
urls += read_sitemap(loc.text.strip())
else:
urls.append(loc.text.strip())
return urls
def load(url, delay):
if url in PAGES:
return PAGES[url]
page = {"status": None, "canonicals": [], "alternates": [], "noindex": False}
request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
try:
with OPENER.open(request, timeout=30) as response:
parser = HeadParser()
parser.feed(response.read().decode(response.headers.get_content_charset() or "utf-8", errors="replace"))
robots = parser.robots + " " + " ".join(response.headers.get_all("X-Robots-Tag") or []).lower()
page.update(status=response.status, canonicals=parser.canonicals, alternates=parser.alternates, noindex="noindex" in robots)
except urllib.error.HTTPError as error:
page["status"] = error.code
except OSError as error:
page["status"] = str(error)
PAGES[url] = page
time.sleep(delay)
return page
def check(url, delay):
page = load(url, delay)
if page["status"] != 200:
return [f"status {page['status']}"]
problems = []
if page["noindex"]:
problems.append("noindex on a sitemap URL")
if len(page["canonicals"]) != 1:
problems.append(f"{len(page['canonicals'])} canonical tag(s) instead of one")
if not page["alternates"]:
return problems + ["no hreflang annotation"]
targets = {}
for code, href in page["alternates"]:
if not CODE.match(code):
problems.append(f"invalid hreflang code: {code}")
if code.lower().endswith("-uk"):
problems.append(f"{code}: the country code for the United Kingdom is GB")
if not href.startswith(("http://", "https://")):
problems.append(f"non-absolute URL for {code}: {href}")
absolute = urljoin(url, href)
if code.lower() in targets and targets[code.lower()] != absolute:
problems.append(f"{code} declared for two different URLs")
targets[code.lower()] = absolute
canonical = urljoin(url, page["canonicals"][0]) if page["canonicals"] else url
if canonical != url and canonical in targets.values():
problems.append(f"canonical to another language version: {canonical}")
elif canonical != url:
problems.append(f"canonical to another URL: {canonical}")
if url not in targets.values():
problems.append("no self-referencing annotation")
for code, target in targets.items():
if target == url:
continue
other = load(target, delay)
if other["status"] != 200:
problems.append(f"{code} -> {target}: status {other['status']}")
continue
if other["noindex"]:
problems.append(f"{code} -> {target}: noindex")
other_canonical = urljoin(target, other["canonicals"][0]) if other["canonicals"] else target
if other_canonical != target:
problems.append(f"{code} -> {target}: canonical to {other_canonical}")
if url not in {urljoin(target, href) for _, href in other["alternates"]}:
problems.append(f"{code} -> {target}: no return link")
return problems
arguments = argparse.ArgumentParser()
arguments.add_argument("sitemap")
arguments.add_argument("--sample", type=int, default=0, help="number of URLs picked at random (0 = all)")
arguments.add_argument("--delay", type=float, default=0.2, help="pause between two requests, in seconds")
options = arguments.parse_args()
urls = read_sitemap(options.sitemap)
if options.sample and options.sample < len(urls):
urls = random.sample(urls, options.sample)
errors = 0
for url in urls:
for problem in check(url, options.delay):
errors += 1
print(f"{url}\t{problem}")
print(f"{len(urls)} URLs checked, {errors} problem(s)", file=sys.stderr)
sys.exit(1 if errors else 0)
The script reads the initial HTML without executing JavaScript: if your tags are injected client-side, fix that first (see test SSR/SSG for all languages (opens in a new tab)). It does not check annotations declared in the sitemap or in HTTP headers; if you combine several methods, see check consistency across methods (opens in a new tab). Adjust --delay so as not to overload the server, and allow the controle-hreflang/1.0 user agent if a web application firewall blocks unknown bots.
GitHub Actions
Put the script in scripts/controle_hreflang.py and create .github/workflows/controle-hreflang.yml:
name: hreflang and canonical check
on:
schedule:
- cron: '30 5 * * *'
workflow_dispatch:
jobs:
hreflang:
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: '3.13'
- name: Check a sample of 300 URLs
run: python3 scripts/controle_hreflang.py https://example.com/sitemap.xml --sample 300 | tee resultats.tsv
- name: Keep the report
if: always()
uses: actions/upload-artifact@v7
with:
name: controle-hreflang
path: resultats.tsv
The check runs every day at 5:30 UTC and can be started manually (Actions > hreflang and canonical check > Run workflow). When it fails, GitHub notifies the user who last modified the cron line; to alert a team, add a conditional if: failure() step that posts to Slack or opens an issue (see notify the people responsible for translations (opens in a new tab)). For a check after every deployment, run the same script at the end of your deployment workflow, against staging and then production.
GitLab CI
In .gitlab-ci.yml:
controle-hreflang:
image: python:3.13-slim
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
- if: $CI_PIPELINE_SOURCE == "web"
script:
- python3 scripts/controle_hreflang.py https://example.com/sitemap.xml --sample 300 | tee resultats.tsv
artifacts:
when: always
paths:
- resultats.tsv
Create the schedule in Build > Pipeline schedules (the label in recent GitLab versions) with a daily cron expression. A failed pipeline sends notifications according to the project's notification settings.
Scheduled Screaming Frog
With a license, Screaming Frog can run scheduled crawls (File > Scheduling) or crawls from the command line, in headless mode, and export the tabs you choose. Tick Store Hreflang and Crawl Hreflang in Configuration > Spider > Crawl, then export the filters of the Hreflang tab (“Missing Return Links”, “Non-200 Hreflang URLs”, “Missing Self Reference”, “Incorrect Language & Region Codes”, “Not Using Canonical”) and of the Canonicals tab. The advantage over the script: JavaScript rendering and the analysis of every discovered URL, not just those in the sitemap. The exact command-line options are listed in the tool's user guide.
Laravel
Versions Laravel 11 to 13, Pest 3 and 4.
A feature test checks the template before deployment, on representative page clusters. Create tests/Feature/HreflangCanonicalTest.php:
<?php
/**
* @return array{
* canonical: string,
* alternates: array<string, string>
* }
*/
function headLinks(string $html): array
{
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML($html);
libxml_clear_errors();
$xpath = new DOMXPath($document);
$alternates = [];
foreach ($xpath->query('//link[@rel="alternate"][@hreflang]') as $link) {
$alternates[$link->getAttribute('hreflang')] = $link->getAttribute('href');
}
return [
'canonical' => $xpath->evaluate('string(//link[@rel="canonical"]/@href)'),
'alternates' => $alternates,
];
}
dataset('clusters', [
'home' => [['fr' => '/fr', 'de' => '/de', 'x-default' => '/fr']],
'guide' => [['fr' => '/fr/guides/temperature-infusion', 'de' => '/de/ratgeber/ziehtemperatur', 'x-default' => '/fr/guides/temperature-infusion']],
]);
it('declares a self canonical and a complete, reciprocal hreflang set', function (array $cluster): void {
$expected = array_map(fn (string $path): string => url($path), $cluster);
foreach (array_unique($cluster) as $path) {
$links = headLinks($this->get($path)->assertOk()->getContent());
expect($links['canonical'])->toBe(url($path));
expect($links['alternates'])->toEqual($expected);
}
})->with('clusters');
The test requires the annotations to use the same base URL as url(), set by APP_URL in the test environment. Run it with php artisan test --filter=HreflangCanonicalTest and add it to CI.
Next.js
Versions Next.js 15 and 16 (App Router), Playwright up to date as of November 2026.
A Playwright test, run against the preview of each deployment (BASE_URL provided by your platform), checks the tags produced by generateMetadata (alternates.canonical and alternates.languages). Create tests/hreflang.spec.ts:
import { expect, test } from '@playwright/test';
const clusters = [
['/fr', '/de', '/en'],
['/fr/guides/temperature-infusion', '/de/ratgeber/ziehtemperatur', '/en/guides/brewing-temperature'],
];
for (const cluster of clusters) {
test(`hreflang and canonical: ${cluster[0]}`, async ({ page, baseURL }) => {
const expected = cluster.map((path) => new URL(path, baseURL).toString());
for (const url of expected) {
const response = await page.goto(url);
expect(response?.status()).toBe(200);
const canonical = await page.locator('link[rel="canonical"]').getAttribute('href');
expect(canonical).toBe(url);
const alternates = await page
.locator('link[rel="alternate"][hreflang]')
.evaluateAll((links) => links.map((link) => link.getAttribute('href')));
expect(alternates).toEqual(expect.arrayContaining(expected));
}
});
}
Declare use: { baseURL: process.env.BASE_URL } in playwright.config.ts. If the page contains several canonical tags, getAttribute fails in strict mode: this is intentional. Run npx playwright test tests/hreflang.spec.ts.
Common mistakes
- Testing only the homepage: errors originate in the templates for product pages, articles and categories.
- Following redirects without reporting them: a redirected hreflang target is an error, not a success.
- Testing a staging site protected by a password or
noindexwith production rules: plan an exception for the test environment. - Checking the rendered DOM when bots read the initial HTML first: a tag injected by JavaScript can pass the test and still be missed by the search engine.
- A check that fails every day because of known errors: the team stops reading the alerts. Fix them or exclude them explicitly.
- Forgetting regional variants (
de-AT,fr-BE) in the test sets.
Frequently asked questions
How do you automatically test a site's hreflang tags?
Schedule a script that reads the sitemap, downloads each page and checks its annotations: presence of the page itself, valid language and region codes, absolute URLs, and for each target a 200 status, no noindex, a self-referencing canonical and a return link. Run it every day and after every deployment, in GitHub Actions, GitLab CI or a scheduled crawler, with an alert when it fails.
Does Search Console report hreflang errors?
No, Search Console has no dedicated report for hreflang errors. URL Inspection shows the canonical Google selected for a page, which helps spot a translation canonicalized to another language, but you need a crawler or a script to check reciprocity, codes and targets across the whole site. Google itself points to third-party hreflang testing tools.
What happens if an hreflang annotation has no return link?
Google states that if two pages do not point to each other, the hreflang annotations are ignored. The page remains indexable, but the search engine no longer knows that it is the equivalent of the other version, and may show a version in the wrong language or for the wrong country. It is often the symptom of an unpublished translation, a changed URL or an incomplete template.
Should you test every page or a sample?
On a small site, test every URL in the sitemap. On a large site, a random sample of a few hundred URLs per run is enough to spot a template regression, which affects every page of the same type. Add a full crawl at regular intervals, monthly for example, and template tests in CI, which block the error before it goes live.
Resources
- Google Search Central: localized versions of your pagesdevelopers.google.com
- GitHub Docs: schedule eventdocs.github.com
- GitLab: scheduled pipelinesdocs.gitlab.com
- Screaming Frog SEO Spider: user guidescreamingfrog.co.uk
- Pest: datasetspestphp.com
- Playwright: locatorsplaywright.dev
- Next.js: generateMetadata and alternatesnextjs.org
Updated on
Topic checklist (PDF)