DEV Community

Cover image for Your Vibe-Coded Site Is Live. The Canonical Still Says localhost.
Vincent for Polydraft

Posted on

Your Vibe-Coded Site Is Live. The Canonical Still Says localhost.

This week on X, launch checklists for vibe-coded sites have been going around again. One I kept seeing, from namdev_ritik on November 23, is a tight six-item list: view-source and confirm the text is there, use real hrefs, stay off hash URLs, give every page a unique title and meta description, ship a sitemap, and watch for a stray noindex tag.

That last item is the failure I keep seeing after the site already looks finished. The coding agent added <meta name="robots" content="noindex, nofollow"> so the preview would not get indexed. It set rel=canonical to http://localhost:5173/ because that is where Vite was running. It set og:url to a *.vercel.app preview. Then someone pointed the real domain at the deploy, and none of those lines got rewritten. Chrome looks like a bakery. The head still looks like a staging server.

It does not matter whether the site came from Cursor, Claude Code or an AI website builder. If the document you ship still tells crawlers "do not index this," or "the real URL is localhost," this applies.

So I wrote the kind of site a coding agent produces for "a neighborhood bakery in Portland with a menu, hours and an order page." The HTML is prerendered on purpose. There is a real title, a real H1, and a short about-the-business page — this is not an empty #root. Then I wrote a short checker, staging_head.py, that reads the local HTML, the sitemap, and robots.txt, and reports leftover staging signals. I ran it on the staging head, on the same site after I only removed noindex, and on a version that points every absolute URL at the production host. All the numbers below come from those three runs.

The fixture

The business is fictional. It is called Lantern Loaf Bakery, and it sells sourdough and pastry in inner Southeast Portland. The "before" tree is a finished-looking marketing site: a title, an H1, hours, an address, a phone number, JSON-LD, a four-URL sitemap, and a robots.txt with a Sitemap: line. The leftovers are all in the head and in those two files.

Here is the head that actually got deployed, with the body omitted.

<head>
  <meta charset="utf-8">
  <title>Lantern Loaf Bakery | Sourdough and pastry in Portland</title>
  <meta name="description" content="Lantern Loaf Bakery in inner Southeast Portland. Sourdough, pastry, and coffee, Tuesday through Sunday.">
  <meta name="robots" content="noindex, nofollow">
  <link rel="canonical" href="http://localhost:5173/">
  <meta property="og:title" content="Lantern Loaf Bakery">
  <meta property="og:url" content="https://lantern-loaf-git-main-somebody.vercel.app/">
  <!-- JSON-LD url and @id are also http://localhost:5173/ -->
</head>
Enter fullscreen mode Exit fullscreen mode

If you open the site in a browser, you see a bakery. If you view-source, you see a page that tells crawlers not to index it, and a canonical that points at the developer's laptop.

The checker

staging_head.py reads a local HTML file — or an index.html under public/, dist/ or build/ — plus sitemap.xml and robots.txt if they sit next to it. Pass --host so it knows which hostname is the production one. It does not fetch a live site, and it does not inspect response headers such as X-Robots-Tag.

It reports:

  • noindex in meta name="robots" or googlebot (including the none token)
  • rel=canonical pointing at localhost, a loopback address, or a preview host such as *.vercel.app, *.netlify.app, *.ngrok-free.app, *.fly.dev, or *.onrender.com
  • og:url with the same problem
  • JSON-LD url or @id values with the same problem
  • sitemap <loc> values and the robots.txt Sitemap: line with the same problem
  • a public hostname that does not match --host
  • an http:// canonical when you asked it to assume https
  • a missing canonical, and a missing sitemap as a warning

It does not claim Google will treat every hint the same way. A noindex on the production URL is the sharp one: Google's documentation says not to index that URL. A canonical that points at localhost is a bad hint that some tools will honor and some will ignore. Either way, you should not ship it.

