Skip to main content

Why we render the homepage without JavaScript: AI crawlers, llms.txt and structured data

AI crawlers saw a loading spinner and numbers from launch day. Here is how we fixed it with server-side rendering, a stale-while-revalidate cache, Markdown mirrors and an access log.

Updated 9 min readMarkdown
Why we render the homepage without JavaScript: AI crawlers, llms.txt and structured data

Open your homepage with JavaScript disabled. That is roughly what most AI crawlers see, and for us it was embarrassing.

Our homepage was a static HTML shell. A script fetched the featured jobs from a JSON endpoint and filled in the counters. In a browser it looked fine. To a crawler that does not execute scripts, the main block said "Loading fresh jobs…" and the location picker showed counts we had typed in by hand on launch day.

This post covers what we changed: rendering the dynamic parts on the server without a frontend rewrite, keeping that render fast, and giving language models a plain text version of the site.

What the crawlers actually saw

We ran an audit: a set of questions about our niche, asked to several assistants, checking whether they mentioned us. The answer was mostly no. When we fetched our own pages with a plain HTTP client, the reason was obvious.

Three problems stood out:

  • Empty featured section. The only text in the block was the loading placeholder.
  • Contradicting numbers. The location picker had hard-coded counts from launch. Our market page, rendered on the server, showed live counts several times larger. Same site, two answers.
  • Slow homepage. The hero counters came from an expensive aggregate query. Once every ten minutes the cache expired, and the unlucky request that refreshed it waited 11 to 25 seconds. Crawlers have short timeouts.

Search engines that run a headless browser could work around the first two. Most AI crawlers and fetchers that answer a user's question in real time do not. They take the HTML as it arrives.

Server-side rendering without a rewrite

We did not want to move the homepage to a template engine or a frontend framework. The page is hand-written HTML with stable markers: data-hero-stat="live_jobs", an element with id="featured-jobs", buttons with data-value. The script already used those markers to fill in values.

So the server does the same thing the script does, before sending the page. It reads the file, substitutes values next to the markers and returns it:

@app.get("/", response_class=HTMLResponse)
def homepage(request: Request, db: Session = Depends(db_session)):
    page = open(INDEX_PATH, encoding="utf-8").read()
    try:
        stats = market_stats(db)
        for key in ("live_jobs", "companies", "new_this_week"):
            page = re.sub(rf'(data-(?:hero|lead)-stat="{key}">)[^<]*',
                          rf"\g<1>{fmt_stat(stats[key])}", page)
        page = location_counts(page, stats)
    except Exception:
        pass  # stats failed: serve the static fallback
    try:
        cards = render_job_cards(featured_jobs(db, request_lang(request)))
        if cards:
            page = FEATURED_RE.sub(lambda m: m.group(1) + cards + m.group(2), page, count=1)
    except Exception:
        pass  # keep the placeholder, the script will draw the cards
    return HTMLResponse(page)

Regex over HTML is usually a bad idea. Here it is a contract: we own both the file and the markers, and the patterns match exact attributes, not structure. If someone edits the markup and a pattern stops matching, the page still renders. It just falls back to the old behaviour.

Each block fails independently. A broken stats query should not cost us the job cards, and neither should take down the homepage.

One function, two consumers

The featured jobs used to live inside the JSON endpoint handler. We pulled the query into a function and let both the API and the homepage call it:

@app.get("/api/featured-jobs")
def api_featured(lang: str = "", db: Session = Depends(db_session)):
    return JSONResponse(featured_jobs(db, lang))

def featured_jobs(db: Session, lang: str = "") -> list[dict]:
    jobs = (db.query(Job).options(defer(Job.description))
            .filter(Job.status == "approved")
            .order_by(Job.featured.desc(), Job.created_at.desc())
            .limit(30).all())
    jobs.sort(key=lambda j: not j.has_salary)
    return [card_dict(j, lang) for j in jobs[:5]]

The card HTML on the server uses the same class names the script generates. When the script runs in a browser, it replaces the cards with identical markup, so there is no visible flash. The defer(Job.description) is a small win: descriptions are the heaviest column and the cards never show them.

The location counts follow the same rule. They come from the same aggregate as the market page, so the two can no longer disagree.

Making the expensive aggregate cheap to read

Rendering stats on the server made the 25-second refresh worse: now every crawler hitting the homepage at the wrong moment would wait. The fix was a stale-while-revalidate cache.

Expired data is returned immediately. One background thread recomputes it. A non-blocking lock makes sure only one refresh runs at a time:

_cache = {"data": None, "at": 0.0}
_lock = threading.Lock()

def market_stats(db: Session) -> dict:
    if _cache["data"] is not None:
        stale = time.time() - _cache["at"] >= STATS_TTL
        if stale and _lock.acquire(blocking=False):
            threading.Thread(target=_refresh, daemon=True).start()
        return _cache["data"]
    with _lock:  # first request after start: compute synchronously
        if _cache["data"] is None:
            _cache.update(data=compute_stats(db), at=time.time())
    return _cache["data"]

