Skip to content

Optional analytics, session recording and advertising stay off unless you accept. You can reject them and use Transglot. Change your choice anytime in Cookie preferences. Cookie Policy

Back to the blog
Best practices

Hreflang: The Complete Guide to Tags, Sitemaps, x-default (2026)

Hreflang rules from Google's documentation: tags, HTTP headers, sitemaps, valid codes, x-default, canonicals, a generator script and an audit script.

by transglot team
published November 24, 2026
28 min read

Documentation reviewed 24 November 2026.

Quick answer

hreflang is an annotation that tells a search engine which URLs are language or regional versions of the same page, so it can show each searcher the right one. It does not translate anything, it does not replace the canonical tag, and Google does not use it to detect a page's language. You can place it in the HTML head, in an HTTP Link header or in an XML sitemap, and Google treats the three as equivalent. The rules are short: every version lists itself and every other version, the links are returned, the URLs are fully qualified, and the codes are an ISO 639-1 language with an optional ISO 3166-1 Alpha 2 region. Add x-default for searchers whose language you do not serve.

Who this guide is for

This guide is for developers and SEO leads who have to add hreflang to a site, or fix one that reports errors. It covers the annotation only. For URL structure, language switchers and everything else on a multilingual site, see the website localization guide.

At the end you will have:

  • The rules, each traced to the search engine's own documentation.
  • A correct example of all three placements.
  • A script that generates head tags and a sitemap from one list of locales.
  • A script that crawls a list of URLs and reports hreflang errors.
  • A checklist to run before and after a release.

Part 1: what hreflang does and does not do

Google's documentation gives hreflang one job: when a page exists in several languages or regions, the annotation helps Google Search point users to the most appropriate version.

Google recommends it in three situations:

  • The content is fully translated, for example German and English versions of each page.
  • The content is in one language with small regional variations, for example English for the US, Great Britain and Ireland.
  • Only the template is translated, such as navigation and footer, while the main content stays in one language. Forums often work this way.

What it does not do, according to the same pages:

  • It does not detect language. Google states that it does not use hreflang or the HTML lang attribute to detect the language of a page. It uses algorithms on the visible content.
  • It does not replace rel="canonical". Canonical says which URL represents a set of duplicates. hreflang says which URLs are alternates of each other. See Part 6.
  • It is not documented as a way to rank higher. Google describes it as a way to choose which version to show. Its page on multi-regional sites says targeting a country can improve rankings in that country at the expense of results in other locales.
  • It is not required for indexing. Google says it might find alternate versions without help, and that it is usually best to indicate them explicitly.

One side effect is documented. In a 2023 post, Google wrote that URLs in hreflang annotations, including x-default, may be used for URL discovery and scheduled for crawling.

hreflang swaps the URL shown in a result for the version that fits the searcher. It is a statement about a group of pages, so it only works when every page in the group agrees.
In short

Part 2: the three placements

Google supports three methods and says they are equivalent from its perspective. It also says that using all three at once brings no benefit in Search and is harder to manage. Pick one per page type.

Each version of the page carries one <link> per version, itself included. The set is identical on every page in the group.

The head of the en-GB page. The other three pages carry the same five alternate lines and their own canonicalhtml
<head>
<title>Pricing</title>
<link rel="canonical" href="https://example.com/en-gb/pricing" />
<link rel="alternate" hreflang="en" href="https://example.com/pricing" />
<link rel="alternate" hreflang="en-GB" href="https://example.com/en-gb/pricing" />
<link rel="alternate" hreflang="de" href="https://example.com/de/pricing" />
<link rel="alternate" hreflang="zh-Hant" href="https://example.com/zh-hant/pricing" />
<link rel="alternate" hreflang="x-default" href="https://example.com/pricing" />
</head>

Two conditions from Google's page:

  • The tags must be inside a well-formed <head>. Google suggests pasting the rendered code into an HTML validator when in doubt.
  • Do not combine hreflang with other alternate attributes, such as media, in a single <link>.

Use this for files that have no head, such as PDFs. The response to a GET request for each version returns one Link header that lists every version, including the one requested. The header is identical for every version.

The response for both PDF files. Each URL sits between angle brackets, and entries are separated by commashttp
HTTP/1.1 200 OK
Content-Type: application/pdf
Link: <https://example.com/guide.pdf>; rel="alternate"; hreflang="en",
<https://example.com/de/guide.pdf>; rel="alternate"; hreflang="de",
<https://example.com/guide.pdf>; rel="alternate"; hreflang="x-default"

XML sitemap

Add the xhtml namespace, then give each URL its own <url> element with one <xhtml:link> child per version, itself included.

