Measuring an og:image Without Downloading It: HEAD, Range Requests and a Small Tested Node Probe
When a link card shows no picture, or shows it late, the first question I ask is how big the image file is. Not the pixel size, the byte size. A 1200x630 PNG can be 80 KB or 2 MB depending on how it was exported, and cha
When a link card shows no picture, or shows it late, the first question I ask is how big the image file is. Not the pixel size, the byte size. A 1200x630 PNG can be 80 KB or 2 MB depending on how it was exported, and chat apps and crawlers are not patient with the second kind.
Checking this by hand means opening the page source, finding og:image, pasting the URL into a new tab and looking at the file size in the network panel. That is fine once. It is not fine for thirty pages. So I wrote a small Node script that does the whole routine, and this post walks through it, including the parts that went wrong the first time I tested it.
The aim is narrow: given a page URL, find its og:image, then learn the status, content type and byte size of that image while downloading as little as possible. It uses only Node's built-in fetch, so there is nothing to install.
Why not just download the image?
You can, and for a single check it is the simplest honest answer. But a page check often runs in a deploy pipeline over many URLs, and some share images are large on purpose (the broken ones). Downloading every file in full is slow and wasteful when the question is only "how many bytes?".
HTTP gives us two cheap ways to ask:
-
HEAD returns the same headers a GET would, with no body. If the response has
Content-Length, you have the size. -
A Range request (
Range: bytes=0-0) asks for just the first byte. A server that supports ranges answers206 Partial Contentwith aContent-Range: bytes 0-0/48213header, and the number after the slash is the full size.
Neither is guaranteed. Some servers and CDNs answer HEAD with 405 or leave out Content-Length. Some ignore Range and send the whole file anyway. A probe that trusts either one blindly will report wrong sizes, so the script has a fallback ladder:
- Try HEAD. If it is OK and has a usable
Content-Length, stop. - Otherwise send
GETwithRange: bytes=0-0. If the answer is206with aContent-Rangetotal, use that. - If the server ignored the range and is sending the whole body, count bytes as they stream in and cancel the download once a limit is passed, reporting "at least N bytes".
Finding the og:image first
The probe starts from a page, not an image URL. The page HTML has to be read to find the tag, and attribute order varies between sites: <meta property="og:image" content="..."> on one, <meta content="..." property="og:image"> on another. Matching each <meta> tag separately and then looking at its attributes avoids depending on the order.
The value can also be just a path, such as /img/share.png. A crawler resolves that against the page URL (or fails, depending on the app), so the script resolves it the same way with new URL(value, pageUrl) and, in the report, shows the absolute address that was actually probed. If your page uses a path-only og:image, that is a finding in itself: the guide to og:image sizes and files and the explanation of what an og:image is both recommend using a full absolute address.
The script
// probe-share-image.mjs - find og:image on a page, then measure the image without downloading all of it.
// Node 18+ (global fetch). No dependencies.
const UA = "share-image-probe/1.0 (+personal tool)";
export function findOgImage(html, pageUrl) {
// Look at <meta ...> tags one by one so attribute order does not matter.
for (const tag of html.match(/<meta\b[^>]*>/gi) ?? []) {
const prop = /\b(?:property|name)\s*=\s*["']og:image["']/i.test(tag);
if (!prop) continue;
const m = tag.match(/\bcontent\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
if (m) return new URL((m[1] ?? m[2]).trim(), pageUrl).href; // resolves a path-only value too
}
return null;
}
async function readUpTo(res, limit) {
// Count bytes of a body, but stop (and cancel the download) once we pass `limit`.
const reader = res.body.getReader();
let total = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) return { bytes: total, complete: true };
total += value.length;
if (total > limit) { await reader.cancel(); return { bytes: total, complete: false }; }
}
}
export async function probeImage(url, { limit = 5 * 1024 * 1024, timeoutMs = 8000 } = {}) {
const notes = [];
const opts = (extra = {}) => ({ redirect: "follow", signal: AbortSignal.timeout(timeoutMs),
headers: { "user-agent": UA, ...extra.headers }, method: extra.method ?? "GET" });
let res = await fetch(url, opts({ method: "HEAD" }));
let method = "HEAD";
let bytes = Number(res.headers.get("content-length"));
let atLeast = false;
if (!res.ok || !Number.isFinite(bytes) || bytes <= 0) {
// Some servers refuse HEAD or leave out Content-Length. Ask for one byte instead.
notes.push(`HEAD gave status ${res.status} and no usable length; retrying with Range`);
res = await fetch(url, opts({ headers: { range: "bytes=0-0" } }));
method = "GET Range";
const cr = res.headers.get("content-range"); // e.g. "bytes 0-0/48213"
const total = cr && cr.match(/\/(\d+)$/);
if (res.status === 206 && total) {
bytes = Number(total[1]);
await res.body?.cancel();
} else if (res.ok) {
notes.push("server ignored Range; counting bytes up to the limit");
const r = await readUpTo(res, limit);
bytes = r.bytes; atLeast = !r.complete;
method = "GET (counted)";
} else {
bytes = NaN;
}
} else {
await res.body?.cancel();
}
const contentType = (res.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
const problems = [];
if (!res.ok && res.status !== 206) problems.push(`status ${res.status}`);
if (!contentType.startsWith("image/")) problems.push(`content-type is "${contentType || "missing"}", not an image`);
return { url, finalUrl: res.url, status: res.status, contentType, bytes, atLeast, method, notes, problems };
}
export function verdict(r, { warnAtBytes = 300 * 1024 } = {}) {
const out = [...r.problems];
if (Number.isFinite(r.bytes) && r.bytes > warnAtBytes)
out.push(`${Math.round(r.bytes / 1024)} KB${r.atLeast ? "+" : ""} is over your ${Math.round(warnAtBytes / 1024)} KB budget`);
return out;
}
export async function checkPage(pageUrl, options) {
const res = await fetch(pageUrl, { redirect: "follow", signal: AbortSignal.timeout(8000), headers: { "user-agent": UA } });
if (!res.ok) return { pageUrl, error: `page returned ${res.status}` };
const image = findOgImage(await res.text(), res.url);
if (!image) return { pageUrl, error: "no og:image tag found" };
const probe = await probeImage(image, options);
return { pageUrl, image, probe, issues: verdict(probe, options) };
}
if (import.meta.url === `file://${process.argv[1]}`) {
const pages = process.argv.slice(2);
if (!pages.length) { console.error("usage: node probe-share-image.mjs <page-url> [more urls]"); process.exit(2); }
let bad = 0;
for (const p of pages) {
const r = await checkPage(p).catch((e) => ({ pageUrl: p, error: e.message }));
if (r.error) { bad++; console.log(`FAIL ${p}\n ${r.error}`); continue; }
const kb = Number.isFinite(r.probe.bytes) ? `${Math.round(r.probe.bytes / 1024)} KB` : "unknown size";
console.log(`${r.issues.length ? "WARN" : "OK "} ${p}\n ${r.image}\n ${r.probe.contentType || "?"}, ${kb}, via ${r.probe.method}`);
for (const i of r.issues) { bad++; console.log(` - ${i}`); }
}
process.exit(bad ? 1 : 0);
}
A few choices are worth explaining.
redirect: "follow" and finalUrl. Image URLs often redirect, for example from an http:// address to https://, or from a short path to a CDN. The probe follows them and keeps res.url, so the report shows where the file really lives.
The content-type check. A very common failure is a URL that answers 200 OK but returns an HTML error page, such as a "not found" page served with the wrong status. The size looks plausible, the status is fine, and the card is still blank. Checking that content-type starts with image/ catches it.
The budget is yours to set. The default warning is 300 KB. That is my own rule of thumb for keeping share images light, not a published limit from any platform, so verdict() takes a warnAtBytes option. Change it to whatever your team agrees on.
AbortSignal.timeout. Every request has a time limit. A probe that can hang on one slow image host is a probe nobody wants in a pipeline.
Tests with a local server
Network code is easy to get subtly wrong, so the tests start a tiny http server on a random port with one route for each situation I care about: an image that answers HEAD properly, one that refuses HEAD but supports ranges, one that refuses HEAD and ignores ranges, a redirect, an HTML page pretending to be an image, and a big file.
import test from "node:test";
import assert from "node:assert/strict";
import http from "node:http";
import { findOgImage, probeImage, checkPage, verdict } from "./probe-share-image.mjs";
const PNG = Buffer.alloc(48213, 1); // pretend image bytes
const BIG = Buffer.alloc(900 * 1024, 2);
let server, base;
test.before(async () => {
server = http.createServer((req, res) => {
const u = req.url;
const img = (body, type = "image/png") => { res.setHeader("content-type", type); return body; };
if (u === "/page") { res.setHeader("content-type", "text/html");
return res.end('<meta content="/img.png" property="og:image"><title>x</title>'); }
if (u === "/nopage") { res.setHeader("content-type", "text/html"); return res.end("<title>no tags</title>"); }
if (u === "/img.png") { const b = img(PNG); res.setHeader("content-length", b.length); return res.end(req.method === "HEAD" ? undefined : b); }
if (u === "/big.png") { const b = img(BIG); res.setHeader("content-length", b.length); return res.end(req.method === "HEAD" ? undefined : b); }
if (u === "/nohead.png") { // refuses HEAD, honours Range
if (req.method === "HEAD") { res.statusCode = 405; return res.end(); }
const m = /bytes=(\d+)-(\d+)/.exec(req.headers.range ?? "");
if (m) { res.statusCode = 206; res.setHeader("content-range", `bytes ${m[1]}-${m[2]}/${PNG.length}`); res.setHeader("content-type", "image/png"); return res.end(PNG.subarray(+m[1], +m[2] + 1)); }
res.setHeader("content-type", "image/png"); return res.end(PNG);
}
if (u === "/norange.png") { // refuses HEAD, ignores Range, streams without Content-Length
if (req.method === "HEAD") { res.statusCode = 501; return res.end(); }
res.setHeader("content-type", "image/png"); res.write(PNG.subarray(0, 20000)); return res.end(PNG.subarray(20000));
}
if (u === "/redirect") { res.statusCode = 302; res.setHeader("location", "/img.png"); return res.end(); }
if (u === "/soft404.png") { res.setHeader("content-type", "text/html"); return res.end("<h1>Not found</h1>"); }
res.statusCode = 404; res.end("nope");
});
await new Promise((r) => server.listen(0, "127.0.0.1", r));
base = `http://127.0.0.1:${server.address().port}`;
});
test.after(() => server.close());
test("findOgImage resolves a path-only value and ignores attribute order", () => {
assert.equal(findOgImage('<meta content="/a/b.png" property="og:image">', "https://example.com/post/1"), "https://example.com/a/b.png");
assert.equal(findOgImage('<meta name="twitter:image" content="/x.png">', "https://example.com/"), null);
});
test("HEAD is enough when Content-Length is present", async () => {
const r = await probeImage(base + "/img.png");
assert.equal(r.method, "HEAD"); assert.equal(r.bytes, 48213); assert.deepEqual(r.problems, []);
});
test("falls back to Range when HEAD is refused", async () => {
const r = await probeImage(base + "/nohead.png");
assert.equal(r.method, "GET Range"); assert.equal(r.bytes, 48213); assert.equal(r.status, 206);
});
test("counts bytes when the server ignores Range, and stops at the limit", async () => {
const full = await probeImage(base + "/norange.png");
assert.equal(full.method, "GET (counted)"); assert.equal(full.bytes, 48213); assert.equal(full.atLeast, false);
const cut = await probeImage(base + "/norange.png", { limit: 10000 });
assert.equal(cut.atLeast, true); assert.ok(cut.bytes > 10000 && cut.bytes <= 48213);
});
test("follows a redirect and reports the final URL", async () => {
const r = await probeImage(base + "/redirect");
assert.equal(r.finalUrl, base + "/img.png"); assert.equal(r.bytes, 48213);
});
test("a page that returns HTML for an image URL is flagged", async () => {
const r = await probeImage(base + "/soft404.png");
assert.match(r.problems.join(), /not an image/);
});
test("verdict warns over budget, and checkPage ties it together", async () => {
const big = await probeImage(base + "/big.png");
assert.match(verdict(big).join(), /900 KB is over your 300 KB budget/);
const ok = await checkPage(base + "/page");
assert.equal(ok.image, base + "/img.png"); assert.deepEqual(ok.issues, []);
assert.match((await checkPage(base + "/nopage")).error, /no og:image/);
});
The first run of the "ignores Range" test failed with ReadableStream is locked. My first version used for await (const chunk of res.body) to read the stream and then called res.body.cancel() inside the loop. You cannot cancel a stream that a reader is holding. Reading with res.body.getReader() and calling reader.cancel() fixed it. This is exactly the kind of mistake that only shows up when you test the "stop early" path, which is the whole point of that branch.
Running the tests:
✔ findOgImage resolves a path-only value and ignores attribute order (5.813086ms)
✔ HEAD is enough when Content-Length is present (19.488048ms)
✔ falls back to Range when HEAD is refused (5.694634ms)
✔ counts bytes when the server ignores Range, and stops at the limit (10.429793ms)
✔ follows a redirect and reports the final URL (3.601072ms)
✔ a page that returns HTML for an image URL is flagged (3.609265ms)
✔ verdict warns over budget, and checkPage ties it together (6.720976ms)
ℹ tests 7
ℹ suites 0
ℹ pass 7
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 150.558056
Running it on real pages
From the command line you can pass one or more page URLs:
node probe-share-image.mjs https://www.abid-ali.dev/ https://abidali671.github.io/blogs/
OK https://www.abid-ali.dev/
https://www.abid-ali.dev/opengraph-image.png
image/png, 108 KB, via GET (counted)
WARN https://abidali671.github.io/blogs/
https://abidali671.github.io/blogs/what-to-put-in-a-freelance-invoice/cover.png
image/png, 1737 KB, via HEAD
- 1737 KB is over your 300 KB budget
Those are two real pages: the first needed the byte-counting fallback, and the second was answered by HEAD and flagged as heavy (its share image is a 1.7 MB PNG, which is a good reminder to run this on your own pages). The output tells you which request method produced the size (HEAD, GET Range or GET (counted)), so when a number looks odd you know how it was obtained. The exit code is non-zero when anything is flagged, which makes it easy to drop into a CI step after a deploy.
What this does not tell you
It does not check pixel dimensions, and it does not tell you whether a particular chat app will accept the file. A small file can still be the wrong shape, and a file within budget can still be rejected for reasons that only the app knows. Treat the probe as a first filter: it finds the obvious problems (heavy file, wrong type, error page, bad redirect) quickly, across many pages.
For the rest, open the page in a free Open Graph checker, which shows the title, description and image the way a link card would, and fix what it points out. Then run the probe again after the next deploy so a heavy replacement image does not slip back in.
Takeaways
- Look at the file size of your
og:image, not only its dimensions. - HEAD first, a one-byte
Rangerequest second, a capped byte count last. Do not trustContent-LengthorRangesupport without a fallback. - Check
content-type; a200that returns HTML is not an image. - Resolve path-only
og:imagevalues against the page URL and report the absolute address. - Test the early-stop path, it is where the bug was.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.