staging_head.py (about 610 lines, 11 tests)
#!/usr/bin/env python3
"""staging_head.py — find leftover staging signals in a site you are about to launch.

Usage:
  python3 staging_head.py fixtures/before --host lanternloaf.example
  python3 staging_head.py path/to/index.html --host example.com
  python3 staging_head.py --self-test

Reads local files only: an HTML page, plus sitemap.xml and robots.txt if they
sit next to it. It does not fetch a live site. Pass --host so the checker
knows which hostname is the production one.

Findings:
  noindex                 — meta robots / googlebot includes noindex
  staging-canonical       — rel=canonical points at localhost or a preview host
  staging-og-url          — og:url is localhost or a preview host
  staging-jsonld-url      — a JSON-LD url or @id is localhost or a preview host
  staging-sitemap         — a sitemap <loc> is localhost or a preview host
  staging-robots-sitemap  — robots.txt Sitemap: is localhost or a preview host
  host-mismatch           — a public URL uses a host other than --host
  insecure-canonical      — rel=canonical is http:// on a host you flagged as https
  missing-canonical       — no rel=canonical in the HTML
  missing-sitemap         — no sitemap.xml next to the page (warning, not a fail)

This does not fetch the live site, does not inspect response headers such as
X-Robots-Tag, and does not claim Google will treat every hint the same way.
"""

from __future__ import annotations

import argparse
import json
import re
import sys
import unittest
from dataclasses import dataclass, field
from html.parser import HTMLParser
from pathlib import Path
from typing import Any
from urllib.parse import urljoin, urlparse
from xml.etree import ElementTree as ET

LOOPBACK_HOSTS = {
    "localhost",
    "127.0.0.1",
    "0.0.0.0",
    "::1",
    "[::1]",
}

# Host suffixes that usually mean a preview or ephemeral deploy, not the
# production domain you are about to point DNS at.
PREVIEW_SUFFIXES = (
    "vercel.app",
    "netlify.app",
    "netlify.live",
    "herokuapp.com",
    "ngrok.io",
    "ngrok.app",
    "ngrok-free.app",
    "railway.app",
    "fly.dev",
    "onrender.com",
    "amplifyapp.com",
    "azurestaticapps.net",
    "trycloudflare.com",
    "loca.lt",
    "localtest.me",
    "lvh.me",
    "csb.app",
    "webcontainer.io",
    "stackblitz.io",
    "github.dev",
    "gitpod.io",
    "preview.tildacdn.com",
)

PREVIEW_EXACT = {"pages.dev"}  # exact only; subdomains may be prod-like and are handled as suffixes
PREVIEW_SUFFIXES_ALL = PREVIEW_SUFFIXES + ("pages.dev",)


def normalize_host(host: str) -> str:
    h = (host or "").strip().lower()
    if h.startswith("[") and h.endswith("]"):
        h = h[1:-1]
    if ":" in h and not h.count(":") > 1:
        # hostname:port, not an IPv6 address
        h = h.rsplit(":", 1)[0]
    if h.endswith("."):
        h = h[:-1]
    return h


def is_loopback(host: str) -> bool:
    h = normalize_host(host)
    if h in LOOPBACK_HOSTS or h.endswith(".localhost") or h.endswith(".local"):
        return True
    return False


def is_preview_host(host: str) -> bool:
    h = normalize_host(host)
    if not h:
        return False
    if h in PREVIEW_EXACT:
        return True
    for suffix in PREVIEW_SUFFIXES_ALL:
        if h == suffix or h.endswith("." + suffix):
            return True
    return False


def classify_url(url: str, production_host: str | None, assume_https: bool) -> dict[str, Any]:
    raw = (url or "").strip()
    result: dict[str, Any] = {
        "url": raw,
        "host": "",
        "kind": "empty",
        "insecure": False,
    }
    if not raw:
        return result
    parsed = urlparse(raw)
    host = normalize_host(parsed.netloc or parsed.path.split("/")[0] if raw.startswith("//") else parsed.netloc)
    if raw.startswith("//"):
        parsed = urlparse("https:" + raw)
        host = normalize_host(parsed.netloc)
    result["host"] = host
    if is_loopback(host):
        result["kind"] = "loopback"
    elif is_preview_host(host):
        result["kind"] = "preview"
    elif host:
        result["kind"] = "public"
    else:
        # relative URL — fine; it inherits the page host
        result["kind"] = "relative"
    if parsed.scheme == "http" and result["kind"] in {"public", "preview"} and assume_https:
        result["insecure"] = True
    if (
        production_host
        and result["kind"] == "public"
        and normalize_host(production_host) != host
        and not host.endswith("." + normalize_host(production_host))
        and normalize_host(production_host) != host
    ):
        result["kind"] = "mismatch"
    return result