def _refresh() -> None:
    try:
        with SessionLocal() as db:
            _cache.update(data=compute_stats(db), at=time.time())
    except Exception as exc:
        log.warning("stats refresh failed: %s", exc)  # old numbers beat a 500
    finally:
        _lock.release()

The lock is acquired in the request thread and released in the worker thread. Python's threading.Lock allows that, unlike RLock. The background thread opens its own database session, because the request's session is closed by the time the work starts.

Only the very first request after a restart pays the full cost. Every later request reads memory.

Finding where the 25 seconds went

The cache hides the latency, but the refresh still burned CPU. A profile showed that two thirds of it went into one helper that detects which languages a job requires. It ran a word-boundary regex for every language alias against every job description: about 57,000 searches per refresh.

Most of those searches cannot match, because the alias is not in the text at all. A plain substring check is far cheaper than a compiled regex with lookarounds, so it goes first:

for code, label, aliases in JOB_LANGUAGES:
    if any((alias in text and re.search(rf"(?<![a-z]){re.escape(alias)}(?![a-z])", text))
           if alias.isascii() else alias in text
           for alias in aliases):
        found.append((code, label))

The substring test is a necessary condition for the regex, so the result is identical. The whole stats refresh got about 1.5 times faster from this one line.

Structured data that describes one entity

Rendering text fixes what crawlers read. Structured data tells them what the text is about. Our Organization markup had been an afterthought, and our brand name collides with an unrelated company in another country.

We filled in the fields that help a model resolve the entity:

  • logo as a 512×512 PNG. An SVG logo was not picked up.
  • sameAs with every official profile, so mentions elsewhere connect back.
  • alternateName, description and disambiguatingDescription. The last one says plainly which company we are not.
  • An @id on the organization, and every article's publisher refers to that @id instead of repeating the object.

The rule we follow now: every number in structured data and on public pages comes from the same function. Our llms.txt once said one company count while the market page said another, because each computed its own. Both now call the shared aggregate.

Markdown mirrors and llms.txt

Language models extract facts from plain text more reliably than from a layout full of cards, badges and navigation. So every public entity has a Markdown twin: /job/123 has /job/123.md, and the same pattern applies to profession pages and the market report.

The handler is short. It renders fields as **Label:** value lines, adds a source link and returns text/markdown:

def md_response(text: str) -> PlainTextResponse:
    return PlainTextResponse(text, media_type="text/markdown; charset=utf-8")

@app.get("/job/{job_id}.md")
def job_markdown(job_id: str, db: Session = Depends(db_session)):
    job = db.get(Job, int(job_id)) if job_id.isdigit() else None
    if not job or job.status not in ("approved", "archived"):
        raise HTTPException(404)
    return md_response(render_job_markdown(job))

On top of that sits /llms.txt: a short description of the site, a few live numbers, and links to the main sections and their Markdown versions. /llms-full.txt concatenates the overview, the market report and every profession page into a single file.

Both respect the language prefix. Assistants answering in English used to get our Russian text, so /en/llms.txt now returns an English version built from the same context.

Logging who actually comes

Our reverse proxy only logs errors, and the app server does not log User-Agents. Without data we could not tell whether any of this mattered. So the application keeps its own small access log for known AI agents and for visits referred from assistant domains.

The key distinction is between training crawlers and user-triggered fetchers. A request from an agent like ChatGPT-User or Perplexity-User happens while the assistant answers someone. That is the closest thing to a citation you can measure.

The log is append-only JSON lines with a lock and a size-based rotation:

def ai_log(entry: dict) -> None:
    line = json.dumps(entry, ensure_ascii=False)
    try:
        with _log_lock:
            try:
                if os.path.getsize(LOG_PATH) > 50 * 1024 * 1024:
                    os.replace(LOG_PATH, LOG_PATH + ".1")
            except OSError:
                pass  # file does not exist yet
            with open(LOG_PATH, "a", encoding="utf-8") as fh:
                fh.write(line + "\n")
    except OSError:
        pass  # logging must never break a request

An admin tab reads both files, groups hits by agent, day and path class (.md mirrors, /api, llms.txt, pages) and shows which pages get fetched during answers.

What we would tell ourselves earlier

  • Test with curl, not a browser. If the important text is not in the raw HTML, assume a model never sees it.
  • Hard-coded numbers rot. A fallback is fine, but it must be replaced by live data on the server, not in the client.
  • One source per number. Two code paths computing the same figure will drift, and models notice contradictions.
  • Fast first byte is part of visibility. A slow request is a missing page for a crawler with a short timeout.
  • Measure user-triggered fetches separately. Training crawlers tell you about coverage. Fetchers tell you about answers.

None of this needed a new framework. It took a few regexes over markers we already had, one cache and some plain text endpoints. We use this at SpinHire, a job board for the iGaming industry.

About the author

  • SpinHire (spinhire.io) is a job board built only for the iGaming industry: casino, sports betting, game studios, affiliates, payments and compliance. We index 6,600+ live roles from 430+ companies every 6 hours and keep the data open: a public jobs API without a key (CC BY 4.0), XML and RSS feeds, and an MCP server for AI assistants. Here we write about building that index, iGaming tech careers and developer salaries.

No comments yet. Be the first to comment.