Catch broken links before your readers do
Automated offline link checking on rendered Quarto and pkgdown sites in CI
The problem
Broken internal links are among the quickest ways to erode reader trust. In technical engineering documentation, clinical study reports, or package reference sites, a link resolving to a 404 page signals sloppy maintenance:
- Slug and path refactoring. Renaming a topic from
topics/01-isolation/toposts/identity-isolation/instantly breaks every incoming relative link unless every reference is updated. - Markdown vs HTML disconnect. Authors write
[Read more](../foo/index.qmd)or[Read more](../foo/), assuming the static site generator will figure out the rendered destination. If the target file or anchor does not exist in the output directory, the error is invisible until a human clicks it. - Manual clicking does not scale. A site with 15 articles, cross-references, navigation menus, and footers easily generates many internal hyperlinks. Nobody can verify them manually on every pull request.
To maintain documentation integrity, link verification must be automated as a mandatory, blocking gate in CI (see test your guardrails).
The web-repo way: lychee in CI
Modern documentation pipelines use automated link checkers such as lychee, a fast, asynchronous link validator written in Rust.
The CI step
In .github/workflows/quarto.yml, link checking executes immediately after the site renders to _site/ and before any deployment step can run:
- name: Check internal links
uses: lycheeverse/lychee-action@v2
with:
args: --offline --no-progress --root-dir "${{ github.workspace }}/_site" '_site/**/*.html'
fail: trueKey arguments in this configuration: - --offline: Instructs lychee to ignore all external HTTP/HTTPS URLs. It checks exclusively local file paths and root-relative links (/posts/...). (Note that lychee does not check #fragments by default unless --include-fragments is supplied, and our local script also ignores fragments.) - --root-dir: Sets the root directory for absolute paths. A link written as /about.html is resolved against ${{ github.workspace }}/_site/about.html. - fail: true: Configures the action to return an exit code of 1 if any broken link is found, immediately failing the PR build and preventing deployment.
What we observed in practice
On our initial CI run, lychee scanned 570 internal links across the rendered HTML files and reported 0 errors.
Because the scan runs in offline mode, it runs without sending outbound network requests. More importantly, prior to opening the PR, local checking caught an issue with directory links: relative paths pointing to a folder that had no index.html at all (for example, a link to this playbook’s GitHub templates folder). The fix was linking directly to a file (templates/README.md or SKILL.md).
Mirroring CI locally
In CI, lychee runs inside GitHub Actions. Locally, I mirror its offline check with a small script using base R and {xml2}. It scans the rendered HTML files, extracts href and src attributes, strips fragments and query strings, URL-decodes path segments, and checks that every target exists on disk (requiring folders to contain an index.html):
# Parse HTML and extract internal links
doc <- xml2::read_html(html_file, encoding = "UTF-8")
hrefs <- xml2::xml_attr(xml2::xml_find_all(doc, "//*[@href]"), "href")
srcs <- xml2::xml_attr(xml2::xml_find_all(doc, "//*[@src]"), "src")
# Skip external protocols, mailto, and anchor fragments
skip_pattern <- "^(https?:|mailto:|#|data:|javascript:|tel:)"
links <- c(hrefs, srcs)
internal_links <- links[!grepl(skip_pattern, links, ignore.case = TRUE)]Each internal link is cleaned with sub("[#?].*$", "", link) to drop fragments and query parameters, decoded with utils::URLdecode(), and resolved against either the site root (for root-relative paths starting with /) or the page’s parent directory (for relative paths).
Reading attributes with a parser matters: a regex that searches the raw HTML for href="…" also counts example links shown inside code blocks. On this very page, the full script below builds a small test site whose HTML appears as text, and a regex version of the check reported three of its example links as broken; the parser-based check correctly ignores them.
Running the check locally gives immediate feedback before opening a pull request, without requiring a containerised CI environment. The full standalone implementation is in the companion script (scripts/check-links.R).
The R way: pkgdown, bookdown, and Quarto
In the R ecosystem, documentation is compiled into static HTML across multiple frameworks: - pkgdown: Builds package documentation into the docs/ directory. - bookdown: Compiles books or long-form documentation into _book/. - R Markdown websites (rmarkdown::render_site()): Renders to _site/. - Quarto sites and books: Renders to _site/.
Because lychee and our R checker operate on standard HTML files on disk, they are completely agnostic to the generator that created them. You can add the identical check to any R package repository’s GitHub Actions workflow:
- name: Build pkgdown site
run: Rscript -e 'pkgdown::build_site()'
- name: Verify package documentation links
uses: lycheeverse/lychee-action@v2
with:
args: --offline --no-progress --root-dir "docs" 'docs/**/*.html'
fail: trueIf a vignette links to a deleted article or page, the CI build fails with the file and the broken URL before the documentation ever deploys.
Separate internal links from external links
A common mistake is attempting to check external internet links inside the same pull request check.
External link checks should never block a pull request. External web servers fail for reasons outside your control: - Temporary network timeouts and DNS glitches; - Anti-scraping firewalls returning 403 or 429 status codes; - Third-party endpoints undergoing maintenance.
If your PR gate checks external URLs, your team’s pull requests will randomly turn red due to third-party outages.
The correct architectural pattern is separation of concerns: 1. Internal links: Checked synchronously in the PR workflow with --offline and fail: true. Internal links must be fully deterministic and blocking. 2. External links: Checked asynchronously in a scheduled weekly cron workflow (e.g. schedule: [{cron: "0 9 * * 1"}]). If an external link rots, the workflow opens a GitHub issue or sends an alert without halting daily pull request merges.
Pitfalls we hit
- Checking source Markdown instead of rendered HTML. Markdown files often contain shortcodes, includes, or generated relative links that only resolve after compilation. Checking the raw Markdown produces false positive errors. Always check the rendered output directory (
_siteordocs). - Linking to directories without an
index.html. A link pointing to a folder that has noindex.htmlfile at all (such as a templates folder) fails verification. Always link to a specific target file (e.g.README.mdorSKILL.md). - Tip on fragment checking. By default, lychee’s
--offlinecheck and our local script do not validate#fragments. If you want to verify in-page header anchors, pass--include-fragmentsto lychee (we have not enabled this). - Unescaped characters in file paths. Query parameters or spaces in file names can cause path resolution to fail unless properly decoded via
utils::URLdecode().
Companion code
An offline internal link checker using base R and {xml2}. Scans rendered HTML files for href and src attributes, resolves root-relative and relative paths, validates directory targets for index.html, and reports broken references. Run with Rscript check-links.R _site or execute without arguments to run the self-contained demonstration.
check-links.R
# Offline internal link checker for rendered Quarto, pkgdown, and static HTML sites.
# Scans HTML files, extracts href and src attributes, resolves root-relative and
# relative links, and flags missing files or directory links without index.html.
#
# Usage:
# Rscript check-links.R _site
#
# Or run without arguments to execute the built-in demonstration:
# Rscript check-links.R
#' Simplify path by resolving '.' and '..' segments
#'
#' @param path Character vector of paths to simplify.
#' @return Simplified path string.
#' @keywords internal
simplify_path <- function(path) {
is_abs <- startsWith(path, "/")
parts <- strsplit(path, "/+")[[1L]]
stack <- character()
for (part in parts) {
if (part == "" || part == ".") {
next
}
if (part == "..") {
if (length(stack) > 0L && stack[length(stack)] != "..") {
stack <- stack[-length(stack)]
} else if (!is_abs) {
stack <- c(stack, part)
}
} else {
stack <- c(stack, part)
}
}
res <- paste(stack, collapse = "/")
if (is_abs) paste0("/", res) else res
}
#' Scan rendered HTML files for broken internal links
#'
#' @param site_dir Root directory of the rendered static site.
#' @return A list containing `broken` (a data frame of broken links with columns
#' `page`, `link`, and `resolved_path`) and `checked` (the total count of
#' internal links checked).
#' @export
check_links <- function(site_dir = "_site") {
if (!dir.exists(site_dir)) {
stop(
sprintf("Site directory '%s' does not exist.", site_dir),
call. = FALSE
)
}
norm_site_dir <- normalizePath(site_dir, winslash = "/", mustWork = TRUE)
html_files <- list.files(
norm_site_dir,
pattern = "\\.html$",
recursive = TRUE,
full.names = TRUE
)
bad_pages <- character()
bad_links <- character()
bad_paths <- character()
n_checked <- 0L
# Skip external protocols, anchor fragments, data URIs, and scripts
skip_pattern <- "^(https?:|mailto:|#|data:|javascript:|tel:)"
for (html_file in html_files) {
norm_html <- normalizePath(html_file, winslash = "/", mustWork = TRUE)
rel_page <- substring(norm_html, nchar(norm_site_dir) + 2L)
html_dir <- dirname(norm_html)
doc <- tryCatch(
xml2::read_html(norm_html, encoding = "UTF-8"),
error = function(e) NULL
)
if (is.null(doc)) {
next
}
href_nodes <- xml2::xml_find_all(doc, "//*[@href]")
hrefs <- xml2::xml_attr(href_nodes, "href")
src_nodes <- xml2::xml_find_all(doc, "//*[@src]")
srcs <- xml2::xml_attr(src_nodes, "src")
raw_links <- c(hrefs, srcs)
raw_links <- raw_links[!is.na(raw_links) & nzchar(trimws(raw_links))]
for (u in raw_links) {
u_trim <- trimws(u)
if (grepl(skip_pattern, u_trim, ignore.case = TRUE)) {
next
}
# Drop #fragment and ?query
clean_u <- sub("[#?].*$", "", u_trim)
p <- tryCatch(
utils::URLdecode(clean_u),
error = function(e) clean_u
)
if (!nzchar(p)) {
next
}
n_checked <- n_checked + 1L
# Resolve root-relative vs relative path
if (startsWith(p, "/")) {
rel_p <- sub("^/+", "", p)
target_path <- file.path(norm_site_dir, rel_p)
} else {
target_path <- file.path(html_dir, p)
}
norm_target <- simplify_path(target_path)
# Check target existence: a folder link must contain index.html
is_valid <- if (dir.exists(norm_target)) {
idx <- file.path(norm_target, "index.html")
file.exists(idx) && !dir.exists(idx)
} else {
file.exists(norm_target)
}
if (!is_valid) {
bad_pages <- c(bad_pages, rel_page)
bad_links <- c(bad_links, u)
bad_paths <- c(bad_paths, norm_target)
}
}
}
broken_df <- data.frame(
page = bad_pages,
link = bad_links,
resolved_path = bad_paths,
stringsAsFactors = FALSE
)
attr(broken_df, "checked") <- n_checked
list(
broken = broken_df,
checked = n_checked
)
}
#' Run demonstration on a temporary mock site
#' @return A list containing `broken` and `checked`.
#' @export
run_link_demo <- function() {
demo_dir <- file.path(tempdir(), paste0("link_demo_", Sys.getpid()))
dir.create(demo_dir, recursive = TRUE, showWarnings = FALSE)
on.exit(unlink(demo_dir, recursive = TRUE), add = TRUE)
# 1. Target with encoded space (valid target)
writeLines(
"<!DOCTYPE html><html><body>Target with space</body></html>",
file.path(demo_dir, "my file.html")
)
# 2. Folder without index.html (broken directory target)
templates_dir <- file.path(demo_dir, "templates")
dir.create(templates_dir, recursive = TRUE, showWarnings = FALSE)
writeLines("plain text", file.path(templates_dir, "README.txt"))
# 3. Main HTML page with:
# - one broken link ("missing.html")
# - one folder link without index.html ("templates/")
# - one encoded space ("my%20file.html")
writeLines(
c(
"<!DOCTYPE html>",
"<html>",
"<head><title>Link Checker Demo</title></head>",
"<body>",
' <a href="missing.html">Missing Page</a>',
' <a href="templates/">Templates Folder</a>',
' <a href="my%20file.html">File with Space</a>',
"</body>",
"</html>"
),
file.path(demo_dir, "index.html")
)
check_links(demo_dir)
}
# Run demo or check CLI directory when invoked directly as a script
if (sys.nframe() == 0L) {
args <- commandArgs(trailingOnly = TRUE)
if (length(args) > 0L) {
target_dir <- args[1L]
if (!dir.exists(target_dir)) {
cat(
sprintf("Error: Directory '%s' does not exist.\n", target_dir),
file = stderr()
)
quit(save = "no", status = 1L)
}
cat(sprintf("Checking internal links in '%s'...\n", target_dir))
report <- check_links(target_dir)
} else {
cat("Running offline link check demonstration in temporary directory...\n")
report <- run_link_demo()
}
cat(sprintf(
"Checked %d internal links; broken: %d\n",
report$checked,
nrow(report$broken)
))
if (nrow(report$broken) > 0L) {
for (i in seq_len(min(50L, nrow(report$broken)))) {
cat(sprintf(
" [%s] %s -> %s\n",
report$broken$page[i],
report$broken$link[i],
report$broken$resolved_path[i]
))
}
quit(save = "no", status = 1L)
} else {
cat("All internal links resolved successfully.\n")
quit(save = "no", status = 0L)
}
}Sources
Link checking and CI tools
- lychee: lychee.cli.rs
- lychee-action: github.com/lycheeverse/lychee-action
R package documentation
- xml2: xml2.r-lib.org
- pkgdown: pkgdown.r-lib.org
- 2026-09-26: Removed the end-of-post checklist.
- 2026-09-27: Clarified directory link recommendations.
- 2026-09-27: Replaced the Python script with an R link checker ({xml2}) and added companion code.