โ† Recipes

Share a birth chart with a link preview, without leaking the birth

When someone pastes a chart link into WhatsApp or Slack, the preview is the og:image. Building it is a server-side render from the chart JSON. Keeping it private is mostly about what you do not put in the URL.

You build
A /c/<id> share page with an SVG chart and a cached 1200 x 630 PNG preview
Code
Node.js, TypeScript - no SDK, runnable as shown

Updated

The chart as SVG on the page

There is no image endpoint: /v1/charts/birth returns signs and planets, and the drawing is yours. A South Indian chart is the simplest to draw because every sign has a fixed cell (layouts are compared in North and South Indian charts):

lib/chart-svg.mjs

Node.js
// lib/chart-svg.mjs - a South Indian chart as an SVG string, for the share page itself
const ABBR = { Sun: "Su", Moon: "Mo", Mars: "Ma", Mercury: "Me", Jupiter: "Ju", Venus: "Ve", Saturn: "Sa", Rahu: "Ra", Ketu: "Ke" };
// Signs sit in fixed cells; [column, row] on a 4 x 4 grid, the middle four left empty.
export const CELLS = {
  Pisces: [0, 0], Aries: [1, 0], Taurus: [2, 0], Gemini: [3, 0], Cancer: [3, 1], Leo: [3, 2],
  Virgo: [3, 3], Libra: [2, 3], Scorpio: [1, 3], Sagittarius: [0, 3], Capricorn: [0, 2], Aquarius: [0, 1],
};

export const cellText = (chart) => {
  const out = Object.fromEntries(Object.keys(CELLS).map((s) => [s, []]));
  out[chart.ascendant.sign].push("Asc");
  for (const p of chart.planets) out[p.sign].push(ABBR[p.name] + (p.retrograde && !["Rahu", "Ketu"].includes(p.name) ? "(R)" : ""));
  return out;
};