Two versions, two url entries, the same three children in eachxml
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xhtml="http://www.w3.org/1999/xhtml">
<url>
<loc>https://example.com/pricing</loc>
<xhtml:link rel="alternate" hreflang="en" href="https://example.com/pricing"/>
<xhtml:link rel="alternate" hreflang="de" href="https://example.com/de/pricing"/>
<xhtml:link rel="alternate" hreflang="x-default" href="https://example.com/pricing"/>
</url>
<url>
<loc>https://example.com/de/pricing</loc>
<xhtml:link rel="alternate" hreflang="en" href="https://example.com/pricing"/>
<xhtml:link rel="alternate" hreflang="de" href="https://example.com/de/pricing"/>
<xhtml:link rel="alternate" hreflang="x-default" href="https://example.com/pricing"/>
</url>
</urlset>

Google's sitemap rules for this method:

  • The order of the child elements does not matter.
  • Child elements do not count toward the sitemap URL limit. A single sitemap is still limited to 50,000 URLs or 50MB uncompressed.
  • A sitemap can only contain URLs that descend from the directory it is hosted in.

Which placement fits

SituationPlacement that fitsWhy
A few languages, templates you controlHTML headVisible in page source, easy to inspect and test
Many languages or many pagesXML sitemapKeeps the head small. One generated file holds every group
PDFs and other non-HTML filesHTTP Link headerThese files have no head
No access to templates or response headersXML sitemapNeeds only a file on the server
No sitemap and no control of headersHTML headGoogle names this case for the head method
Yandex matters to youHTML headYandex states it no longer reads language versions from sitemaps. See Part 11
Three cream paper-pulp objects on a dark stone plinth: an open page, a sealed envelope and a rolled map, each tied to the same small cluster of paper tags
Three placements, one set of annotations

Part 3: the rules

These apply to all three placements. Each one is from Google's page on localized versions.

  1. Each version lists itself and all other versions. The self reference is part of the set, not an extra.
  2. Links must be returned. If page X names page Y, page Y must name page X. Google states that when two pages do not both point to each other, the tags are ignored. Otherwise anyone could name their page as an alternate of yours.
  3. URLs are fully qualified, including the scheme. https://example.com/foo, not //example.com/foo and not /foo.
  4. Alternates do not need to be on the same domain. example.com and example.de can be one group.
  5. One URL, one language of content. Google recommends a different URL for each language version, and a single language for content and navigation on each page.

Two relaxations are documented:

  • You may annotate part of a site. Google's 2023 post says it is fine to have hreflang on only some pages.
  • You may leave some languages out on some pages. If a complete set is hard to maintain, Google still processes the pairs that do point to each other. It asks that new language pages are linked both ways with the original or dominant language first.
Generate the set once per group and print the same lines on every member. A set written by hand per page is where missing return links come from.
Rule

Part 4: language, region and script codes

The value is a language code, optionally followed by a region code, separated by a dash:

  • Language: ISO 639-1, two letters. de, en, fr.
  • Region, optional: ISO 3166-1 Alpha 2. en-GB, de-CH.
  • Script, optional: ISO 15924. zh-Hant, zh-Hans. A region can follow: zh-Hans-US.

Google states that only codes listed in those two standards are supported. The value is case-insensitive. Google notes that upper-case regions, as in en-GB, follow the ISO convention.

Codes people get wrong

WrittenProblemWrite instead
en-UKUK is not the assigned code. Google lists UK, EU and UN as codes that have no effecten-GB
es-419419 is not an ISO 3166-1 Alpha 2 code. Google names es-419 as unsupportedes for all Spanish speakers, or es-MX, es-AR and so on per country
GB, US, DE aloneA region cannot stand alone. The first code is always read as a languageen-GB, en-US, de-DE
be for Belgiumbe is the Belarusian languagenl-BE, fr-BE, de-BE
en-EUEU is a reserved code, so that part is ignoreden, or one entry per country
jp, engNot ISO 639-1 language codesja, en
en_USGoogle's format uses a dashen-US
zh-CN when you mean "Simplified Chinese anywhere"Valid, but it targets users in Chinazh-Hans

zh-CN and zh-Hans are both valid and mean different things. With zh-TW, Google derives the script from the country: Traditional Chinese for users in Taiwan. zh-Hant names the script and no country. Choose by audience.

Language only, or language and region

Your contentCode to use
One page for all speakers of a languageLanguage only: de
Pages that differ by country in the same languageLanguage and region for each: en-US, en-GB, en-AU, plus a catch-all en
A page for a language in a country where it is not the main oneLanguage and region: de-ES is German for users in Spain
A language selector or fallback pagex-default

Part 5: x-default

x-default is a reserved value. Google uses it when no other language or region in the set matches the searcher's browser setting. It needs no language code, because the language of that page is irrelevant to the match.

Google's documentation and its 2023 post describe three pages it can point to:

  • A language or country selector page. Google says the value was designed for these and works best with them.
  • The page you send users to when you have nothing for their region.
  • The version of the content you consider the default.

So x-default may share a URL with one of your language versions. In Google's own example, a page with English and Spanish versions and x-default on the English URL sends French-speaking users to the English page.

