# International Hreflang Audit Crawler (`kayhermes/international-hreflang-audit-crawler`) Actor

Audit international hreflang across all three sources: HTML link tags, HTTP Link headers and XML sitemaps. Checks return links, self-references, locale codes, canonicals, noindex conflicts, redirects and broken targets. Findings are errors, warnings, recommendations or explicitly unverified.

- **URL**: https://apify.com/kayhermes/international-hreflang-audit-crawler.md
- **Developed by:** [Khoa Nguyen](https://apify.com/kayhermes) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$1.20 / 1,000 audited pages

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## International Hreflang Audit Crawler (Actor #198)

Ultimate international hreflang and SEO audit for Apify. Validates hreflang across **all
three supported sources** — HTML `<link>` tags, HTTP `Link` headers and XML sitemaps — and
verifies reciprocal return links, self-references, locale codes, canonical and noindex
conflicts, redirects and broken targets.

### Why this Actor

Google documents HTML, HTTP-header and sitemap hreflang as **equivalent alternatives**. Most
hreflang checkers read HTML only, so a site that declares hreflang correctly in its sitemap is
reported as broken. Others treat a missing `x-default` as a critical error, though Google
documents it as *recommended*. This Actor is built to avoid both classes of false positive.

Every finding is classified as one of:

| Class | Meaning |
|---|---|
| `CONFIRMED_ERROR` | Factually wrong per documented Google guidance, observed on real fetched bytes |
| `WARNING` | Documented failure mode, but not unambiguously an error |
| `RECOMMENDATION` | Google calls it recommended or a convention |
| `UNVERIFIED` | The check could not be completed — no conclusion is claimed |
| `SKIPPED_BUDGET` | Not attempted because a declared budget was exhausted |

A missing return link is **only** reported when the target page was actually fetched and
verified in the same run.

### Modes

| Mode | Use |
|---|---|
| `QUICK_CHECK` | Validate the URLs you supply |
| `CLUSTER_AUDIT` | Cross-page language/region relationships and cluster consistency |
| `SITEWIDE_AUDIT` | Sitemap discovery (incl. sitemap indexes and `.gz`) plus bounded crawling |
| `MIGRATION_QA` | Validate hreflang across migrations, redirects and domain changes |
| `DIFF_MONITOR` | Compare against a previous snapshot: new / resolved / persistent / unverified |

### Output

- **Dataset** — one row per audited page: declared annotations with source and locator,
  source coverage, verification coverage, findings with rule id + evidence + fix, and a grade.
- **`OUTPUT`** — counts, findings by rule and class, budget usage, coverage diagnostics,
  cluster totals and explicit assumptions.
- **`CLUSTER_GRAPH`** — the hreflang graph, nodes and edges with provenance.
- **`REMEDIATION_REPORT`** — findings grouped by rule as CSV, so one change can fix many pages.

Output is usable as-is: no second Actor is required for sitemap reading or CSV.

### Safety and cost control

Every fetch is **reserved against the budget before it is dispatched**, so a run can never
over-fetch. Limits cover pages, unique fetches (global and per host), alternates per page,
sitemaps, sitemap URLs, redirects, response bytes, wall clock, concurrency and retries.
Budget exhaustion is reported as `SKIPPED_BUDGET` — never as a silent page loss.

Security controls applied to *every* request, including redirect hops, alternates and
sitemaps: http/https only, no URL credentials, DNS resolution of all A/AAAA records with
private/loopback/link-local/reserved/metadata ranges rejected for IPv4 and IPv6, the
validated IP pinned to the connection to prevent DNS rebinding, per-hop redirect
revalidation, TLS verification never disabled, a response-size cap enforced on the
**decompressed** stream, and XML parsed with DTD/entity processing disabled.

### Notes

`hreflang` is a hint to Google, not a directive. Findings describe the state of your
annotations; they do not guarantee ranking, indexing or regional search selection.

### Local development and tests

The audit engine has **zero runtime dependencies** (Node built-ins only) and is fully
testable offline:

```bash
node --test            # 194 tests: unit, integration, adversarial, security, stress, RED/GREEN
CRAWLEE_STORAGE_DIR=./storage node src/main.js
```

`apify` is a dependency of the Actor entry point only.

Repair verification: the R3 frozen candidate records 194 tests, 194 pass, 0 fail (`evidence/r3/`);
the earlier R2 tape `evidence/r2/final-suite.tap` records the historic 176-test round-two point.
The adjudicated H1a acceptance and true-script controls run in the full suite and
standalone via `node tools/_acceptance_security_h1a.mjs`; see
`ASTRA_TO_KAY_REVIEW_HANDOFF.md`. No cloud or real SDK release gate is claimed.

# Actor input Schema

## `mode` (type: `string`):

QUICK_CHECK audits the supplied URLs only. CLUSTER_AUDIT also verifies cross-page language/region relationships. SITEWIDE_AUDIT discovers URLs from sitemaps and robots.txt. MIGRATION_QA compares explicit old-to-new URL pairs. DIFF_MONITOR compares this run against a previous snapshot.

## `startUrls` (type: `array`):

Public HTTP(S) pages to audit. Every URL must be fully qualified. Localhost, private-network and metadata addresses are rejected by the security layer.

## `sitemapUrls` (type: `array`):

Optional XML sitemaps to read. Sitemap xhtml:link annotations are treated as a first-class hreflang source, so a site that declares hreflang ONLY in its sitemap is audited correctly. Sitemap indexes and .gz sitemaps are supported.

## `allowedHosts` (type: `array`):

Optional exact hostname allowlist, case-insensitive. Empty means unrestricted public hosts. When set it applies to seeds, sitemap discovery, alternates, robots and every redirect hop. Do not include schemes, ports or paths. Off-list targets remain unverified.

## `useRobotsSitemaps` (type: `boolean`):

When enabled, Sitemap: lines in robots.txt are used to discover sitemaps.

## `respectRobotsTxt` (type: `boolean`):

When enabled, URLs disallowed for this Actor by robots.txt are skipped and reported as SKIPPED with a reason. Disabling this is your responsibility as the site operator.

## `migrationMap` (type: `array`):

For MIGRATION_QA: explicit old-to-new URL pairs. Each pair is audited and compared so dropped locales, redirect problems and canonical retargeting are reported.

## `previousSnapshot` (type: `object`):

For DIFF_MONITOR: a previous run's page findings, normally taken from a prior dataset export. Issues are classified as new, resolved, persistent or unverified using stable fingerprints.

## `checks` (type: `object`):

Which verification checks to perform. Absence of x-default is reported as a recommendation by default, because Google documents x-default as recommended rather than required.

## `limits` (type: `object`):

Hard resource bounds. Every fetch is reserved against these limits BEFORE it is dispatched, so no run can over-fetch. Values above the enforced ceiling are clamped and the clamp is disclosed in OUTPUT.

## Actor input object example

```json
{
  "mode": "QUICK_CHECK",
  "startUrls": [
    {
      "url": "https://www.wikipedia.org/"
    }
  ],
  "sitemapUrls": [],
  "allowedHosts": [],
  "useRobotsSitemaps": true,
  "respectRobotsTxt": true,
  "migrationMap": [],
  "previousSnapshot": {},
  "checks": {
    "verifyReciprocity": true,
    "verifyAlternateStatus": true,
    "requireSelfReference": true,
    "requireXDefault": false,
    "includeSitemapAlternates": true
  },
  "limits": {
    "maxPages": 50,
    "maxDepth": 2,
    "maxAlternatesPerPage": 25,
    "maxFetches": 300,
    "maxFetchesPerHost": 60,
    "maxSitemaps": 10,
    "maxSitemapUrls": 50000,
    "maxRedirects": 5,
    "maxBytesPerResponse": 5000000,
    "maxXmlDepth": 64,
    "timeoutMs": 15000,
    "concurrency": 6,
    "maxRetries": 1,
    "requestDelayMs": 0,
    "maxWallClockSec": 900,
    "maxDeclarationsPerRow": 200,
    "maxFindingsPerRow": 200,
    "maxChargeUsd": 0,
    "estimatedUsdPerPage": 0
  }
}
```

# Actor output Schema

## `dataset` (type: `string`):

One row per audited page with declared hreflang annotations, source coverage, verification coverage, findings and a compliance grade.

## `output` (type: `string`):

Counts discovered/fetched/audited/failed, findings by rule and class, budget usage, coverage diagnostics and assumptions.

## `clusterGraph` (type: `string`):

Cluster nodes and hreflang edges with provenance and verification state.

## `remediationReport` (type: `string`):

Findings grouped by rule so one change can fix many pages.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("kayhermes/international-hreflang-audit-crawler").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("kayhermes/international-hreflang-audit-crawler").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call kayhermes/international-hreflang-audit-crawler --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,kayhermes/international-hreflang-audit-crawler"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/GPMQJMetaxbh9ZZmP/builds/cVS0rHbBLhPTxOsY1/openapi.json