export function chartSvg(chart, size = 480) {
  const c = size / 4;
  const esc = (s) => s.replace(/[&<>"]/g, (m) => `&#${m.charCodeAt(0)};`);
  const cells = Object.entries(cellText(chart)).map(([sign, items]) => {
    const [x, y] = CELLS[sign];
    const lines = items.map((t, i) => `<text x="${x * c + 8}" y="${y * c + 40 + i * 20}">${esc(t)}</text>`).join("");
    return `<rect x="${x * c}" y="${y * c}" width="${c}" height="${c}"/><text x="${x * c + 8}" y="${y * c + 18}" class="s">${sign.slice(0, 3)}</text>${lines}`;
  });
  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${size} ${size}" role="img" aria-label="Birth chart, ascendant ${chart.ascendant.sign}">` +
    `<style>rect{fill:none;stroke:#444}text{font:16px sans-serif}.s{font-size:11px;fill:#888}</style>${cells.join("")}</svg>`;
}

app/c/[id]/page.tsx (Next.js; not rendered in our run):

tsx
import { notFound } from "next/navigation";
import { chartSvg } from "@/lib/chart-svg.mjs";
import { getShare } from "@/lib/share.mjs";

export const metadata = { robots: { index: false, follow: false } }; // a shared chart is not a search result

export default async function SharePage({ params }: { params: Promise<{ id: string }> }) {
  const share = getShare((await params).id);
  if (!share) notFound();
  return <figure dangerouslySetInnerHTML={{ __html: chartSvg(share.chart) }} />;
}

Inline SVG on the page is crisp at any size, selectable and readable by screen readers through the aria-label. For this chart it is 1,579 bytes. Next.js picks up opengraph-image.tsx in the same folder and writes the og:image tag for you.

The og:image: draw text where a font exists

Link previews need a PNG (or JPEG); scrapers do not render SVG. In Next.js, ImageResponse from next/og lays out elements with satori, which turns text into outlines using the font bundled with it, then rasterises - with sharp (native libvips) if it can import it, otherwise with resvg compiled to WebAssembly, which needs no native dependencies.

app/c/[id]/opengraph-image.tsx

tsx
// app/c/[id]/opengraph-image.tsx - the og:image, 1200 x 630 PNG, rendered once per birth
import { ImageResponse } from "next/og";
import { CELLS, cellText } from "@/lib/chart-svg.mjs";
import { getShare } from "@/lib/share.mjs";

export const size = { width: 1200, height: 630 };
export const contentType = "image/png";
const pngs = new Map<string, ArrayBuffer>(); // birth hash + engine version -> PNG (use your blob store)

export default async function Image({ params }: { params: Promise<{ id: string }> }) {
  const share = getShare((await params).id);
  if (!share) return new Response("Not found", { status: 404 }); // revoked or never existed
  const key = `${share.hash}:${share.engine_version}`;
  if (!pngs.has(key)) {
    const items = cellText(share.chart);
    const C = 140; // cell size: a 560 px chart on the left of the card
    const card = new ImageResponse(
      (
        <div style={{ display: "flex", width: "100%", height: "100%", background: "#fbfaf7", padding: 35, gap: 48 }}>
          <div style={{ display: "flex", position: "relative", width: C * 4, height: C * 4 }}>
            {Object.entries(CELLS).map(([sign, [x, y]]) => (
              <div key={sign} style={{ position: "absolute", left: x * C, top: y * C, width: C, height: C,
                border: "1px solid #444", display: "flex", flexDirection: "column", padding: 8, fontSize: 24 }}>
                <span style={{ fontSize: 14, color: "#888" }}>{sign.slice(0, 3)}</span>
                {items[sign].map((t) => <span key={t}>{t}</span>)}
              </div>
            ))}
          </div>
          <div style={{ display: "flex", flexDirection: "column", justifyContent: "center", fontSize: 44 }}>
            <span>Vedic birth chart</span>
            <span style={{ fontSize: 30, color: "#555" }}>Ascendant {share.chart.ascendant.sign}</span>
          </div>
        </div>
      ),
      size,
    );
    pngs.set(key, await card.arrayBuffer());
  }
  // A day, not ImageResponse's default "immutable, max-age=31536000": a revoked share should stop resolving.
  return new Response(pngs.get(key), { headers: { "content-type": contentType, "cache-control": "public, max-age=86400" } });
}

Output, with sharp available:

text
share urls: /c/qUokP1FnhFw-JbC2 /c/_sRviQ9-cpZCvRwK api calls: 1
page svg: 1579 bytes
image/png 44456 bytes 1200x630 218 ms renderer: sharp
image/png 44456 bytes 1200x630 0 ms renderer: sharp
after revoke: 404 other link: 200

Output, with sharp hidden (the WebAssembly path):

text
share urls: /c/6vX7jSD75wUcMFRO /c/1LS97YcMxoYOrjq7 api calls: 1
page svg: 1579 bytes
image/png 32976 bytes 1200x630 223 ms renderer: wasm
image/png 32976 bytes 1200x630 0 ms renderer: wasm
after revoke: 404 other link: 200

The tempting shortcut is to pass the page's SVG string to ImageResponse as an <img> data URI. We tried it: with sharp installed the chart's labels rendered, and with sharp hidden the boxes rendered and every <text> disappeared, because the WebAssembly renderer has no system fonts to draw them with. It looks right on a laptop and loses its labels on a host without sharp. Laying the card out as elements, as above, rendered the same on both paths.

Outside Next.js the same two choices exist: @resvg/resvg-wasm with a font file you load yourself (no native code), or sharp (native, fast, renders SVG text with whatever fonts the machine has). Neither was run for this page beyond what next/og does internally.

Caching and privacy rules

  • Render once per birth. The PNG is cached under the birth hash plus engine_version; the second share rendered in 0 ms against about 220 ms for the first. In production put it in object storage, not process memory.
  • Override the default cache header. ImageResponse sends public, immutable, max-age=31536000 outside development. On a per-share URL that means a revoked link keeps its image in every CDN for a year. A day is a better default.
  • Revocation stops new previews only. After revokeShare the page and the image answer 404, but WhatsApp, Slack and others keep the preview they already fetched. Tell users that before they share.
  • Keep names off the image. The card shows the chart and the ascendant, nothing that identifies the person. The same goes for the page title.
  • `noindex` the share pages. They are for the people the link was sent to, not for search engines.

Questions

What do I end up with?
A /c/<id> share page with an SVG chart and a cached 1200 x 630 PNG preview. The code is in Node.js and TypeScript.
Which endpoints does this recipe call, and in what order?
1 endpoint, in this order: Birth Chart (Kundli) (POST /v1/charts/birth).

In the API

Endpoints this recipe calls

  1. Birth Chart (Kundli) APIPOST /v1/charts/birth