Google's example of x-default on a country selectorhtml
<link rel="alternate" hreflang="en-GB" href="https://example.com/en-gb" />
<link rel="alternate" hreflang="en-US" href="https://example.com/en-us" />
<link rel="alternate" hreflang="en-AU" href="https://example.com/en-au" />
<link rel="alternate" hreflang="x-default" href="https://example.com/country-selector" />

Google's wording is "consider adding" it. It is recommended, not required. Use it when:

  • The home page redirects or adapts by location or Accept-Language. Yandex documents the same use.
  • You serve some languages and want to choose where everyone else lands.
  • A page exists in one language only and other speakers should reach a selector.

Without it, Google picks a version for unmatched searchers itself.


Part 6: hreflang with canonical tags

The correct combination has three parts:

  1. Each language version names itself as canonical.
  2. Each version carries the full hreflang set.
  3. Every href in that set is the canonical URL of its page.
The German page is its own canonical and a member of the grouphtml
<!-- https://example.com/de/pricing -->
<link rel="canonical" href="https://example.com/de/pricing" />
<link rel="alternate" hreflang="en" href="https://example.com/pricing" />
<link rel="alternate" hreflang="de" href="https://example.com/de/pricing" />
<link rel="alternate" hreflang="x-default" href="https://example.com/pricing" />

What Google's canonical documentation says on the subject:

  • If you use hreflang, specify a canonical page in the same language, or the best possible substitute language if none exists.
  • Include a self-referencing rel="canonical" on the canonical page.
  • A rel="canonical" annotation that carries hreflang, lang, media or type attributes is not used for canonicalization. Keep the two as separate <link> elements.

The mistake: canonicalising every language to English

A translated page is not a duplicate of its source. Google states that localized versions are only considered duplicates if the main content remains untranslated. rel="canonical" is, in Google's words, a strong signal that the specified URL should become canonical. A German page whose canonical is the English URL asks Google to index the English page in its place, while its hreflang asks Google to show the German one. The two instructions contradict each other.

This mistake usually comes from a template, not a person: a layout that prints one hardcoded canonical, or an SEO plugin that builds the canonical from the default language's URL. Check one translated page per template.
Watch out

Part 7: pagination, parameters, noindex and redirects

Google's hreflang page does not mention these four cases. The rules below follow from its other pages and from how audit tools document the same errors.

Pagination

Google's pagination guidance says to give each page in a sequence its own canonical URL, and not to make the first page canonical for the rest. It follows that page 2 in English is the alternate of page 2 in German, not of page 1. Annotate each page of the sequence with its own set.

URL parameters

A sorted or filtered URL such as ?order=price is normally not the canonical URL. Google suggests keeping such variations out of the index with noindex or robots.txt. Put hreflang on the canonical URL and point it at canonical URLs, with no tracking parameters.

noindex pages

Google says that when it sees noindex on a page, it drops that page entirely from Search results. Such a page cannot be the version shown to anyone. Screaming Frog's documentation adds that noindex on a return link may result in the relationship being ignored. Leave noindex pages out of every set.

Redirects

A URL that returns a redirect has no head and no content of its own, so it cannot return a link. Google's redirect documentation says a permanent redirect signals that the target should be canonical. Point every href at the final URL that returns 200, and update the set whenever URLs move.

Target of an hreflang linkKeep it?
Returns 200, self-canonical, indexableYes
RedirectsNo. Use the final URL
Returns 404 or 5xxNo. Remove it or fix the page
noindexNo
Canonical points to another URLNo. Use the canonical URL
Blocked in robots.txtNo. Google cannot read its return link

Part 8: one language in several countries

Pages for en-US, en-GB and en-AU often share most of their text and differ in currency, spelling or shipping terms.

Three points from its documentation:

  • Add a catch-all. With several regional pages in one language, Google advises a generic version for that language too, for speakers elsewhere. The catch-all can be one of the regional pages.
  • A URL can therefore carry two values. If the US page is also your generic English page, list it under en-US and under en.
  • Subdomain or folder names are not read. Google states that the en-gb in a hostname is not used to determine the audience. You must map it explicitly.
The US page doubles as the generic English page and the fallbackhtml
<link rel="alternate" hreflang="en" href="https://example.com/" />
<link rel="alternate" hreflang="en-US" href="https://example.com/" />
<link rel="alternate" hreflang="en-GB" href="https://example.com/en-gb/" />
<link rel="alternate" hreflang="en-AU" href="https://example.com/en-au/" />
<link rel="alternate" hreflang="x-default" href="https://example.com/" />

Is this duplicate content?

Where similar same-language content sits on different URLs, Google's instruction is to pick a preferred version and use rel="canonical" and hreflang so the correct regional URL is served. Regional pages that are each their own canonical, with a complete set, are declared alternates.