class HeadParser(HTMLParser):
    def __init__(self) -> None:
        super().__init__(convert_charrefs=True)
        self.title_parts: list[str] = []
        self._in_title = False
        self._in_ld: str | None = None
        self._ld_chunks: list[str] = []
        self.canonicals: list[str] = []
        self.og_urls: list[str] = []
        self.robots_meta: list[str] = []
        self.jsonld: list[str] = []
        self.h1: list[str] = []
        self._in_h1 = False
        self._h1_chunks: list[str] = []

    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        ad = {k.lower(): (v or "") for k, v in attrs}
        if tag == "title":
            self._in_title = True
        elif tag == "h1":
            self._in_h1 = True
            self._h1_chunks = []
        elif tag == "link" and "canonical" in re.split(r"\s+", ad.get("rel", "").lower()):
            href = ad.get("href", "").strip()
            if href:
                self.canonicals.append(href)
        elif tag == "meta":
            name = ad.get("name", "").lower()
            prop = ad.get("property", "").lower() or ad.get("prop", "").lower()
            content = ad.get("content", "").strip()
            if name in {"robots", "googlebot", "bingbot", "googlebot-news"} and content:
                self.robots_meta.append(f"{name}:{content}")
            if prop == "og:url" and content:
                self.og_urls.append(content)
        elif tag == "script" and "ld+json" in ad.get("type", "").lower():
            self._in_ld = "ld"
            self._ld_chunks = []

    def handle_endtag(self, tag: str) -> None:
        if tag == "title":
            self._in_title = False
        elif tag == "h1":
            self._in_h1 = False
            text = re.sub(r"\s+", " ", "".join(self._h1_chunks)).strip()
            if text:
                self.h1.append(text)
        elif tag == "script" and self._in_ld:
            self.jsonld.append("".join(self._ld_chunks))
            self._in_ld = None
            self._ld_chunks = []

    def handle_data(self, data: str) -> None:
        if self._in_title:
            self.title_parts.append(data)
        if self._in_h1:
            self._h1_chunks.append(data)
        if self._in_ld:
            self._ld_chunks.append(data)


def extract_jsonld_urls(blobs: list[str]) -> list[str]:
    urls: list[str] = []

    def walk(node: Any) -> None:
        if isinstance(node, dict):
            for key in ("url", "@id"):
                val = node.get(key)
                if isinstance(val, str) and re.match(r"https?:|//", val):
                    urls.append(val)
            for val in node.values():
                walk(val)
        elif isinstance(node, list):
            for item in node:
                walk(item)

    for blob in blobs:
        text = blob.strip()
        if not text:
            continue
        try:
            walk(json.loads(text))
        except json.JSONDecodeError:
            # Some generators wrap JSON-LD in a JS comment or leave a trailing comma.
            try:
                walk(json.loads(re.sub(r",\s*}", "}", re.sub(r",\s*]", "]", text))))
            except json.JSONDecodeError:
                for m in re.findall(r'https?://[^"\\s]+', text):
                    urls.append(m)
    return urls


def parse_sitemap(path: Path) -> list[str]:
    if not path.is_file():
        return []
    try:
        tree = ET.parse(path)
    except ET.ParseError:
        return []
    locs: list[str] = []
    for el in tree.iter():
        if el.tag.lower().endswith("loc") and el.text and el.text.strip():
            locs.append(el.text.strip())
    return locs


def parse_robots_sitemaps(path: Path) -> list[str]:
    if not path.is_file():
        return []
    found: list[str] = []
    for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
        raw = line.strip()
        if raw.lower().startswith("sitemap:"):
            found.append(raw.split(":", 1)[1].strip())
    return found


def has_noindex(robots_meta: list[str]) -> list[str]:
    hits: list[str] = []
    for entry in robots_meta:
        name, _, content = entry.partition(":")
        tokens = {t.strip().lower() for t in content.split(",") if t.strip()}
        if "noindex" in tokens or "none" in tokens:
            hits.append(entry)
    return hits


@dataclass
class Finding:
    code: str
    detail: str


@dataclass
class Report:
    path: Path
    title: str = ""
    h1: str = ""
    canonicals: list[str] = field(default_factory=list)
    og_urls: list[str] = field(default_factory=list)
    robots_meta: list[str] = field(default_factory=list)
    jsonld_urls: list[str] = field(default_factory=list)
    sitemap_locs: list[str] = field(default_factory=list)
    robots_sitemaps: list[str] = field(default_factory=list)
    sitemap_path: Path | None = None
    robots_path: Path | None = None
    findings: list[Finding] = field(default_factory=list)
    production_host: str = ""

    @property
    def codes(self) -> list[str]:
        return [f.code for f in self.findings]


