Scheduled broken-link and redirect checks that tell you the moment a link breaks — linkbruno.com

There's a detail about npm that surprises a lot of package authors: the README shown on npmjs.com is the one from the published tarball. It doesn't update when you fix your GitHub README. If version 2.3.1 shipped with a broken link to the docs, every visitor to the package page sees that broken link until you publish 2.3.2.

The same goes for the URLs in package.json: homepage, repository, bugs and funding are shown in the package page sidebar, used by npm docs and npm bugs, and read by tools that build dependency reports. A typo there is a broken link in thousands of places at once.

So the right moment to check those links is just before npm publish. Here's a small script that does it.

What to check

  1. Every absolute URL in the README. Documentation, badges, examples, license, changelog.
  2. Relative links in the README. This is the big one, covered below.
  3. package.json URL fields: homepage, repository.url, bugs.url (or bugs as a string), and funding (string, object or array).
  4. Images. Badge services change URLs; screenshots stored in a branch that got renamed stop loading.

The relative-link trap

On GitHub, a README link like [Configuration](docs/config.md) or ![demo](assets/demo.gif) resolves relative to the repo. On npmjs.com, it's resolved against the package page, or against the repository URL if npm can work one out, depending on the link and the npm website's current rendering rules. It's often not where you intended, and files that aren't in the published tarball (docs/, assets/, anything in .npmignore or not in files) can't be served from the package at all.

The safe approach is to use absolute URLs in the README for anything that must work on npm. Link to a docs site, or to a specific tag on GitHub (https://github.com/OWNER/REPO/blob/v2.3.1/docs/config.md) so the link matches the published version. The script below flags any relative link so you can make that choice deliberately.

The script

Save as scripts/check-links.mjs. It needs Node 18 or later (for the built-in fetch) and no dependencies.

import { readFile } from "node:fs/promises"; const pkg = JSON.parse(await readFile("package.json", "utf8")); const readme = await readFile("README.md", "utf8"); const urls = new Map(); // url -> where it came from const add = (u, from) => u && urls.set(u.replace(/^git\+/, "").replace(/\.git$/, ""), from); add(pkg.homepage, "package.json homepage"); add(typeof pkg.repository === "string" ? null : pkg.repository?.url, "package.json repository"); add(typeof pkg.bugs === "string" ? pkg.bugs : pkg.bugs?.url, "package.json bugs"); for (const f of [pkg.funding].flat().filter(Boolean)) add(typeof f === "string" ? f : f.url, "package.json funding"); const relative = []; // Markdown links/images and HTML href/src attributes const re = /\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)|(?:href|src)=["']([^"']+)["']/g; for (const m of readme.matchAll(re)) { const u = m[1] || m[2]; if (/^https?:\/\//.test(u)) add(u, "README"); else if (!u.startsWith("#") && !u.startsWith("mailto:")) relative.push(u); } async function check(url) { for (const method of ["HEAD", "GET"]) { try { const res = await fetch(url, { method, redirect: "follow", signal: AbortSignal.timeout(15000), headers: { "user-agent": "pkg-link-check/1.0" } }); if (res.ok || res.status === 429) return [res.status, res.url]; if (method === "GET") return [res.status, res.url]; } catch (e) { if (method === "GET") return [0, String(e.cause?.code || e.name)]; } } } let failed = 0; const results = await Promise.all([...urls].map(async ([u, from]) => [u, from, ...(await check(u))])); for (const [u, from, status, final] of results) { const bad = status === 0 || status >= 400; if (bad) failed++; console.log(`${bad ? "FAIL" : "ok "} ${status} ${u} (${from})${final && final !== u ? ` -> ${final}` : ""}`); } for (const r of relative) console.log(`WARN relative link in README: ${r}`); if (failed) { console.error(`\n${failed} broken link(s)`); process.exit(1); } 

The script tries HEAD first and falls back to GET, because many servers answer HEAD with 404 or 405 even when the page is fine. It treats 429 (rate limited) as success, since that means the server is up. Redirects are followed and the final URL printed, which catches the common case of a repository URL that redirects after the project was renamed.

The README isn't the only place a package link can break. linkbruno.com keeps checking those URLs after publish, so a dead homepage or docs link doesn't sit unnoticed.

Run it before every publish

Add it to package.json:

{ "scripts": { "check-links": "node scripts/check-links.mjs", "prepublishOnly": "npm run check-links" } } 

prepublishOnly runs on npm publish and stops the publish if the script exits with an error. It doesn't run on npm install, so it won't bother your users.

If you publish from CI, run the same script in the release workflow, before the publish step. You might also want a weekly scheduled run on the main branch: links in the README can break between releases, and it's better to fix them in the next release than to find out from an issue.

Check what's actually in the tarball

The README you check should be the one that gets published. Two quick commands:

npm pack --dry-run # lists every file that would be published npm pack && tar -xzf *.tgz && cat package/README.md 

If you generate the README at build time, or your files field excludes it by accident, this is where you'll notice.

Other places your package's links live

  • The bin script's --help text and error messages often contain URLs. They ship in the tarball and live as long as the version stays installed.
  • The CHANGELOG, if you publish it. Links to issues and pull requests are usually stable; links to blog posts and docs pages aren't.
  • JSDoc @see and @link tags, which editors show on hover.

For the docs site those links point to, a scheduled crawl from something like linkbruno.com covers the other half: making sure the pages your package sends people to still exist.

Related reading

Have you ever shipped a package with a broken README link and had to publish a patch release just to fix it? I suspect most maintainers have.