hreflang does not make thin variations worth having. Bing's webmaster blog says localization creates duplicate content when regional or language pages are nearly identical, and advises meaningful differences such as terminology, examples, regulations or product details. If the pages differ in nothing a visitor would notice, one page with a language-only code is less to maintain.

A row of three nearly identical cream paper-pulp houses on a dark stone plinth, each with a different small paper flag, and a fourth plain house set slightly apart with a teal glass window
Regional versions and the catch-all

Part 9: generating hreflang at scale

Sets written by hand drift. Generate them from one list of locales and one list of paths.

A generator script

This script targets Node.js 22 or later and has no dependencies. It reads a config file and writes two outputs: the head tags for every page, and a sitemap with xhtml:link children. Use one output, not both.

hreflang.config.json. Remove the caption line before use, JSON has no commentsjson
{
"origin": "https://example.com",
"xDefault": "en",
"locales": [
{ "hreflang": "en", "prefix": "" },
{ "hreflang": "en-GB", "prefix": "/en-gb" },
{ "hreflang": "de", "prefix": "/de" },
{ "hreflang": "zh-Hant", "prefix": "/zh-hant" }
],
"paths": ["/", "/pricing"]
}
generate-hreflang.mjs. Run on Node.js 22.15 with the config above: 8 pages, 2 groupsjs
// Usage: node generate-hreflang.mjs hreflang.config.json out
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
const [configFile = "hreflang.config.json", outDir = "out"] = process.argv.slice(2);
const { origin, xDefault, locales, paths } = JSON.parse(readFileSync(configFile, "utf8"));
const esc = (s) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
// One absolute URL per locale and path. "/" under "/de" becomes "/de", not "/de/".
const urlFor = (locale, path) =>
new URL((locale.prefix + path).replace(/(.)\/$/, "$1") || "/", origin).href;
// The full set for one path: every locale, then x-default.
function alternates(path) {
const set = locales.map((l) => ({ hreflang: l.hreflang, href: urlFor(l, path) }));
const fallback = locales.find((l) => l.hreflang === xDefault);
if (fallback) set.push({ hreflang: "x-default", href: urlFor(fallback, path) });
return set;
}
const head = {};
let sitemap =
'<?xml version="1.0" encoding="UTF-8"?>\n' +
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"\n' +
' xmlns:xhtml="http://www.w3.org/1999/xhtml">\n';
for (const path of paths) {
const set = alternates(path);
for (const locale of locales) {
const self = urlFor(locale, path);
// The same lines go on every page in the group. Only the canonical differs.
head[self] = [
`<link rel="canonical" href="${esc(self)}" />`,
...set.map((a) => `<link rel="alternate" hreflang="${a.hreflang}" href="${esc(a.href)}" />`),
].join("\n");
sitemap +=
` <url>\n <loc>${esc(self)}</loc>\n` +
set.map((a) => ` <xhtml:link rel="alternate" hreflang="${a.hreflang}" href="${esc(a.href)}"/>\n`).join("") +
" </url>\n";
}
}
sitemap += "</urlset>\n";
mkdirSync(outDir, { recursive: true });
writeFileSync(`${outDir}/head-tags.json`, JSON.stringify(head, null, 2));
writeFileSync(`${outDir}/sitemap.xml`, sitemap);
console.log(`${Object.keys(head).length} pages, ${paths.length} groups written to ${outDir}/`);

The script was run for this guide. With the config above it wrote eight pages in two groups, and the sitemap passed xmllint --noout. The head example in Part 2 is its output for /en-gb/pricing, with a title added.

It assumes every path exists in every locale, with the same slug. Two cases need more input:

  • Translated slugs. Replace paths with a map from a page id to its path per locale.
  • Pages missing in some locales. Build each set from the locales that have the page, and print no entry for the others.

Next.js

The samples target the Next.js 16 App Router. Its metadata API has an alternates field with canonical and languages. The documentation shows languages rendering as <link rel="alternate" hreflang="..."> elements, and metadataBase turning relative paths into absolute URLs.

Every locale is listed, including the current one. Next.js prints what you pass and adds no self referencetsx
// app/[lang]/pricing/page.tsx
import type { Metadata } from 'next'
const locales = ['en', 'en-GB', 'de']
export async function generateMetadata(
{ params }: { params: Promise<{ lang: string }> }
): Promise<Metadata> {
const { lang } = await params
return {
metadataBase: new URL('https://example.com'),
alternates: {
canonical: `/${lang}/pricing`,
languages: {
...Object.fromEntries(locales.map((code) => [code, `/${code}/pricing`])),
'x-default': '/en/pricing',
},
},
}
}

Two notes. The x-default key is not in the documentation's example. It is a typed key (UnmatchedLang) in the next 16.4.6 package. And for sitemaps, app/sitemap.ts accepts alternates.languages per entry since v14.2.0 and writes xhtml:link children. The documented output contains only the languages you list, so add the entry's own language to its languages object to meet Google's self-reference rule. This sample follows the documentation and was not run in a Next.js app. Translate a React or Next.js app automatically covers the translation files behind these routes.