def resolve_input(target: Path) -> tuple[Path, Path]:
    """Return (html_path, root_dir)."""
    if target.is_file():
        return target, target.parent
    for rel in ("index.html", "public/index.html", "dist/index.html", "build/index.html"):
        cand = target / rel
        if cand.is_file():
            root = cand.parent
            # If we found public/index.html, also look beside public/ for sitemap
            if cand.parent.name in {"public", "dist", "build"} and (target / "sitemap.xml").is_file():
                return cand, target
            return cand, root
    raise FileNotFoundError(f"No index.html found under {target}")


def analyze(target: Path, production_host: str | None = None, assume_https: bool = True) -> Report:
    html_path, root = resolve_input(target)
    parser = HeadParser()
    parser.feed(html_path.read_text(encoding="utf-8", errors="replace"))
    sitemap_path = None
    for cand in (root / "sitemap.xml", html_path.parent / "sitemap.xml", root.parent / "sitemap.xml"):
        if cand.is_file():
            sitemap_path = cand
            break
    robots_path = None
    for cand in (root / "robots.txt", html_path.parent / "robots.txt", root.parent / "robots.txt"):
        if cand.is_file():
            robots_path = cand
            break

    report = Report(
        path=html_path,
        title=re.sub(r"\s+", " ", "".join(parser.title_parts)).strip(),
        h1=parser.h1[0] if parser.h1 else "",
        canonicals=parser.canonicals,
        og_urls=parser.og_urls,
        robots_meta=parser.robots_meta,
        jsonld_urls=extract_jsonld_urls(parser.jsonld),
        sitemap_locs=parse_sitemap(sitemap_path) if sitemap_path else [],
        robots_sitemaps=parse_robots_sitemaps(robots_path) if robots_path else [],
        sitemap_path=sitemap_path,
        robots_path=robots_path,
        production_host=production_host or "",
    )

    noindex_hits = has_noindex(parser.robots_meta)
    if noindex_hits:
        report.findings.append(
            Finding("noindex", "meta " + "; ".join(noindex_hits))
        )

    def flag_urls(urls: list[str], staging_code: str, label: str) -> None:
        if not urls:
            return
        for url in urls:
            info = classify_url(url, production_host, assume_https)
            if info["kind"] in {"loopback", "preview"}:
                report.findings.append(
                    Finding(staging_code, f"{label} {url} ({info['kind']})")
                )
            elif info["kind"] == "mismatch":
                report.findings.append(
                    Finding(
                        "host-mismatch",
                        f"{label} {url} (host {info['host']}, expected {production_host})",
                    )
                )
            elif staging_code == "staging-canonical" and info["insecure"]:
                report.findings.append(
                    Finding("insecure-canonical", f"{label} {url} uses http://")
                )

    if parser.canonicals:
        flag_urls(parser.canonicals, "staging-canonical", "canonical")
        if assume_https:
            # flag_urls already adds insecure-canonical for canonicals
            pass
    else:
        report.findings.append(Finding("missing-canonical", "no rel=canonical in the HTML"))

    flag_urls(parser.og_urls, "staging-og-url", "og:url")
    flag_urls(report.jsonld_urls, "staging-jsonld-url", "JSON-LD url/@id")
    flag_urls(report.sitemap_locs, "staging-sitemap", "sitemap loc")
    flag_urls(report.robots_sitemaps, "staging-robots-sitemap", "robots Sitemap")

    if sitemap_path is None:
        report.findings.append(Finding("missing-sitemap", "no sitemap.xml next to the page"))

    # Deduplicate findings that list the same code+detail
    seen: set[tuple[str, str]] = set()
    unique: list[Finding] = []
    for f in report.findings:
        key = (f.code, f.detail)
        if key in seen:
            continue
        seen.add(key)
        unique.append(f)
    report.findings = unique
    return report


def verdict_lines(report: Report) -> list[str]:
    codes = set(report.codes)
    lines: list[str] = []
    if "noindex" in codes:
        lines.append(
            "The page tells crawlers not to index it. If this is the production URL, that leftover preview tag will hide the site."
        )
    staging_url_codes = {
        "staging-canonical",
        "staging-og-url",
        "staging-jsonld-url",
        "staging-sitemap",
        "staging-robots-sitemap",
    }
    if codes & staging_url_codes:
        lines.append(
            "One or more absolute URLs still point at localhost or a preview host, not the production hostname."
        )
    if "host-mismatch" in codes:
        lines.append(
            "A public URL uses a hostname that does not match --host."
        )
    if "insecure-canonical" in codes:
        lines.append("The canonical uses http://. Prefer https:// for the production host.")
    if "missing-canonical" in codes:
        lines.append("There is no rel=canonical. Add one that points at the production URL.")
    if "missing-sitemap" in codes and len(codes) == 1:
        lines.append("No sitemap.xml was found next to the page. That is a warning, not a hide-the-site bug.")
    if not codes or codes == {"missing-sitemap"} and "noindex" not in codes and not (codes & staging_url_codes):
        if not codes:
            lines.append(
                "No staging signals in the head, sitemap or robots.txt Sitemap line."
            )
    if not lines and not codes:
        lines.append("No staging signals in the head, sitemap or robots.txt Sitemap line.")
    return lines


