Skip to content
Linux Running · 8 min read

Bulk-Checking 149 Websites for SSL Errors, Redirects and Parked Domains with Node.js

A dependency-free Node.js script that checked 149 listing websites for TLS errors, redirect chains, parked domains and wrong links. Code, results, gotchas.

A local directory app I maintain for a client has 206 accommodation listings. 149 of them have a website link. Nobody had looked at those links in a while, and that is exactly how a directory rots: hotels change domains, certificates expire, domains get dropped and bought by someone selling something very different. The user taps "Website" and lands on garbage, and the app looks bad, not the hotel.

So I checked all of them in one run. No crawler service, no npm packages, just Node.js and its built-in https, http and tls modules.

TL;DR: 12 parallel workers, 15 second timeout, redirects followed by hand (max 8) so you get the full chain, a retry without certificate validation when the error looks like TLS so you can still classify the site, a separate tls.connect() to read expiry and issuer, a regex for parked and for-sale pages, and a name check against title, host and body to catch links that work but point to the wrong business. Result: 127 ok, 22 with some kind of problem, 57 listings without any website.

The script

This is the important part, translated and trimmed from what I actually ran. Input is a JSON array of { id, name, web }.

// check-sites.mjs: reachability, TLS, redirects, title, parked/wrong-site heuristics
import https from 'node:https';
import http from 'node:http';
import tls from 'node:tls';
import { readFileSync, writeFileSync } from 'node:fs';

const [, , input, output] = process.argv;
const list = JSON.parse(readFileSync(input, 'utf8'));
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36';

function fetchUrl(url, insecure, hopsLeft = 8) {
  return new Promise((resolve) => {
    let u;
    try { u = new URL(url); } catch { return resolve({ error: 'INVALID_URL', chain: [url] }); }
    const mod = u.protocol === 'https:' ? https : http;
    const req = mod.get(u, {
      headers: { 'User-Agent': UA, Accept: 'text/html,*/*' },
      rejectUnauthorized: !insecure,
      timeout: 15000,
    }, (res) => {
      const loc = res.headers.location;
      if (res.statusCode >= 300 && res.statusCode < 400 && loc && hopsLeft > 0) {
        res.resume();
        const next = new URL(loc, u).toString();
        return fetchUrl(next, insecure, hopsLeft - 1)
          .then((r) => resolve({ ...r, chain: [url, ...(r.chain || [])] }));
      }
      let body = '';
      res.setEncoding('utf8');
      res.on('data', (c) => { if (body.length < 300000) body += c; });
      res.on('end', () => resolve({ status: res.statusCode, final: url, body, chain: [url] }));
      res.on('error', (e) => resolve({ error: e.code || e.message, chain: [url] }));
    });
    req.on('timeout', () => req.destroy(new Error('TIMEOUT')));
    req.on('error', (e) => resolve({ error: e.code || e.message, chain: [url] }));
  });
}

function certInfo(host) {
  return new Promise((resolve) => {
    const s = tls.connect({ host, port: 443, servername: host, rejectUnauthorized: false, timeout: 10000 }, () => {
      const c = s.getPeerCertificate();
      resolve({ validTo: c.valid_to, issuer: c.issuer?.O || c.issuer?.CN, authorized: s.authorized, reason: s.authorizationError });
      s.end();
    });
    s.on('error', (e) => resolve({ reason: e.code }));
    s.on('timeout', () => { s.destroy(); resolve({ reason: 'TIMEOUT' }); });
  });
}

Then the heuristics and the classifier:

const TLS_ERR = /CERT|SSL|TLS|SELF_SIGNED|UNABLE_TO_VERIFY|ALTNAME|EPROTO/i;
const PARKED = /(domain (is )?for sale|this domain|domain parked|hugedomains|sedo|parkingcrew|bodis|under construction|coming soon|casino|slot|betting)/i;
const host = (u) => { try { return new URL(u).hostname.replace(/^www\./, ''); } catch { return ''; } };
const flat = (s) => s.toLowerCase().normalize('NFD').replace(/\p{Diacritic}/gu, '');
const title = (b) => (b.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1] || '').replace(/\s+/g, ' ').trim().slice(0, 140);
// significant words of the listing name, minus generic ones
const nameWords = (n) => flat(n)
  .replace(/\b(hotel|guesthouse|pension|apartments?|haus|chalet|the|and)\b/g, ' ')
  .split(/[^a-z0-9]+/).filter((w) => w.length >= 4);