WordPress

On WordPress, hreflang comes from the multilingual plugin. Stated from each plugin's own pages:

  • WPML says it automatically inserts hreflang tags into pages and updates them as the site changes, with no action needed.
  • Polylang says it adds hreflang automatically, converts WordPress locales such as en_ZA to en-ZA, and generates x-default only for the home page. It documents the pll_rel_hreflang_attributes filter for changing the set, for example to add a generic en or an x-default on every page.

Whichever plugin you use, view the source of a translated page and run it through the audit in Part 10. Best CMS translation tools for content teams compares the wider options.

Shopify

Shopify's theme documentation states that Shopify automatically includes hreflang tags through the content_for_header object. Its help centre states that each published language gets its own URLs. A theme that outputs content_for_header in its layout therefore needs no hreflang code of its own. Nothing further is documented on those two pages about which codes are emitted or about x-default, so check the rendered source of your store. See AI translation for Shopify stores for the translation side.


Part 10: auditing hreflang

The common errors

ErrorWhat it looks likeEffectFix
Missing return linkX names Y, Y does not name XGoogle ignores that pairPrint the same set on every member
Missing self referenceThe page is absent from its own setBreaks Google's "must list itself" ruleAdd the page to its set
Wrong language codejp, eng, a country used as a languageNot a supported valueUse ISO 639-1
Wrong region codeen-UK, en-EUGoogle ignores that part of the annotationUse ISO 3166-1 Alpha 2
Relative URLhref="/de/"Not fully qualifiedPrint the scheme and host
Redirected or broken targethref returns 301 or 404No page to return the linkPoint at the final 200 URL
Non-canonical targetThe target's canonical is another URLConflicts with the canonical signalUse the canonical URL
Canonical to another languageGerman page, English canonicalAsks Google to drop the German pageSelf-referencing canonical
Tags outside the headThe head closes early in rendered HTMLTags are not read as head tagsFix the markup, validate rendered HTML
Two methods that disagreeHead says one set, sitemap anotherTwo answers to one questionKeep one method

An audit script

This script reads a list of URLs, fetches each without following redirects, and reads hreflang from the head and from the Link header. For every target it fetches the page and checks the return link. It targets Node.js 22 or later and uses the built-in fetch.