def format_report(report: Report) -> str:
    def join(xs: list[str]) -> str:
        return ", ".join(xs) if xs else "(none)"

    lines = [
        "staging_head.py  (local files only)",
        f"file: {report.path}",
        "",
        "PAGE",
        f"  title              {report.title or '(none)'}",
        f"  H1                 {report.h1 or '(none)'}",
        f"  canonical          {join(report.canonicals)}",
        f"  og:url             {join(report.og_urls)}",
        f"  robots meta        {join(report.robots_meta) or '(none)'}",
        f"  JSON-LD urls       {join(report.jsonld_urls)}",
        "",
        "SITEMAP / ROBOTS",
        f"  sitemap file       {report.sitemap_path or '(none)'}",
        f"  sitemap locs       {join(report.sitemap_locs)}",
        f"  robots Sitemap     {join(report.robots_sitemaps)}",
        "",
        "FINDINGS",
    ]
    if report.findings:
        for f in report.findings:
            lines.append(f"  - {f.code:24} {f.detail}")
    else:
        lines.append("  (none)")
    lines.append("")
    lines.append("VERDICT")
    for v in verdict_lines(report):
        lines.append(f"  {v}")
    if report.production_host:
        lines.append(f"  production host     {report.production_host}")
    return "\n".join(lines) + "\n"


# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------

class ClassifyTests(unittest.TestCase):
    def test_loopback_variants(self) -> None:
        for url in (
            "http://localhost:5173/",
            "http://127.0.0.1:3000/menu",
            "http://[::1]/",
            "https://app.localhost/",
        ):
            self.assertEqual(classify_url(url, "example.com", True)["kind"], "loopback", url)

    def test_preview_hosts(self) -> None:
        for url in (
            "https://lantern-loaf-git-main-somebody.vercel.app/",
            "https://curious-bakery.netlify.app/",
            "https://abc.ngrok-free.app/menu",
            "https://foo.onrender.com/",
        ):
            self.assertEqual(classify_url(url, "example.com", True)["kind"], "preview", url)

    def test_production_match(self) -> None:
        info = classify_url("https://lanternloaf.example/menu", "lanternloaf.example", True)
        self.assertEqual(info["kind"], "public")
        self.assertFalse(info["insecure"])

    def test_mismatch_and_http(self) -> None:
        mis = classify_url("https://other.example/", "lanternloaf.example", True)
        self.assertEqual(mis["kind"], "mismatch")
        insecure = classify_url("http://lanternloaf.example/", "lanternloaf.example", True)
        self.assertEqual(insecure["kind"], "public")
        self.assertTrue(insecure["insecure"])

    def test_relative_is_fine(self) -> None:
        self.assertEqual(classify_url("/menu", "lanternloaf.example", True)["kind"], "relative")


class ParserTests(unittest.TestCase):
    def test_parses_head_and_jsonld(self) -> None:
        html = """<!doctype html><html><head>
        <title>  Lantern Loaf </title>
        <meta name="robots" content="noindex, nofollow">
        <link rel="canonical" href="http://localhost:5173/">
        <meta property="og:url" content="https://x.vercel.app/">
        <script type="application/ld+json">
        {"@type":"Bakery","url":"http://localhost:5173/","@id":"http://localhost:5173/#biz"}
        </script>
        </head><body><h1>Portland bakery</h1></body></html>"""
        p = HeadParser()
        p.feed(html)
        self.assertEqual(re.sub(r"\s+", " ", "".join(p.title_parts)).strip(), "Lantern Loaf")
        self.assertEqual(p.canonicals, ["http://localhost:5173/"])
        self.assertEqual(p.og_urls, ["https://x.vercel.app/"])
        self.assertTrue(any("noindex" in r for r in p.robots_meta))
        urls = extract_jsonld_urls(p.jsonld)
        self.assertIn("http://localhost:5173/", urls)
        self.assertIn("http://localhost:5173/#biz", urls)
        self.assertEqual(p.h1, ["Portland bakery"])

    def test_noindex_none_token(self) -> None:
        self.assertTrue(has_noindex(["robots:none"]))
        self.assertFalse(has_noindex(["robots:index, follow"]))
        self.assertFalse(has_noindex(["robots:nofollow"]))
        self.assertTrue(has_noindex(["googlebot:noindex"]))


