Skip to content

Pages by country

hreflang for AI fetchers: pick the localized URL, then read it

Read the hreflang alternates a page declares, pick the right localized URL for your user with an x-default fallback, and check the language of what you actually got.

By Curtis Mccann, Live Web Data team · Published

This article was drafted with AI assistance from the sources listed below and edited and published by the Live Web Data team. Disclosure: the Live Web Data API, which this article mentions, is this site's own product.

From one URL to the right localized page
  1. 1Read the alternatesCollect rel="alternate" hreflang links from the HTML head and the HTTP Link header.
  2. 2Match language and regionTry language-region first, then the language alone.
  3. 3Fall back to x-defaultUse the x-default URL when nothing matches the user.
  4. 4Request that URLFetch the chosen localized URL directly, not the original one.
  5. 5Verify the pageCheck the lang attribute and Content-Language of what came back.

Your user is in Austria and asks what a public pricing page says. The URL you have is https://example.com/pricing. The page you get back is in English. Somewhere in its <head> there may be a line that says a German version exists at another address. If your fetcher ignores that line, the model answers a German-speaking user from the English page.

The guide on country-specific web content explains that hreflang does not decide what a fetcher receives. This post covers the next step: how to use the annotations a page does publish to pick the right localized URL, and how to check what you got.

What hreflang is, and what it is not

The decision first: treat hreflang as a map of URLs, not as a switch. The HTML standard says the hreflang attribute gives the language of the linked resource, calls it "purely advisory", and says user agents must not consider it authoritative. A rel="alternate" link whose hreflang differs from the document's own language marks the linked document as a translation.

Search engines use these maps to show the right version in results. Google's documentation also states that it does not use hreflang or the HTML lang attribute to detect the language of a page; it uses algorithms for that. So the annotation tells you where a version is supposed to live. It does not prove what that version contains.

Where the alternates live

Google lists three ways a site can declare localized versions, and treats them as equivalent:

  • HTML link elements inside <head>: <link rel="alternate" hreflang="de" href="https://example.com/de/pricing" />. Each page lists every variant, itself included.
  • An HTTP Link header, with the same rel="alternate" and hreflang parameters. Google points to this for non-HTML files such as PDFs.
  • An XML sitemap, with xhtml:link entries under each <url>.

A fetcher sees the first two in the response it already has. The sitemap is a separate file, so read it only when the page itself declares nothing. Note that the head links only exist in the HTML. If you convert the page to Markdown before you look, they are gone, so read the alternates from the HTML or the response headers first.

The values you will see

The default here: match on language and region, then on language alone, then use x-default. Google's rules for the values make that order work:

  • The language is an ISO 639-1 code, optionally followed by an ISO 3166-1 alpha-2 region code: de, de-at, en-us.
  • A country code on its own is not allowed, so at alone is not a valid value.
  • The value is case-insensitive, so lowercase everything before you compare.
  • Script codes such as zh-Hant and zh-Hans are supported; codes like es-419 are not, by Google's rules.
  • x-default is reserved for the version to use when no other language or region matches.

Alternate URLs must be fully qualified, with http or https. A relative href is invalid by Google's rules, so treat one as a sign the annotations may be broken.

Pick the URL in code

This parser collects the alternates from HTML and picks one for a language and an optional region. It uses the Python standard library only.

from html.parser import HTMLParser


class AlternateLinks(HTMLParser):
    def __init__(self):
        super().__init__()
        self.alternates = {}

    def handle_starttag(self, tag, attrs):
        if tag != "link":
            return
        a = dict(attrs)
        rel = (a.get("rel") or "").lower().split()
        if "alternate" in rel and a.get("hreflang") and a.get("href"):
            self.alternates[a["hreflang"].lower()] = a["href"]


def pick(alternates, lang, region=None):
    lang = lang.lower()
    if region:
        key = f"{lang}-{region.lower()}"
        if key in alternates:
            return alternates[key]
    if lang in alternates:
        return alternates[lang]
    return alternates.get("x-default")


html = """<html lang="en"><head>
<link rel="alternate" hreflang="en-us" href="https://example.com/en-us/pricing">
<link rel="alternate" hreflang="de" href="https://example.com/de/pricing">
<link rel="alternate" hreflang="x-default" href="https://example.com/pricing">
</head><body>...</body></html>"""

parser = AlternateLinks()
parser.feed(html)
print(pick(parser.alternates, "de", "AT"))  # https://example.com/de/pricing
print(pick(parser.alternates, "fr"))        # https://example.com/pricing

There is no de-at entry, so the Austrian user gets the de page. A French user matches nothing and gets the x-default page. When pick returns None, the page declared no usable alternates: keep the URL you have.

Google ignores the annotations when two pages do not both point to each other, and each version must list itself as well as the others. That rule is Google's, but it is a cheap test for your own fetcher too. After you request the chosen URL, look for an alternate that points back to the page you started from. If it is missing, the map is one-sided: you can still use the page, but trust the language check below more than the annotation.

Verify what you got

The HTML standard says that once a resource is fetched, its own language information is what counts, not the hreflang on the link that led there. So after you request the localized URL, check the lang attribute on the <html> element and the Content-Language header. The post on which language you fetched covers how to read those signals and pass the result to the model.

When hreflang cannot help

Some sites keep one URL and change the page by the reader's location or language settings. Google advises against redirecting users automatically between language versions and recommends a separate URL for each language version. It also says its crawler usually comes from the USA and that it does not try to vary the location to find site variations. On a site that varies one URL by location, there is no alternate URL to request. The only way to see a country's version is to read the page from that country.

Live Web Data API reads each page through a connection in the country you set with countryCode, and the default is us. Every request fetches the page live; there is no cache. The API reference shows the parameter. Read only public pages, check robots.txt and the site's terms before fetching at volume, and keep to the acceptable-use policy.

Checklist

  • Read alternates from the HTML head and the Link header before converting to Markdown.
  • Lowercase the values, then match language-region, language, x-default, in that order.
  • Request the chosen URL itself.
  • Look for the return link on the page you land on.
  • Record the language the page declares, not the one the link promised.

Frequently asked questions

Does hreflang change what a server sends to my fetcher?

No. hreflang annotations list the localized URLs a page says exist. The server still answers each request the way it chooses. To get a specific localized version, request that version's own URL.

Where does a page declare its hreflang alternates?

Google documents three equivalent places: link elements in the HTML head, an HTTP Link header (useful for non-HTML files such as PDFs) and an XML sitemap. A fetcher sees the first two in the response; the sitemap is a separate file.

What is x-default in hreflang?

It is a reserved value for the version to use when no other language or region matches the user, for example a language selector page or a generic fallback.

Can I trust the hreflang value as the language of the linked page?

Treat it as a hint. The HTML standard calls the attribute purely advisory and says that after fetching, user agents must use only the language information associated with the resource itself. Check the fetched page's lang attribute and Content-Language.

Sources

  1. Tell Google about localized versions of your page (Google Search Central) (Documentation)
  2. HTML Standard: Links (WHATWG) (Documentation)
  3. Managing multi-regional and multilingual sites (Google Search Central) (Documentation)