A page has two ways of saying "this is my real address". The rel="canonical" link tells search engines which URL to index. The og:url meta tag tells social platforms and chat apps which URL a shared card belongs to. They are meant to agree. On sites that have been edited by several people, or moved between hosts, they quietly stop agreeing, and the symptoms are strange: shares that are counted under a different address, a card that opens a www version while Google indexes the bare domain, or a staging URL sitting inside a live page.
Checking this by hand is a two-minute job per page: view source, find both tags, compare. It is not a job for fifty pages. So this post builds a small checker with Node's built-in fetch, nothing to install, and walks through the cases that made me add tests.
If you want a plain-language explanation of why a mismatch matters, OG Scope has a guide to canonical tag mismatches. This post is the code side.
What counts as a mismatch
Before writing code it helps to decide what we will call a problem, because "the two strings are different" is too strict. These differences are harmless:
- a trailing slash:
/postagainst/post/ - a
#fragmenton one of them - upper-case letters in the host name
These are real problems:
- different hosts:
www.example.comagainstexample.com -
httpagainsthttps - one of the two tags missing
- a canonical that is only a path, such as
/post/. It is allowed by the spec, but a lot of tooling handles it badly, andog:urlshould always be absolute. - the page was fetched at one URL but names a different one as canonical. That one is often fine (tracking parameters, for example), so the checker reports it as information about the fetched URL rather than as a broken page.
Reading the two tags
I avoid a full HTML parser here on purpose. For two tags in the <head>, a small regular expression per tag is enough, as long as it copes with single quotes, unquoted values and any attribute order. Real pages do all three.
The comparison itself needs one helper that makes two URLs comparable: it strips the fragment and a trailing slash, and lets the URL class lower-case the host.
// canonical-check.mjs - compare rel=canonical, og:url and the final URL of a page. Node 18+, no dependencies. export function readTags(html) { const out = { canonical: null, ogUrl: null }; for (const tag of html.match(/<(link|meta)\b[^>]*>/gi) ?? []) { const attr = (name) => { const m = tag.match(new RegExp(`\\b${name}\\s*=\\s*("([^"]*)"|'([^']*)'|([^\\s>]+))`, "i")); return m ? (m[2] ?? m[3] ?? m[4]) : null; }; if (/^<link/i.test(tag) && /\bcanonical\b/i.test(attr("rel") ?? "")) out.canonical ??= attr("href"); if (/^<meta/i.test(tag) && attr("property")?.toLowerCase() === "og:url") out.ogUrl ??= attr("content"); } return out; } // Two URLs "match" when they only differ by a trailing slash on the path, upper-case host or a #fragment. export function normalise(u, base) { const url = new URL(u, base); url.hash = ""; if (url.pathname.length > 1) url.pathname = url.pathname.replace(/\/+$/, ""); return url.href; } export function compare(finalUrl, html) { const { canonical, ogUrl } = readTags(html); const problems = []; if (!canonical) problems.push("no rel=canonical link"); if (!ogUrl) problems.push("no og:url tag"); if (canonical && ogUrl && normalise(canonical, finalUrl) !== normalise(ogUrl, finalUrl)) problems.push(`canonical (${canonical}) and og:url (${ogUrl}) disagree`); if (canonical && /^\//.test(canonical)) problems.push("canonical is only a path; use a full https:// URL"); if (ogUrl && !/^https?:\/\//i.test(ogUrl)) problems.push("og:url is not an absolute URL"); if (canonical && normalise(canonical, finalUrl) !== normalise(finalUrl, finalUrl)) problems.push(`page was fetched at ${finalUrl} but names ${canonical} as canonical`); return { canonical, ogUrl, problems }; } export async function check(url) { const res = await fetch(url, { redirect: "follow", headers: { "user-agent": "canonical-check/1.0" } }); const html = await res.text(); return { status: res.status, finalUrl: res.url, ...compare(res.url, html) }; } if (import.meta.url === `file://${process.argv[1]}`) { let bad = 0; for (const url of process.argv.slice(2)) { const r = await check(url); console.log(`${r.problems.length ? "WARN" : "OK "} ${url} (HTTP ${r.status})`); if (r.finalUrl !== url) console.log(` redirected to ${r.finalUrl}`); for (const p of r.problems) console.log(` - ${p}`); bad += r.problems.length ? 1 : 0; } process.exitCode = bad ? 1 : 0; } Two details are worth pointing out. First, rel can hold several words, so the check is \bcanonical\b on the attribute value, not equality. A <link rel="stylesheet" href="/canonical.css"> must not be mistaken for a canonical link. Second, ??= keeps the first match only, which is what a crawler does with duplicates in practice, and a duplicate canonical is its own problem you may want to add later.
The tests
The tests use node:test and node:assert, which ship with Node, and they only need strings, so they run offline and in milliseconds.
import test from "node:test"; import assert from "node:assert/strict"; import { readTags, normalise, compare } from "./canonical-check.mjs"; const page = (head) => `<!doctype html><html><head>${head}</head><body></body></html>`; test("reads canonical and og:url with either quote style and any attribute order", () => { const t = readTags(page(`<link href='https://a.test/x/' rel="canonical"><meta content="https://a.test/x/" property="og:url">`)); assert.deepEqual(t, { canonical: "https://a.test/x/", ogUrl: "https://a.test/x/" }); }); test("ignores a canonical-looking word inside another rel value", () => { const t = readTags(page(`<link rel="alternate" href="https://a.test/feed"><link rel="stylesheet" href="/canonical.css">`)); assert.equal(t.canonical, null); }); test("a trailing slash and a fragment are not a mismatch", () => { assert.equal(normalise("https://a.test/post/#top"), normalise("https://a.test/post")); }); test("matching tags give no problems", () => { const r = compare("https://a.test/post/", page(`<link rel="canonical" href="https://a.test/post/"><meta property="og:url" content="https://a.test/post/">`)); assert.deepEqual(r.problems, []); }); test("different hosts (www vs bare) are reported", () => { const r = compare("https://a.test/post/", page(`<link rel="canonical" href="https://www.a.test/post/"><meta property="og:url" content="https://a.test/post/">`)); assert.ok(r.problems.some((p) => p.includes("disagree"))); }); test("missing tags and a path-only canonical are reported", () => { const r = compare("https://a.test/post/", page(`<link rel="canonical" href="/post/">`)); assert.ok(r.problems.includes("no og:url tag")); assert.ok(r.problems.some((p) => p.includes("only a path"))); }); test("a page that names another URL as canonical is reported", () => { const r = compare("https://a.test/post/?utm_source=x", page(`<link rel="canonical" href="https://a.test/post/"><meta property="og:url" content="https://a.test/post/">`)); assert.ok(r.problems.some((p) => p.includes("fetched at"))); }); Running them:
✔ reads canonical and og:url with either quote style and any attribute order (1.683618ms) ✔ ignores a canonical-looking word inside another rel value (0.259365ms) ✔ a trailing slash and a fragment are not a mismatch (1.172634ms) ✔ matching tags give no problems (0.422509ms) ✔ different hosts (www vs bare) are reported (0.407833ms) ✔ missing tags and a path-only canonical are reported (0.194251ms) ✔ a page that names another URL as canonical is reported (0.170551ms) ℹ tests 7 ℹ pass 7 ℹ fail 0 The second test was added after a false positive. My first version looked for the word canonical anywhere in the tag, and a stylesheet called canonical.css was reported as the page's canonical URL. Writing the test first made the fix obvious.
Running it against real pages
The command line part is at the bottom of the same file. Give it any number of URLs, it follows redirects, and the exit code is 1 if any page has a problem, so you can put it in a deploy step.
OK https://abidali671.github.io/blogs/ (HTTP 200) OK https://www.abid-ali.dev/ (HTTP 200) OK https://abidali671.neocities.org/ (HTTP 200) WARN https://abidali671.github.io/blogs/?utm_source=test (HTTP 200) - page was fetched at https://abidali671.github.io/blogs/?utm_source=test but names https://abidali671.github.io/blogs/ as canonical The last line shows the "information" case. I added ?utm_source=test to a blog address on purpose. The page correctly names the clean URL as canonical, so nothing is broken for visitors, but a share link with that parameter will not match what the tags say. If your team pastes links with tracking parameters into chats, this is worth knowing, and a checker that tells you which URL was fetched makes it easy to spot.
To check more than a handful of pages, read URLs from your sitemap.xml and pass them in. I keep the checker free of that on purpose, so it stays small enough to read in one go.
What to do with a failure
The fix is almost never in the checker. The usual causes are:
- A theme or plugin writes
og:urland another one writes the canonical. Pick one source and turn the other off, or set both from the same variable. - A site moved from
httptohttps, or from bare domain towww, and one of the tags is still built from an old setting. OG Scope's guide toog:urlexplains which address the tag should contain. - A staging address was copied into the live template. Search your repository for the staging host name.
After fixing, open the page in a real preview tool rather than trusting the source alone. The Open Graph checker shows the tags a crawler reads and the card they produce, which also catches things a script that only looks at two tags will not.
Limits
This checker only reads the HTML that the server returns. If your tags are added by JavaScript in the browser, most link preview crawlers will not see them, and neither will this script. It also does not follow <link rel="alternate" hreflang> groups, where each language version names itself as canonical, and that is correct. Add that rule before pointing it at a multilingual site, or you will get false alarms.
It is about sixty lines and does one job. If you extend it, write the test for the new case first.