class FixtureTests(unittest.TestCase):
    ROOT = Path(__file__).resolve().parent / "fixtures"

    def test_before_flags_staging_and_noindex(self) -> None:
        r = analyze(self.ROOT / "before", "lanternloaf.example")
        codes = set(r.codes)
        self.assertIn("noindex", codes)
        self.assertIn("staging-canonical", codes)
        self.assertIn("staging-og-url", codes)
        self.assertIn("staging-jsonld-url", codes)
        self.assertIn("staging-sitemap", codes)
        self.assertIn("staging-robots-sitemap", codes)
        self.assertNotIn("missing-canonical", codes)
        self.assertNotIn("missing-sitemap", codes)

    def test_mid_clears_noindex_keeps_staging_urls(self) -> None:
        r = analyze(self.ROOT / "mid", "lanternloaf.example")
        codes = set(r.codes)
        self.assertNotIn("noindex", codes)
        self.assertIn("staging-canonical", codes)
        self.assertIn("staging-og-url", codes)
        self.assertIn("staging-sitemap", codes)

    def test_after_is_clean(self) -> None:
        r = analyze(self.ROOT / "after", "lanternloaf.example")
        self.assertEqual(r.codes, [])
        self.assertTrue(r.canonicals[0].startswith("https://lanternloaf.example"))

    def test_missing_canonical(self) -> None:
        import tempfile
        with tempfile.TemporaryDirectory() as td:
            p = Path(td)
            (p / "index.html").write_text(
                "<html><head><title>Hi</title></head><body><h1>Hi</h1></body></html>",
                encoding="utf-8",
            )
            r = analyze(p, "example.com")
            self.assertIn("missing-canonical", r.codes)
            self.assertIn("missing-sitemap", r.codes)


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Find leftover staging signals in local HTML and sitemaps.")
    parser.add_argument("target", nargs="?", help="HTML file or directory containing index.html")
    parser.add_argument("--host", help="Production hostname, e.g. lanternloaf.example")
    parser.add_argument("--allow-http", action="store_true", help="Do not flag http:// canonicals as insecure")
    parser.add_argument("--self-test", action="store_true")
    args = parser.parse_args(argv)

    if args.self_test:
        suite = unittest.defaultTestLoader.loadTestsFromModule(sys.modules[__name__])
        result = unittest.TextTestRunner(verbosity=2).run(suite)
        return 0 if result.wasSuccessful() else 1

    if not args.target:
        parser.print_help()
        return 2

    report = analyze(Path(args.target), production_host=args.host, assume_https=not args.allow_http)
    sys.stdout.write(format_report(report))
    fail_codes = {c for c in report.codes if c != "missing-sitemap"}
    return 1 if fail_codes else 0


if __name__ == "__main__":
    sys.exit(main())
Enter fullscreen mode Exit fullscreen mode

Run 1: the staging head on a finished page

$ python3 staging_head.py fixtures/before --host lanternloaf.example

staging_head.py  (local files only)
file: fixtures/before/index.html

PAGE
  title              Lantern Loaf Bakery | Sourdough and pastry in Portland
  H1                 Sourdough, pastry, and coffee in Portland
  canonical          http://localhost:5173/
  og:url             https://lantern-loaf-git-main-somebody.vercel.app/
  robots meta        robots:noindex, nofollow
  JSON-LD urls       http://localhost:5173/, http://localhost:5173/#bakery

SITEMAP / ROBOTS
  sitemap file       fixtures/before/sitemap.xml
  sitemap locs       http://localhost:5173/, http://localhost:5173/menu,
                     https://lantern-loaf-git-main-somebody.vercel.app/hours,
                     https://lantern-loaf-git-main-somebody.vercel.app/order
  robots Sitemap     http://localhost:5173/sitemap.xml

