← All writing

4 min readArchitectureCloudflarePayments

Link previews for a single-page app

Chat apps build link previews from your HTML and never run your JavaScript. How we gave every payment link its own preview with a Cloudflare Worker, and the details that are easy to get wrong.

Paste a link into WhatsApp, Slack or LinkedIn and a little card appears: a title, a line of description, maybe an image. That card comes from Open Graph tags in the page’s HTML:

<meta property="og:title" content="Northwind Traders is requesting ₹12,500" />
<meta property="og:description" content="Invoice INV-2041 · Website design" />
<meta property="og:image" content="https://pay.example.com/preview.png" />

For a payment link, that card matters. It’s the difference between “someone sent me a link” and “my web designer is asking for ₹12,500.” Here’s how we got there for our payment links, and what I’d check if you’re doing the same.

The catch: crawlers don’t run JavaScript

When you paste a link, the app’s server fetches the URL and reads the HTML that comes back. It doesn’t run the page’s scripts. So in a single-page app, where JavaScript fills in everything after load, any tags you set from the browser arrive too late. The crawler has already left with whatever was in the static index.html.

That leaves a few ways to get per-page tags into the HTML itself:

Approach How Trade-off
Server-side rendering Render the page on a server for each request A big change to how the app is built and hosted
Prerendering Generate HTML for each URL ahead of time Doesn’t work when links are created all day long
Rewrite in the web server e.g. text substitution in nginx Awkward to feed live data into, and hard to maintain
Rewrite at the edge A small function in front of the site edits the HTML on the way out One more moving part, but small and separate

We picked the last one, using a Cloudflare Worker.

How it works

  1. Payment links get their own domain, routed through the Worker. Everything else goes straight to the origin.
  2. The static page ships with placeholder Open Graph tags that make a decent generic preview on their own.
  3. For each request, the Worker fetches the page and, at the same time, asks our API for that link’s details.
  4. It swaps the placeholders for the real values and sends the page on.

A simplified version, which reads the whole page before replacing (ours streamed it instead):

export default {
  async fetch(request, env) {
    const [page, link] = await Promise.all([fetch(request), getLink(request, env)]);
    if (!link) return page; // unknown link: keep the generic tags

    const html = (await page.text())
      .replace(/(<meta property="og:title" content=")[^"]*/, `$1${escapeHtml(link.title)}`)
      .replace(/(<meta property="og:description" content=")[^"]*/, `$1${escapeHtml(link.summary)}`);

    return new Response(html, page);
  },
};

Details that are easy to get wrong

  • Escape what you insert. A merchant’s name or an invoice description goes straight into your HTML. A quote or an angle bracket in it can break the page, or worse. Escape it every time.
  • Decide what’s public. Anyone who sees the link sees the preview. A merchant name and an amount are fine; a customer’s details are not. Choose the fields deliberately.
  • Fail back to the generic tags. If the API is slow or the link doesn’t exist, send the page with its placeholders rather than an error. A plain preview beats no page.
  • Don’t let it slow the page down. Fetching the page and the link details at the same time keeps the extra wait to one API call. Streaming the response helps people opening the link.
  • Previews are cached by the apps. WhatsApp and others cache a link’s preview, sometimes for a long time. Get it right before links go out, because fixing the tags later won’t update previews people have already seen.
  • Regex works, and so does a real parser. Matching a few known placeholder tags with a regular expression is fine when you control the HTML exactly. Cloudflare’s HTMLRewriter parses HTML as it streams and is sturdier if the markup might change.
  • Mind the image. Use a PNG or JPEG of a sensible size, and make sure the og:image:type you declare matches the file you serve.

What I took from it

A static single-page app is simple to host right up until something outside the browser needs to read it. Link previews, search engines and social cards all read HTML, not your running app. A small function at the edge can give them what they need without turning the whole app into a server-rendered one.

↑↓ move↵ openesc close