Build a Link Checker With Node.js
Build a link checker in Node.js: extract links, try HEAD then GET, limit concurrency, handle redirects and timeouts, and exit non-zero on broken links.

Broken links accumulate quietly. A page you published two years ago points at a blog that moved, a docs URL that was reorganized, a repository that was deleted. Readers hit a 404 and lose trust, and search engines notice too. A link checker finds them before readers do, and in Node.js it is a pleasant small project because the global fetch, AbortSignal.timeout and URL are all built in. This post builds one in three steps: extract the links, check one link correctly, then check many with limited concurrency. It targets Node.js 26 'Lithium', LTS since 2026-10-28, and runs the same on the Node.js 24 and 22 maintenance lines. There are no dependencies.
What a correct check involves
Checking a link sounds like "fetch it and look at the status". Four details decide whether the results are trustworthy.
Relative links must be resolved against the page's base URL, and only
httpandhttpslinks are checkable, somailto:andjavascript:must be skipped.A
HEADrequest is cheaper thanGETbecause the server sends no body, but some servers answerHEADwith405 Method Not Allowedor501. The checker should retry those withGET.Redirects are normal. The fetch standard follows them by default, so the final status is the target's, and
response.redirectedtells you it happened. A link that redirects is worth reporting because it should be updated.Every request needs a timeout. Without one, a server that accepts a connection and never replies stalls the whole run.
Concurrency is the fifth concern, and it is a courtesy as much as a speed-up: checking four hundred links one at a time is slow, and checking them all at once opens four hundred connections, possibly to the same host. A small pool, such as five at a time, is a reasonable middle.
Extracting links
A regular expression is not a general HTML parser, and for production crawling you would use one. For checking the pages you control, where anchors look like <a href="...">, a focused pattern is enough, and it keeps the post dependency-free. The function resolves each match against the base URL, drops fragments so /page#top and /page count once, filters protocols and removes duplicates.
export function extractLinks(html, base) {
const found = new Set();
for (const match of html.matchAll(/<a\s[^>]*href="([^"]+)"/gi)) {
let url;
try {
url = new URL(match[1], base);
} catch {
continue;
}
if (url.protocol !== "http:" && url.protocol !== "https:") continue;
url.hash = "";
found.add(url.href);
}
return [...found];
}
const html = `
<a href="/docs">Docs</a>
<a href="/docs#install">Install</a>
<a class="x" href="https://nodejs.org/api/fs.html">fs</a>
<a href="mailto:[email protected]">Mail</a>
<a href="guide/start">Start</a>
`;
for (const link of extractLinks(html, "https://example.com/handbook/")) {
console.log(link);
}The base is https://example.com/handbook/. The absolute path /docs resolves against the origin. The second link differs only by its fragment, so after the hash is removed it duplicates the first and the Set drops it. The mailto: link is filtered. The relative guide/start resolves against the base directory, which ends in a slash, so it lands under /handbook/.
https://example.com/docs
https://nodejs.org/api/fs.html
https://example.com/handbook/guide/startChecking one link
The check function returns a small result object rather than throwing, because a broken link is an expected outcome and not an error in the checker. It tries HEAD, falls back to GET when the server rejects the method, and maps a timeout to a readable status.
export async function checkLink(url, { timeoutMs = 5000 } = {}) {
async function attempt(method) {
return fetch(url, { method, redirect: "follow", signal: AbortSignal.timeout(timeoutMs) });
}
try {
let res = await attempt("HEAD");
if (res.status === 405 || res.status === 501) res = await attempt("GET");
return { url, status: res.status, redirected: res.redirected };
} catch (err) {
return { url, status: err.name === "TimeoutError" ? "timeout" : "error", redirected: false };
}
}A fetch that rejects does so for a network failure, a DNS error or a timeout. AbortSignal.timeout aborts with a TimeoutError, and checking err.name is how you tell it apart from a refused connection, which arrives as a TypeError. A 404 is not an exception at all: fetch resolves with the response, and you read status. That difference is why a naive try/catch checker misses every 404.
One limit to know: some sites answer automated requests with 403 or 429 however valid the link is. Those results mean "could not verify", not "broken", and a real checker lets you configure a user agent and a list of hosts to skip.
Checking many with a pool
The pool is a few lines. It starts limit workers, and each worker keeps taking the next index until none is left. Results are written to the slot for their index, so the output order matches the input order even though the checks finish in any order.
The demo below starts its own small server on a free port, so it needs no internet and the output is deterministic. The server has five routes: one that works, one missing, one that redirects, one that rejects HEAD, and one that never answers.
import { createServer } from "node:http";
import { checkLink } from "./check.js";
async function mapLimit(items, limit, fn) {
const results = new Array(items.length);
let next = 0;
async function worker() {
while (next < items.length) {
const i = next++;
results[i] = await fn(items[i]);
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
return results;
}
const server = createServer((req, res) => {
if (req.url === "/ok") res.writeHead(200).end("ok");
else if (req.url === "/old") res.writeHead(301, { location: "/ok" }).end();
else if (req.url === "/nohead") {
if (req.method === "HEAD") res.writeHead(405).end();
else res.writeHead(200).end("fine");
} else if (req.url === "/slow") {
return;
} else res.writeHead(404).end();
});
await new Promise((resolve) => server.listen(0, resolve));
const base = `http://127.0.0.1:${server.address().port}`;
const paths = ["/ok", "/missing", "/old", "/nohead", "/slow"];
const results = await mapLimit(paths.map((p) => base + p), 3, (u) =>
checkLink(u, { timeoutMs: 300 }),
);
let broken = 0;
for (const r of results) {
const path = new URL(r.url).pathname;
const bad = r.status === "timeout" || r.status === "error" || r.status >= 400;
if (bad) broken += 1;
console.log(`${r.status} ${path}${r.redirected ? " (redirected)" : ""}`);
}
console.log(`${broken} broken of ${results.length}`);
server.closeAllConnections();
server.close();
process.exitCode = broken > 0 ? 1 : 0;Walk through each route. /ok answers 200. /missing falls through to the final branch and returns 404. /old returns 301 to /ok, fetch follows it, and the final response is 200 with redirected set. /nohead rejects HEAD with 405, the checker retries with GET, and the server answers 200. /slow never calls res.end, so the request waits until the 300 ms timeout fires and the result is timeout. Two links are broken, and the exit code becomes 1.
200 /ok
404 /missing
200 /old (redirected)
200 /nohead
timeout /slow
2 broken of 5The exit code is what makes this usable in CI. A build step that runs the checker fails when anything is broken, which turns link rot into a visible failing check instead of a surprise.
Using it on real sites
To point the checker at real pages, fetch each page's HTML, call extractLinks with the page URL as the base, and feed the combined, deduplicated list to mapLimit. Keep a few practices in mind. Check internal links separately from external ones, since internal breakage is your bug and external breakage may be temporary. Retry a failed external link once later before reporting it, because a single timeout is weak evidence. Respect robots.txt and rate limits when you check someone else's site, and keep the concurrency low per host. Cache results between runs, so a nightly job does not re-check the same stable URLs.
Where this checker stops
The regular expression sees only double-quoted href attributes in anchor tags. It misses single-quoted attributes, links in <link> and <img> tags, and anything a script inserts after load. It does not verify that a fragment such as #install exists on the target page. And it treats any 2xx as healthy, so a "soft 404" page that returns 200 with a not-found message passes. For single-page applications that render links in the browser, drive a real browser instead. For static sites and markdown-derived HTML, this checker is a good start.
Running it in CI and keeping it quiet
A checker that cries wolf gets ignored, so tune it before you wire it into a pipeline. Keep an allowlist file of URLs or hosts to skip, such as sites that block automated requests or links that only work behind a login. Print broken links grouped by the page that contains them, because the person fixing the problem needs to know where to edit, not only which URL failed. Include the status in the report, so a team can tell a permanent 404 from a 500 that may clear by itself.
Retries deserve a policy. A single timeout is weak evidence, so recheck failures once after the main run, with a longer timeout, and report only those that fail twice. Do not retry a 404, which is a definite answer. When you check your own site from CI, point at a staging build of it, so a failing link means the change under review broke something and not that production was briefly slow.
Respect the sites you check. Send a descriptive user-agent header so owners can identify the traffic, keep concurrency low per host, and honor 429 responses and their retry-after header. A nightly job over a few hundred links is polite. A job that hammers one host with dozens of parallel requests is not. If your link list is long, spread checks for the same host apart, for example by grouping URLs by hostname and giving each group its own small pool.
For internal links, skip the network entirely when you can. If your site is generated from files, resolve each relative link against the output folder and check that the target file exists, which is faster, deterministic and catches mistakes before deployment.


