# Website Broken Outbound Link Watch (`practical_ai_lab_jp/pal-website-broken-outbound-link-watch`) Actor

Samples a public HTTPS site's outbound links within robots.txt rules and reports newly broken or fixed links against a stored baseline.

- **URL**: https://apify.com/practical_ai_lab_jp/pal-website-broken-outbound-link-watch.md
- **Developed by:** [Practical AI Lab](https://apify.com/practical_ai_lab_jp) (community)
- **Categories:** E-commerce, Developer tools
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 85.7% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.00 / 1,000 link change reports

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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

## Website Broken Outbound Link Watch

Watch the links your public website sends visitors to other sites. The Actor reads a small, bounded set of your pages, validates a sample of the outbound links, and keeps a per-domain baseline. The first run stores the baseline. Every later run reports which links **became broken**, which were **fixed**, and which broken links **disappeared from your pages**, each with the page it was found on, the before/after status and UTC timestamps.

It is a monitoring and evidence tool, not a full site crawler. See [Limitations](#limitations-and-sample-size-caveats) before relying on it.

### Quick start

Copy this input into the Input tab and run it once to create the baseline:

```json
{
    "startUrl": "https://crawlee.dev/",
    "maxPages": 12,
    "maxOutboundLinks": 20,
    "maxLinksPerHost": 3
}
```

Replace `startUrl` with your own site root. It must be one public HTTPS root with no path, for example `https://example.com/`.

Run it again later (or on a schedule) with the same input to get the change report.

### What it does

1. Validates `startUrl`: HTTPS only, public host, no credentials, no custom port, no localhost, private or reserved addresses (host names are resolved and every address must be public).
2. Reads `robots.txt` first and obeys it, including `Crawl-delay` (a delay above 10 seconds stops the run). If `robots.txt` cannot be read safely, nothing is crawled.
3. Reads the homepage, then up to `maxPages` pages in total, chosen from the sitemap (one index level, at most 3 sitemap files, first 200 URLs) or, when there is no usable sitemap, from homepage links.
4. Collects outbound links from `<a href>` tags only, then validates a stable, host-diversified sample using `HEAD` (falling back to a bodyless `GET` when `HEAD` is not allowed). Each failing link is retried once.
5. Compares the sample with the stored baseline and writes the report.

Redirects are followed manually and every hop is re-validated. On your own site, redirects to a different origin are rejected. For outbound links, redirects must stay HTTPS and public.

### Output

**Dataset** (`recordType`):

- `SUMMARY`: one row per run with status, counts and a plain-language message.
- `FINDING`: one row per broken or changed link, with `changeType`, `targetUrl`, `sourcePageUrl`, `previousLinkStatus` / `previousHttpStatus` / `previousCheckedAt` (before) and `linkStatus` / `httpStatus` / `checkedAt` (after).

**Key-value store of the run**:

- `REPORT`: full JSON report (summary, findings, every checked link, crawled pages, notes, limitations, billing eligibility).
- `REPORT_CSV`: findings as CSV, with the same source URL and timestamp columns.

**Baseline store** (named store, default `pal-link-watch-state`): one `BASELINE_<domain>` record per domain.

#### Run statuses

| Status | Meaning | Eligible for billing event |
| --- | --- | --- |
| `BASELINE_CREATED` | First run for this domain; baseline stored | No |
| `NO_CHANGES` | Nothing changed since the previous run | No |
| `CHANGES_DETECTED` | At least one change in the table below | Yes, once per run |
| `UNSAFE_START_URL`, `INVALID_START_URL`, `START_HOST_UNRESOLVABLE` | Input rejected before any request | No (run fails) |
| `BLOCKED_BY_ROBOTS`, `ROBOTS_UNAVAILABLE`, `ROBOTS_CRAWL_DELAY_TOO_LONG` | robots.txt forbids, cannot be read, or asks for a very long delay | No (run fails) |
| `START_PAGE_UNAVAILABLE`, `NETWORK_UNRELIABLE` | Homepage unreadable, or every sampled link failed (likely a network problem) | No (run fails) |

Failed runs write an explanatory report, never touch the baseline and are never billed.

#### Change types

| `changeType` | Meaning |
| --- | --- |
| `BASELINE_BROKEN` | Broken in the first run (baseline evidence) |
| `NEWLY_BROKEN` | Was healthy in the baseline, now broken |
| `NEWLY_OBSERVED_BROKEN` | Broken and not part of the baseline sample (new link, or only sampled now) |
| `FIXED` | Was broken, now answers successfully |
| `BROKEN_STATUS_CHANGED` | Still broken, but in a different way (for example 404 to 500) |
| `BROKEN_LINK_REMOVED` | A broken link is no longer found on the pages that carried it |
| `STILL_BROKEN` | Informational: unchanged broken link (not a change) |

Link statuses: `ok`, `broken_not_found` (404/410), `broken_client_error`, `broken_server_error`, `broken_unreachable` (DNS, connection, timeout), `broken_redirect`, `blocked_or_restricted` (401, 403, 429 and similar; **not** counted as broken).

### Scheduling

Create a Task with your input and add a schedule, for example daily or weekly. Keep `stateStoreName` unchanged so runs share one baseline. Because `updateBaseline` is on by default, each run is compared with the previous run and every change is reported once. Turn it off to keep comparing against the first run.

Use one Task per site root. Different domains are stored under separate baseline keys, and `www.example.com` and `example.com` are different origins.

### Input

| Field | Default | Notes |
| --- | --- | --- |
| `startUrl` (required) | | One public HTTPS site root |
| `maxPages` | 12 | 1-40 pages read on your site |
| `maxOutboundLinks` | 20 | 1-60 outbound links validated |
| `maxLinksPerHost` | 3 | 1-10 links per outside host |
| `requestDelayMs` | 500 | 250-5000 ms between all requests |
| `requestTimeoutSecs` | 10 | 3-30 seconds |
| `updateBaseline` | true | Roll the baseline forward after each run |
| `stateStoreName` | `pal-link-watch-state` | Named store for baselines; empty uses the run's own store, which does not persist between runs |

Total requests per run are capped (about `10 + maxPages + 4 x maxOutboundLinks`). Memory use is low because pages are streamed up to a size limit and processed one at a time.

### Safety and privacy

- Only robots-permitted public pages are read. Login, account, checkout, admin, unsubscribe and similar paths are skipped, as are non-page files (PDF, images, archives).
- Outbound hosts have their own `robots.txt` read; disallowed links are skipped and counted, not reported as broken.
- Contact-style links (`mailto:`, `tel:`) are ignored and never stored. Outbound links whose query contains credential-like or address-like values are skipped entirely. Tracking parameters and fragments are removed from stored URLs.
- No logins, cookies, proxies, browsers or third-party APIs are used.
- Response sizes are capped, compressed responses are decoded under the same cap, and XML with DTD or entity declarations is refused.

### Pricing

The code defines one pay-per-event event, `link-change-report`, charged at most once per run and only when the status is `CHANGES_DETECTED`. Baseline, no-change and failed runs never charge. No price or payable plan is configured in this project.

### Limitations and sample-size caveats

- **This is a sample, not a full audit.** At most 40 pages and 60 outbound links are checked per run. The report states how many links were discovered versus checked (`coveragePercent`). No finding does not mean no broken links.
- Pages come from the first 200 URLs of the sitemap (or homepage links), chosen by a stable hash so repeated runs look at mostly the same pages. Large sites will have large unchecked areas. Gzip-compressed sitemaps are not read.
- Links are compared only when present in both samples. If the sample changes, a link can appear as `NEWLY_OBSERVED_BROKEN` although it existed before.
- Only static `<a href>` links are seen; links rendered by JavaScript are not.
- A broken result can be a temporary outage, a bot-blocking rule answering with an error code, or a site that rejects `HEAD` requests. Treat findings as leads to verify, not final proof.
- Sites that hide behind a login, answer 401/403/429, or disallow this crawler cannot be validated and are reported as blocked or skipped.
- DNS is checked before each request, but a hostile DNS server could change its answer between the check and the connection; do not rely on this Actor as a security scanner.
- Redirect targets are checked for safety but their `robots.txt` is not re-read.
- Query strings are cleaned, so a page that depends on a removed tracking parameter may be checked in a slightly different form.

### Local tests

The unit tests are fully offline and use mocked HTTP. From the project folder:

```
python -m unittest discover -s tests -t .
```

# Actor input Schema

## `startUrl` (type: `string`):

Public HTTPS site root, e.g. https://practical-ai-lab.pages.dev/ . Only monitor sites you own or are permitted to audit. robots.txt is respected; do not use private addresses, credentials or unsafe URLs.

## `maxPages` (type: `integer`):

Pages read on your site: the homepage plus a stable sample of sitemap URLs (or homepage links when no sitemap exists).

## `maxOutboundLinks` (type: `integer`):

Size of the outbound link sample that is validated. Larger samples give better coverage and cost more run time.

## `maxLinksPerHost` (type: `integer`):

Keeps the sample spread out and polite to third-party sites.

## `requestDelayMs` (type: `integer`):

Pause between all requests. A longer Crawl-delay in robots.txt always wins.

## `requestTimeoutSecs` (type: `integer`):

Per-request timeout.

## `updateBaseline` (type: `boolean`):

When on, each run becomes the new baseline so every change is reported once. Turn off to keep comparing against the first run.

## `stateStoreName` (type: `string`):

Named key-value store that keeps one baseline per domain between runs. Use 3-63 lowercase letters, digits or hyphens. Leave empty to use the run's own store, which does not persist between runs.

## Actor input object example

```json
{
  "startUrl": "https://practical-ai-lab.pages.dev/",
  "maxPages": 5,
  "maxOutboundLinks": 8,
  "maxLinksPerHost": 2,
  "requestDelayMs": 500,
  "requestTimeoutSecs": 10,
  "updateBaseline": true,
  "stateStoreName": "pal-link-watch-state"
}
```

# Actor output Schema

## `results` (type: `string`):

Download rows from the latest run in JSON/CSV.

# 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 = {
    "startUrl": "https://practical-ai-lab.pages.dev/",
    "maxPages": 5,
    "maxOutboundLinks": 8,
    "maxLinksPerHost": 2,
    "requestDelayMs": 500
};

// Run the Actor and wait for it to finish
const run = await client.actor("practical_ai_lab_jp/pal-website-broken-outbound-link-watch").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 = {
    "startUrl": "https://practical-ai-lab.pages.dev/",
    "maxPages": 5,
    "maxOutboundLinks": 8,
    "maxLinksPerHost": 2,
    "requestDelayMs": 500,
}

# Run the Actor and wait for it to finish
run = client.actor("practical_ai_lab_jp/pal-website-broken-outbound-link-watch").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 '{
  "startUrl": "https://practical-ai-lab.pages.dev/",
  "maxPages": 5,
  "maxOutboundLinks": 8,
  "maxLinksPerHost": 2,
  "requestDelayMs": 500
}' |
apify call practical_ai_lab_jp/pal-website-broken-outbound-link-watch --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,practical_ai_lab_jp/pal-website-broken-outbound-link-watch"
        }
    }
}
```

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/mHzqPpIBK1dIqp2qh/builds/Xl5lqVARBVYeBVSXa/openapi.json