async function check(e) {
  const r = { id: e.id, name: e.name, web: e.web };
  if (!e.web) return { ...r, result: 'no website' };

  let a = await fetchUrl(e.web, false);
  let tlsProblem = null;
  if (a.error && TLS_ERR.test(a.error)) {
    tlsProblem = a.error;                 // remember the real error...
    a = await fetchUrl(e.web, true);      // ...then look at the site anyway
  }
  r.status = a.status ?? null;
  r.error = a.error ?? null;
  r.final = a.final ?? null;
  r.chain = (a.chain || []).join(' -> ');

  const finalUrl = a.final || e.web;
  if (finalUrl.startsWith('https')) {
    const c = await certInfo(new URL(finalUrl).hostname);
    r.certValidTo = c.validTo || null;
    r.certIssuer = c.issuer || null;
    if (!c.authorized && c.reason) tlsProblem = tlsProblem || c.reason;
  }
  if (a.final?.startsWith('http:')) {    // http only: does https work at all?
    const h = await fetchUrl(a.final.replace(/^http:/, 'https:'), false, 3);
    if (!h.status && h.error && TLS_ERR.test(h.error)) tlsProblem = tlsProblem || `http only, https: ${h.error}`;
  }
  r.tls = tlsProblem;

  const body = a.body || '';
  r.title = title(body);
  const words = nameWords(e.name);
  const text = flat(r.title + ' ' + host(finalUrl) + ' ' + body.slice(0, 200000).replace(/<[^>]+>/g, ' '));
  r.nameFound = words.length ? (words.some((w) => text.includes(w)) ? 'yes' : 'no') : 'n/a';
  r.parked = PARKED.test(r.title) || (body.length < 3000 && PARKED.test(body));

  if (a.error) r.result = /ENOTFOUND|EAI_AGAIN/.test(a.error) ? 'domain does not exist' : `unreachable (${a.error})`;
  else if (r.status >= 400) r.result = `HTTP ${r.status}`;
  else if (r.parked) r.result = 'parked / foreign';
  else if (r.nameFound === 'no') r.result = 'possibly wrong website';
  else if (tlsProblem) r.result = 'SSL problem';
  else if (a.final?.startsWith('http:')) r.result = 'ok, but no HTTPS';
  else r.result = 'ok';
  if (tlsProblem && r.result !== 'SSL problem') r.result += ' + SSL problem';
  return r;
}

const out = new Array(list.length);
let i = 0;
await Promise.all(Array.from({ length: 12 }, async () => {
  while (i < list.length) { const k = i++; out[k] = await check(list[k]); process.stderr.write('.'); }
}));
writeFileSync(output, JSON.stringify(out, null, 1));
const counts = {};
out.forEach((x) => { counts[x.result] = (counts[x.result] || 0) + 1; });
console.log('\n', counts);

Run it:

node check-sites.mjs listings.json results.json

The worker pool at the bottom is the poor man's p-limit: 12 async loops pull the next index from a shared counter. JavaScript is single threaded, so i++ can't race. For 149 URLs, 12 workers was plenty, and few enough that no single host gets hammered.

What came out

ok                                    127
no website                             57
SSL problem                             6
domain does not exist + SSL problem     2
ok, but no HTTPS                        4
parked / foreign                        1
HTTP 403                                3
possibly wrong website                  4
domain does not exist                   1
HTTP 404                                1