FINDINGS
  - noindex                  meta robots:noindex, nofollow
  - staging-canonical        canonical http://localhost:5173/ (loopback)
  - staging-og-url           og:url https://lantern-loaf-git-main-somebody.vercel.app/ (preview)
  - staging-jsonld-url       JSON-LD url/@id http://localhost:5173/ (loopback)
  - staging-jsonld-url       JSON-LD url/@id http://localhost:5173/#bakery (loopback)
  - staging-sitemap          sitemap loc http://localhost:5173/ (loopback)
  - staging-sitemap          sitemap loc http://localhost:5173/menu (loopback)
  - staging-sitemap          sitemap loc https://lantern-loaf-git-main-somebody.vercel.app/hours (preview)
  - staging-sitemap          sitemap loc https://lantern-loaf-git-main-somebody.vercel.app/order (preview)
  - staging-robots-sitemap   robots Sitemap http://localhost:5173/sitemap.xml (loopback)

VERDICT
  The page tells crawlers not to index it. If this is the production URL,
  that leftover preview tag will hide the site.
  One or more absolute URLs still point at localhost or a preview host,
  not the production hostname.
  production host     lanternloaf.example
Enter fullscreen mode Exit fullscreen mode

A real title. A real H1. A sitemap with four URLs. And a noindex that will hide the whole thing if this is the document behind the custom domain. The canonical does not even point at the preview host. It points at port 5173 on the machine that ran the dev server.

This is easy to miss because the failure is invisible in the tool you use all day. The tab looks right. The Lighthouse run you did in Chrome looks right. The lines that are wrong are in the <head>, in sitemap.xml, and in one line of robots.txt.

Terminal output of staging_head.py on the Lantern Loaf Bakery fixture. The first run flags noindex, a localhost canonical, a Vercel preview og:url, and staging sitemap URLs; the final run has no findings.

Why a leftover noindex is worse than a missing title

A missing title is a quality problem. A production noindex is a hide-the-site problem.

Coding agents add the tag for a good reason. Preview URLs get indexed, and then the official domain has to compete with a *.vercel.app or *.netlify.app copy. The usual fix during development is noindex on the preview, or a preview that is itself gated. The bug is leaving that tag in the document you attach to the real hostname.

Google's documentation is direct: if a URL has noindex, it should not appear in search results. If the page was already indexed, the tag tells Google to drop it. You will not notice this in the browser. You notice it later, in a coverage report, or when a customer searches for the bakery name and does not find you.

The localhost canonical is a different kind of mess. Google may ignore a canonical it cannot crawl. Other tools are less forgiving. If you paste the custom domain into Slack or LinkedIn, the unfurl often follows og:url. In this fixture that destination is a Vercel preview, which may be protected, expired, or later deleted. A sitemap whose <loc> values are http://localhost:5173/ is not a map of the public site, and a robots.txt Sitemap: line that points there sends the crawler to a machine that is not on the internet.

Run 2: take off noindex, leave the staging URLs

The first "fix" a coding agent reaches for, once you point at the noindex line, is to delete that line and call the job done. I did that and changed nothing else.

$ python3 staging_head.py fixtures/mid --host lanternloaf.example

PAGE
  title              Lantern Loaf Bakery | Sourdough and pastry in Portland
  H1                 Sourdough, pastry, and coffee in Portland
  canonical          http://localhost:5173/
  og:url             https://lantern-loaf-git-main-somebody.vercel.app/
  robots meta        (none)

FINDINGS
  - staging-canonical        canonical http://localhost:5173/ (loopback)
  - staging-og-url           og:url https://lantern-loaf-git-main-somebody.vercel.app/ (preview)
  - staging-jsonld-url       JSON-LD url/@id http://localhost:5173/ (loopback)
  - staging-jsonld-url       JSON-LD url/@id http://localhost:5173/#bakery (loopback)
  - staging-sitemap          sitemap loc http://localhost:5173/ (loopback)
  - staging-sitemap          sitemap loc http://localhost:5173/menu (loopback)
  - staging-sitemap          sitemap loc https://lantern-loaf-git-main-somebody.vercel.app/hours (preview)
  - staging-sitemap          sitemap loc https://lantern-loaf-git-main-somebody.vercel.app/order (preview)
  - staging-robots-sitemap   robots Sitemap http://localhost:5173/sitemap.xml (loopback)

VERDICT
  One or more absolute URLs still point at localhost or a preview host,
  not the production hostname.
  production host     lanternloaf.example
Enter fullscreen mode Exit fullscreen mode

The hide-the-site bug is gone. The site still does not agree with itself about which hostname is real. Half the sitemap is localhost. The other half is the preview deploy. JSON-LD still describes http://localhost:5173/.

Clearing noindex is necessary. It is not sufficient.

Run 3: one production host, everywhere