audit-hreflang.mjs. Exits with code 1 when anything is found, so it can gate a deployjs
// Usage: node audit-hreflang.mjs urls.txt (one absolute URL per line, Node.js 22 or later)
import { readFileSync } from "node:fs";
const LANGS = new Set("aa ab ae af ak am an ar as av ay az ba be bg bi bm bn bo br bs ca ce ch co cr cs cu cv cy da de dv dz ee el en eo es et eu fa ff fi fj fo fr fy ga gd gl gn gu gv ha he hi ho hr ht hu hy hz ia id ie ig ii ik io is it iu ja jv ka kg ki kj kk kl km kn ko kr ks ku kv kw ky la lb lg li ln lo lt lu lv mg mh mi mk ml mn mr ms mt my na nb nd ne ng nl nn no nr nv ny oc oj om or os pa pi pl ps pt qu rm rn ro ru rw sa sc sd se sg si sk sl sm sn so sq sr ss st su sv sw ta te tg th ti tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa wo xh yi yo za zh zu".split(" "));
const REGIONS = new Set("AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW".split(" "));
// language, optional four-letter script, optional region. The script is checked for shape only.
function validCode(code) {
if (code.toLowerCase() === "x-default") return true;
const parts = code.split("-");
if (!LANGS.has(parts.shift().toLowerCase())) return false;
if (parts[0] && /^[a-z]{4}$/i.test(parts[0])) parts.shift();
if (parts[0] && REGIONS.has(parts[0].toUpperCase())) parts.shift();
return parts.length === 0;
}
const attrs = (tag) =>
Object.fromEntries([...tag.matchAll(/([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)].map((m) => [m[1].toLowerCase(), m[2] ?? m[3]]));
const same = (a, b) => { try { return new URL(a).href === new URL(b).href; } catch { return false; } };
const cache = new Map();
async function load(url) {
if (cache.has(url)) return cache.get(url);
const page = { url, status: 0, alternates: [], canonical: null, noindex: false, outsideHead: false };
try {
const res = await fetch(url, { redirect: "manual" });
page.status = res.status;
const html = res.status === 200 ? await res.text() : "";
const headEnd = html.search(/<\/head>/i);
const links = (s) => (s.match(/<link\b[^>]*>/gi) ?? []).map(attrs);
const isAlt = (l) => /\balternate\b/i.test(l.rel ?? "") && l.hreflang;
for (const l of links(headEnd < 0 ? html : html.slice(0, headEnd))) {
if (isAlt(l)) page.alternates.push({ code: l.hreflang, href: l.href ?? "" });
if (/\bcanonical\b/i.test(l.rel ?? "")) page.canonical = l.href;
}
page.outsideHead = headEnd >= 0 && links(html.slice(headEnd)).some(isAlt);
// The HTTP Link header carries the same data for files with no head.
for (const part of (res.headers.get("link") ?? "").split(/,(?=\s*<)/)) {
const href = part.match(/<([^>]+)>/)?.[1];
const code = part.match(/hreflang\s*=\s*"?([\w-]+)"?/i)?.[1];
if (href && code && /rel\s*=\s*"?alternate"?/i.test(part)) page.alternates.push({ code, href });
}
const robots = (html.match(/<meta\b[^>]*>/gi) ?? []).map(attrs).find((m) => /^(robots|googlebot)$/i.test(m.name ?? ""));
page.noindex = /noindex/i.test(`${robots?.content ?? ""} ${res.headers.get("x-robots-tag") ?? ""}`);
} catch (e) {
page.error = e.message;
}
cache.set(url, page);
return page;
}
const urls = readFileSync(process.argv[2], "utf8").split("\n").map((s) => s.trim()).filter(Boolean);
let errors = 0;
for (const url of urls) {
const found = [];
const p = await load(url);
if (p.status !== 200) found.push(`returns ${p.error ?? p.status}, so it cannot carry hreflang`);
else if (!p.alternates.length) found.push("no hreflang annotations");
else {
if (p.outsideHead) found.push("hreflang link found outside <head>");
if (p.noindex) found.push("page is noindex");
if (p.canonical && !same(p.canonical, url)) found.push(`canonical points to ${p.canonical}`);
if (!p.alternates.some((a) => a.code.toLowerCase() !== "x-default" && same(a.href, url))) found.push("missing self reference");
if (!p.alternates.some((a) => a.code.toLowerCase() === "x-default")) found.push("no x-default (optional)");
const seen = new Set();
for (const a of p.alternates) {
const code = a.code.toLowerCase();
if (!validCode(a.code)) found.push(`invalid code "${a.code}"`);
if (seen.has(code)) found.push(`"${a.code}" is declared more than once`);
seen.add(code);
if (!/^https?:\/\//i.test(a.href)) { found.push(`"${a.code}" href is not fully qualified: ${a.href}`); continue; }
if (same(a.href, url)) continue;
const t = await load(a.href);
if (t.status !== 200) { found.push(`"${a.code}" target ${a.href} returns ${t.error ?? t.status}`); continue; }
if (t.noindex) found.push(`"${a.code}" target ${a.href} is noindex`);
if (t.canonical && !same(t.canonical, a.href)) found.push(`"${a.code}" target ${a.href} is not canonical`);
if (code !== "x-default" && !t.alternates.some((b) => same(b.href, url))) found.push(`no return link from ${a.href}`);
}
}
errors += found.length;
console.log(`${found.length ? "FAIL" : "ok "} ${url}`);
for (const f of found) console.log(` - ${f}`);
}
console.log(`\n${urls.length} URLs checked, ${errors} findings`);
process.exitCode = errors ? 1 : 0;

It was run against a local fixture: a small Node.js server with four pages and one redirect, each broken on purpose. This is the output:

Output against the local fixture, Node.js 22.15text
FAIL http://localhost:4010/en/
- "fr" target http://localhost:4010/fr/ is not canonical
- "it" target http://localhost:4010/it-old/ returns 301
ok http://localhost:4010/de/
FAIL http://localhost:4010/fr/
- canonical points to http://localhost:4010/en/
- no return link from http://localhost:4010/de/
FAIL http://localhost:4010/it/
- page is noindex
- missing self reference
- no x-default (optional)
- invalid code "en-UK"
- no return link from http://localhost:4010/en/
- "de" href is not fully qualified: /de/
FAIL http://localhost:4010/it-old/
- returns 301, so it cannot carry hreflang
5 URLs checked, 11 findings

A missing return link is reported on the page that is not linked back, here French. The fix belongs on /de/, which forgot the link.

Limits of the script:

  • It reads the HTML the server returns. Tags added by JavaScript in the browser are not seen.
  • It does not read sitemaps.
  • Script subtags are checked for shape, four letters, not against the ISO 15924 list.
  • A trailing-slash difference counts as a different URL.

Run it in CI against a preview deployment. React localization CI checks shows the same pattern for translation files.

Where other tools report errors

  • Google Search Console. The International Targeting report is deprecated. Google's help page says it will continue to support and use hreflang tags. The Performance report can group data by Countries and Pages, which shows which URL appears in which country.
  • Tools Google names. Its documentation links to a third-party tag generator by Aleyda Solis and a single-page testing tool by Merkle, and says they are not maintained or checked by Google.
  • Screaming Frog SEO Spider. Its documentation describes an Hreflang tab with 13 filters, including Non-200 Hreflang URLs, Missing Return Links, Inconsistent Language & Region Return Links, Non Canonical Return Links, Noindex Return Links, Incorrect Language & Region Codes, Missing Self Reference and Missing X-Default. For sets that span domains it says external pages are not fully reviewed by default.
  • Ahrefs Site Audit. Its help centre lists these issues: hreflang annotation invalid, self-reference hreflang annotation missing, page referenced for more than one language, more than one page for same language, hreflang and HTML lang mismatch, missing reciprocal hreflang, hreflang to non-canonical and hreflang to broken page.

Neither crawler was run for this guide. The lists above are what each vendor's page states.


Part 11: Bing and Yandex

Yandex

Yandex documents hreflang on its own Webmaster help pages, with differences from Google:

  • Placement. It describes <link rel="alternate" hreflang> elements in the head. It states that it no longer supports using the sitemap file for language versions. Its page does not describe an HTTP header method.
  • Codes. ISO 639-1 for the language. For the region, ISO 3166-1 Alpha 2, or ISO 3166-2:RU for Russian regions. It publishes a list of supported languages.
  • x-default. Use it when the page language is chosen automatically, for example from the IP address or the Accept-Language header.
  • Structure. Versions can sit on different domains, subdomains or directories.

If Yandex matters to you, head tags are the placement both engines read.

Bing

Bing's public material says less. A Bing Webmaster blog post from December 2025 tells site owners to use hreflang to define language and regional targeting, with an HTML <link> example, and lists hreflang with canonical tags, redirects and noindex as signals that make clear which URL to show. Microsoft's page on how Bing delivers results says ranking considers the user's location, where the page is hosted and the language of the page.

No Bing page was found that sets out placements, code rules or a return-link requirement, so none are stated here. An hreflang set that is valid for Google uses the same markup Bing's example shows.


Part 12: what to expect after a fix

Google does not document a timeline for hreflang specifically. What it does document:

  • Crawling can take anywhere from a few days to a few weeks.
  • Requesting a crawl, through the URL Inspection tool for a few URLs or a sitemap for many, does not guarantee instant inclusion in results.

Because a pair only counts when both pages point to each other, a fix is complete for a pair once Google has recrawled both pages. That is a deduction from the return-link rule, not a figure Google publishes.

What to watch:

  1. Run the audit until it reports nothing.
  2. Resubmit the sitemap if that is your placement.
  3. In the Search Console Performance report, group the data by Countries and by Pages and look at which pages appear in each market. English URLs showing in Germany should give way to German URLs as pages are recrawled.

Do not expect a change in how many searches you appear for. hreflang changes which of your URLs is shown.

A cream paper-pulp balance scale on a dark stone plinth with a paper page on each pan and a thin paper cord running both ways between them, a teal glass bead at the pivot
A pair counts when both pages point to each other

Doing this with Transglot

Transglot is a continuous localization platform: it keeps the text of a product or site translated. What its documentation states about hreflang is limited to this:

  • WordPress. With the Transglot plugin, translations are rendered on per-language URLs with hreflang and per-language sitemaps. See the WordPress connector page.
  • Sites built in code. hreflang is the job of your framework and templates. Transglot supplies the translated files or strings. The routing, the canonical and the alternate links come from code such as the samples in Part 9.

Neither was tested for this guide. Audit the WordPress output the same way as any other site.


Common mistakes

  • Missing return links. The set differs from page to page.
  • No self reference.
  • en-UK, es-419, or a country code alone.
  • Relative or protocol-relative URLs.
  • Canonical on every translation pointing at English.
  • Targets that redirect after a URL change.
  • noindex pages in the set.
  • Tags outside the head in rendered HTML.
  • Head tags and a sitemap that disagree.
  • Expecting a ranking gain. The gain is the right URL in the right market.
  • Automatic redirects by IP or browser language on top of hreflang.
  • Every page pointing at each language's home page in place of its own translation.

Checklist

texttext
Set
[ ] One list of locales and paths generates every set
[ ] Every page lists itself
[ ] Every page lists all other versions
[ ] The set is identical on every member of a group
[ ] x-default present where a fallback makes sense
Codes
[ ] Language is ISO 639-1
[ ] Region, if used, is ISO 3166-1 Alpha 2 (GB, not UK)
[ ] No region-only values, no es-419, no EU
[ ] zh-Hans or zh-Hant where the script is the point
[ ] A catch-all language code exists next to regional versions
URLs
[ ] Fully qualified, with https://
[ ] Each href returns 200 without a redirect
[ ] Each href is the canonical URL of its page
[ ] No noindex or robots.txt-blocked targets
[ ] No tracking or sort parameters
Canonical
[ ] Each language version is its own canonical
[ ] canonical and hreflang are separate link elements
Placement
[ ] One method per page type: head, header or sitemap
[ ] Head tags are inside <head> in rendered HTML
[ ] Sitemap declares the xhtml namespace
[ ] PDFs carry the Link header
Audit
[ ] audit-hreflang.mjs returns no findings on a sample of every template
[ ] The audit runs in CI or on a schedule
[ ] Search Console Performance checked by country after release

Frequently asked questions

What is an hreflang tag?

An hreflang tag is a <link rel="alternate" hreflang="code" href="url"> element that names one language or regional version of a page. A page carries one per version, itself included.

Does hreflang improve rankings?

Google documents it as a way to point users to the most appropriate version of a page, not as a way to rank higher. Its effect is on which of your URLs appears for a searcher.

What is x-default hreflang and do I need it?

x-default names the page for searchers whose language or region matches none of your versions. Google recommends it and does not require it. It can point to a language selector, to a page you redirect unmatched users to, or to the version you treat as the default.

Should hreflang go in the HTML or in the sitemap?

Google treats the head, the HTTP header and the sitemap as equivalent and advises picking one. The head is easy to inspect. An hreflang sitemap keeps pages lighter when there are many languages. Yandex no longer reads language versions from sitemaps, so use head tags if it matters to you.

Is there an hreflang generator?

Google's documentation links to a third-party generator by Aleyda Solis and notes that it is not maintained or checked by Google. For a site with many pages, generate the tags in code from one list of locales, as the script in Part 9 does.

How do I check hreflang tags?

Fetch each page, read its set, then fetch every target and confirm it returns 200, is canonical, and links back. The script in Part 10 does this for a list of URLs. Google links to a single-page testing tool by Merkle, and crawlers such as Screaming Frog and Ahrefs Site Audit document hreflang reports.

Why does a tool say "your site has no hreflang tags"?

It means the crawler found no hreflang annotations in the pages it read, which is correct for a site in one language. If you do have tags, check that they are inside the <head> of the rendered HTML and that the tool read your sitemap or headers if that is your placement.

Is en-UK a valid hreflang code?

No. The ISO 3166-1 Alpha 2 code for the United Kingdom is GB, so the value is en-GB. Google lists UK, EU and UN as codes that have no effect in hreflang annotations.

How this guide was checked

  • Rules, placements, codes, x-default and common mistakes follow Google Search Central's "Tell Google about localized versions of your page", read on 24 November 2026. The x-default uses and the URL discovery note follow Google's 2013 and 2023 blog posts.
  • Canonical, pagination, noindex, redirects and timing follow the Google pages listed below. Google's hreflang page does not cover pagination, parameters, noindex or redirects. Part 7 says where a point is a deduction from other Google pages or comes from a crawler vendor's documentation.
  • Yandex follows its Webmaster help page on localized pages. Bing follows one Bing Webmaster blog post and one Microsoft support page. An older Bing post on country and language signals returned 404 and was not used.
  • Next.js follows the generateMetadata and sitemap reference pages. The x-default key was confirmed in the type definitions of next 16.4.6. The sample was not run in a Next.js app.
  • WordPress and Shopify are stated only from WPML's, Polylang's and Shopify's own pages. No plugin or store was tested.
  • The generator script was run on Node.js 22.15. Its sitemap was checked with xmllint for well-formed XML. It was not submitted to Search Console.
  • The audit script was run on Node.js 22.15 against a local fixture server with seeded errors. The output shown is the real output. It was not run against a production site. Its language and region lists were built from the Library of Congress ISO 639-2 code file (183 two-letter codes) and the Debian iso-codes list for ISO 3166-1 (249 codes).
  • Other tools. Screaming Frog and Ahrefs are described from their own documentation. Neither was run or benchmarked. The two tools Google links to were not tested.
  • Not tested. No ranking, traffic or indexing effect was measured. Baidu, Naver and AI answer engines are not covered.

Sources

colophon

Who wrote this, and what to read next

wrote this

transglot team

The byline on this post has no profile yet. Author profiles are managed alongside the posts themselves.

Engineering
Best practices
keep reading

How to Translate a React or Next.js App Automatically

The three parts of automatic translation in a React or Next.js app, the tools that cover each part, and a setup that keeps every language current on each push.

November 23, 2026
8 min read
keep reading

Best CMS Translation Tools for Content Teams

Compare the best CMS translation tools for content teams. Explore six options, current pricing, connector limits and a practical pilot before you buy.

September 14, 2026
32 min read
keep reading

The Best AI Tools to Translate a Shopify Store in 2026

Compare four ways to translate a Shopify store with AI, what each one translates, how each is priced, and which fits a store of your size.

November 23, 2026
10 min read
works with what you already run

41 connectors, already built.

the pipeline this post describes

Try it on your own strings. Free, no card.

Free plan: 100,000 words to start (25,000 at sign-up, 75,000 after a phone check), then 10,000 a month, 15 locales including your source, 3 seats.