The real TLS errors were the usual suspects: ERR_TLS_CERT_ALTNAME_INVALID (the certificate is for some other hostname, typically the hosting provider's default cert) and CERT_HAS_EXPIRED. One "SSL problem" site was worse than it sounds: http answered with a hosting "Domain Default page", https with an expired cert. Technically reachable, practically empty.

Among the broken ones: a listing whose domain now belongs to an online casino, two domains that no longer exist at all while the business had moved to a new domain, and one deep link to a subpage that returns 404 while the homepage works fine.

Gotcha: rejectUnauthorized: false hides the thing you're looking for

The tempting shortcut is to run everything with rejectUnauthorized: false so nothing fails. Then every broken cert looks like a happy 200. The script does the opposite: first request with validation on, keep the error code, and only then retry insecure so you can still read the title and the body. You want both facts: "the cert is broken" and "behind it is the right hotel".

The separate tls.connect() keeps the certificate check independent of the HTTP request and its redirects: one connection to the final host, nothing else. With getPeerCertificate() you get valid_to and the issuer, which went into the spreadsheet as its own column. Good for spotting certs that are about to expire, not just the ones already dead.

Gotcha: the TLS error can sit behind a redirect

Plenty of listings had http:// links. The http site answers with a 301 to https, and the https side is broken. If you only check the URL as stored, it looks fine until the redirect. That's why the cert check runs on the final host of the chain, not the original one, and why http-only results get an extra https probe.

The "domain does not exist + SSL problem" combo comes from the same flow: first request fails on the certificate, the insecure retry follows the chain and ends at a hostname that doesn't resolve.

This is the part I didn't expect to matter as much. A parked domain returns 200. A casino returns 200. A hosting default page returns 200. So there are two extra checks:

  • Parked/foreign: a regex over the title, and over the body only if the page is tiny (under 3000 bytes). Running "casino" against a full hotel homepage would be asking for false positives.
  • Name match: strip the generic words ("hotel", "pension", "apartments") from the listing name, keep words with 4+ letters, and look for any of them in title, hostname and body text. No match means "possibly wrong website". Crude, but it flagged 4 links, and you check those 4 by hand instead of 149.

The normalize plus \p{Diacritic} trick matters for non-English names. "Gästehaus" and "gaestehaus" are the same thing to a human, not to includes().

Gotcha: 403 is usually a bot wall, not a dead site

The three HTTP 403 results were bot protection on the hotel sites, which blocked my automated check. A browser user agent helps sometimes, not always. Don't mark those as broken. Put them on a "open once in a real browser" list.

Finding the right websites

After the scan I searched for the correct website for the 73 problem cases. 35 got a working address: 32 new or corrected, 3 where the existing link turned out to be right after all. 38 had no website of their own I could find. Every one of the 35 was fetched again at the end, and all of them returned 200. Never paste a "found" URL into production without that second check.

Everything went into an Excel file:

  • Overview: count per category
  • All listings: all 206 entries, color-coded, with result, final URL, SSL error, cert expiry and page title
  • Research: the 73 cases with the URL found, an alternative, a confidence level, the source and a note

23 corrected websites then went live through the app's admin panel, which writes to a corrections table the app reads at startup, so no new app build was needed. The remaining 51 went into a "still open" tab, then into a checklist for the client with columns to fill in, because things like "is this guesthouse still open?" are not something a script can answer.

Not every SSL problem got "fixed". Three working sites still only run over http. They're the right sites, the owners just never set up a valid certificate. Linking the http URL beats linking nothing.

Would I do it again like this?

Yes. Zero dependencies means it runs anywhere Node runs, today and in two years. The whole thing is one file you can read in five minutes. Link rot in a directory is the same problem as dead backups: nothing tells you, it just gets worse quietly, which is why I wrote about checking that backups are actually fresh too.

If you want this continuously instead of once, an uptime tool with certificate expiry alerts covers the "is it up" part, see my Uptime Kuma setup. It won't tell you a domain now sells casino bonuses though. For the cert side of your own servers, the expired Let's Encrypt cleanup is the other end of the same story, and if you wonder how much of your traffic is bots like this script, here's how I split bots from real readers.


Related posts