The second rewrite points rel=canonical, og:url, the JSON-LD url and @id, every sitemap <loc>, and the robots.txt Sitemap: line at https://lanternloaf.example. The visible page did not change.

$ python3 staging_head.py fixtures/after --host lanternloaf.example

PAGE
  title              Lantern Loaf Bakery | Sourdough and pastry in Portland
  H1                 Sourdough, pastry, and coffee in Portland
  canonical          https://lanternloaf.example/
  og:url             https://lanternloaf.example/
  robots meta        (none)
  JSON-LD urls       https://lanternloaf.example/, https://lanternloaf.example/#bakery

SITEMAP / ROBOTS
  sitemap file       fixtures/after/sitemap.xml
  sitemap locs       https://lanternloaf.example/, https://lanternloaf.example/menu,
                     https://lanternloaf.example/hours, https://lanternloaf.example/order
  robots Sitemap     https://lanternloaf.example/sitemap.xml

FINDINGS
  (none)

VERDICT
  No staging signals in the head, sitemap or robots.txt Sitemap line.
  production host     lanternloaf.example
Enter fullscreen mode Exit fullscreen mode

That is the bar. Not "the tab looks right." "The production hostname is the only absolute host in the head, the sitemap, and the robots Sitemap: line, and the page is allowed to be indexed."

Table comparing the Lantern Loaf Bakery fixture across three runs: a staging head with noindex, the same page with noindex removed, and a version that points every absolute URL at the production host.

Three decisions

Once the checker has barked at you, the work is three decisions, not one "take off noindex" prompt.

  1. Do not ship noindex on the production URL. If you still need to hide a preview, hide it on the preview host — a noindex there, a suppressed preview indexing setting, or a gate. The document behind the custom domain should be allowed to be indexed, unless you truly do not want that URL in search.
  2. Point the head at the production host. rel=canonical, og:url, and JSON-LD url / @id should be https:// URLs on the hostname you are about to attach. http://localhost:5173/ is a dev-server address, not a canonical.
  3. Make the sitemap agree. Every <loc> and the robots.txt Sitemap: line should use that same host. A mixed sitemap of localhost and a preview deploy is not a map of the public site.

Three decisions for a production head: strip leftover noindex, point canonical and og:url at the production host, and make the sitemap agree.

This sits next to a website migration checklist: the cutover is not only DNS and redirects. It is also "did the staging head survive the domain cutover?" The same idea shows up in website architecture for SEO: each intent should have one owner URL, and the canonical should name that URL, not a laptop or a preview.

What I would do with a real repo

If I were handed a vibe-coded marketing site tomorrow, I would check this before I pointed a domain at it:

  1. curl the URL you think is production, or use view-source, and read the <head>. Do not trust the tab.
  2. Search the response, sitemap.xml, and robots.txt for noindex, localhost, 127.0.0.1, vercel.app, netlify.app, and ngrok.
  3. Run python3 staging_head.py . --host yourdomain.com against the files you are about to deploy, or against an HTML file you already saved with curl -o page.html https://yoursite.example/.
  4. Run it again after the next prompt. A scan you run once is a scan that is out of date after the agent "adds SEO" or "prepares the launch."

A site built with an AI website builder still has to pass this test. The builder is doing the right kind of work if the published document's canonical, og:url, and sitemap already use your domain. Generating the first version of the site is the cheap part. Knowing which hostname you told the rest of the internet to use is the part that decides whether Google, Slack, and your sitemap agree.

What we do in PolyDraft, and what we do not claim

PolyDraft is the AI website builder we work on. It publishes server-rendered HTML to your own Cloudflare account, so the document a crawler fetches is the document you can view-source. That makes a check like this easy to run. It does not make it unnecessary. An agent can still leave a preview noindex in a head, or write a canonical from a local dev server. We still run checks like these on what we ship, and you should run them on anything with your name on the domain, whoever or whatever built it.

Before you point a domain at the preview

  1. Read the production head, not just the rendered tab. If you see noindex or localhost, stop there.
  2. Confirm rel=canonical and og:url are https:// URLs on the hostname you are launching.
  3. Confirm the sitemap and the robots.txt Sitemap: line use that same host, and only that host.
  4. Save the files and run staging_head.py --host yourdomain.com again after the next change.

Ten minutes, all of it against HTML and XML you already have, all of it on your own site. Cheaper than finding out from a Search Console coverage report that the live site is still tagged noindex, or from a customer who pasted your URL into Slack and landed on an expired preview.

Top comments (0)