โ† Recipes

Cache charts and panchang on the device for offline use

A chart app is opened on planes, in temples and in basements. Most of what it shows can be stored on the phone indefinitely - the trick is knowing which responses are fixed for good, and noticing when the engine behind them changes.

You build
A device cache that serves the chart and a week of panchang offline and refreshes after an engine release
Code
Node.js - no SDK, runnable as shown

Updated

What stays valid, and for how long

Cache lifetime by response
ResponseValid untilKey
Birth chartThe engine version changesKind + hash of the five birth fields
Panchang for a date and placeThe engine version changes - it is fixed for that dateKind + date + place
Anything that defaults to "now" when you omit a dateDo not cache it - pass the date instead-
ErrorsNever cache-

The panchang row is the one people get wrong. A panchang does not go stale at midnight; what changes at midnight is which date counts as today. Key it by date and the cache needs no expiry at all, which also means a week can be fetched in advance. The determinism guide lists the endpoints that read the clock when no date is given.

Every successful response carries meta.engine_version in the envelope (checked on both endpoints used here). The chart repeats it in data.meta; the panchang's data.meta does not, so read the envelope's. Error envelopes have no meta at all - one more reason not to cache them.

Your backend passes the version through

The app calls your server, never AstroNode directly - a key in an app bundle can be read out of every install (see React Native for the EXPO_PUBLIC_ trap). The server forwards only the accepted fields and returns engine_version alongside the data, because it is the app's only way to learn that cached results are outdated:

server.mjs - a web-standard route handler

Node.js
// server.mjs - your backend route. The app never holds the AstroNode key.
const API = process.env.ASTRONODE_API_URL ?? "https://api.astronode.dev";
const KEY = process.env.ASTRONODE_API_KEY;
const BIRTH = ["date", "time", "tz_offset_minutes", "lat", "lng"];

export async function handle(req) {
  const { kind, input } = await req.json();
  const path = kind === "chart" ? "/v1/charts/birth" : kind === "panchang" ? "/v1/panchang" : null;
  if (!path) return Response.json({ error: "unknown kind" }, { status: 400 });
  // Forward only the accepted fields; panchang takes a date and a place, no time.
  const keys = kind === "chart" ? BIRTH : BIRTH.filter((k) => k !== "time");
  const res = await fetch(API + path, {
    method: "POST",
    headers: { authorization: `Bearer ${KEY}`, "content-type": "application/json" },
    body: JSON.stringify(Object.fromEntries(keys.map((k) => [k, input[k]]))),
  });
  const json = await res.json();
  if (!res.ok) return Response.json({ error: json.error.code }, { status: res.status });
  // Pass engine_version through: it is the app's only signal that cached results are outdated.
  return Response.json({ data: json.data, engine_version: json.meta.engine_version });
}

The cache in the app

storage is any synchronous string store - MMKV in React Native, or a thin wrapper over SQLite. Entries carry the version that produced them. While online, an entry from an older version is a miss; while offline, it is still better than nothing and is returned with a label the UI can show:

offline-cache.mjs

Node.js
// offline-cache.mjs - app-side cache. `storage` is MMKV / AsyncStorage / SQLite in the app.
import { createHash } from "node:crypto"; // in React Native: expo-crypto or any sha256

export function createAstroCache({ storage, call, now = () => Date.now() }) {
  const keyFor = (kind, input) =>
    `${kind}:` + createHash("sha256").update(JSON.stringify(Object.entries(input).sort())).digest("hex").slice(0, 24);

  // A chart never expires. A panchang is correct forever FOR ITS DATE - what changes is
  // which date is "today", so it is keyed by date and needs no expiry at all.
  // networkFirst: for the one screen you refresh on every launch (today's panchang). It is
  // also how the app learns a new engine_version while every other read is a cache hit.
  const get = async (kind, input, { networkFirst = false } = {}) => {
    const key = keyFor(kind, input);
    const hit = JSON.parse(storage.get(key) ?? "null");
    const current = storage.get("engine_version");
    if (hit && hit.engine_version === current && !networkFirst) return { ...hit, from: "cache" };
    try {
      const { data, engine_version } = await call(kind, input);
      storage.set("engine_version", engine_version); // older entries now miss when online
      storage.set(key, JSON.stringify({ data, engine_version, saved_at: now() }));
      return { data, engine_version, from: "network" };
    } catch (err) {
      if (hit) return { ...hit, from: hit.engine_version === current ? "cache (offline)" : "cache (offline, older engine)" };
      throw err;
    }
  };

  // Before a trip: fetch the next N days while online.
  const prefetchPanchang = async (place, fromDate, days) => {
    for (let i = 0; i < days; i++) {
      const date = new Date(Date.parse(fromDate) + i * 86_400_000).toISOString().slice(0, 10);
      await get("panchang", { ...place, date });
    }
  };
  return { get, prefetchPanchang };
}

Running it with the network switched off

demo.mjs - airplane mode is a fetch that throws

Node.js
import { handle } from "./server.mjs";
import { createAstroCache } from "./offline-cache.mjs";

const disk = new Map(); // what MMKV would persist
const storage = { get: (k) => disk.get(k), set: (k, v) => disk.set(k, v) };
let online = true, calls = 0, fakeEngine = null;
const call = async (kind, input) => {
  if (!online) throw new TypeError("Network request failed"); // what fetch throws in airplane mode
  calls++;
  const res = await handle(new Request("http://app.local/astro", { method: "POST", body: JSON.stringify({ kind, input }) }));
  const body = await res.json();
  if (fakeEngine) body.engine_version = fakeEngine; // simulate an engine release
  return body;
};
const app = createAstroCache({ storage, call });

const me = { date: "1988-11-02", time: "10:40:00", tz_offset_minutes: 330, lat: 12.9716, lng: 77.5946 };
const home = { tz_offset_minutes: 330, lat: 12.9716, lng: 77.5946 };
const line = (label, r) => console.log(label.padEnd(26), r.from.padEnd(29), r.engine_version, r.data.ascendant?.sign ?? `${r.data.date} ${r.data.tithi.paksha} ${r.data.tithi.name}`);

line("chart, first open", await app.get("chart", me));
await app.prefetchPanchang(home, "2026-12-05", 7);
console.log(`prefetched 7 days of panchang; ${calls} calls so far; ${disk.size} keys stored`);
online = false;
line("chart, offline", await app.get("chart", me));
line("panchang 8 Dec, offline", await app.get("panchang", { ...home, date: "2026-12-08" }));
try { await app.get("panchang", { ...home, date: "2026-12-20" }); } catch (e) { console.log("panchang 20 Dec, offline".padEnd(26), "miss:", e.message); }
online = true; fakeEngine = "1.2.2"; // an engine release while the user was away
line("chart, online", await app.get("chart", me));
line("today's panchang, launch", await app.get("panchang", { ...home, date: "2026-12-06" }, { networkFirst: true }));
line("chart, online again", await app.get("chart", me));
online = false;
line("panchang 9 Dec, offline", await app.get("panchang", { ...home, date: "2026-12-09" }));
console.log(`${calls} calls in total`);

Output:

text
chart, first open          network                       1.2.1 Sagittarius
prefetched 7 days of panchang; 8 calls so far; 9 keys stored
chart, offline             cache                         1.2.1 Sagittarius
panchang 8 Dec, offline    cache                         1.2.1 2026-12-08 Krishna Amavasya
panchang 20 Dec, offline   miss: Network request failed
chart, online              cache                         1.2.1 Sagittarius
today's panchang, launch   network                       1.2.2 2026-12-06 Krishna Trayodashi
chart, online again        network                       1.2.2 Sagittarius
panchang 9 Dec, offline    cache (offline, older engine) 1.2.1 2026-12-09 Shukla Pratipada
10 calls in total

Offline, the chart and any prefetched day are served; 20 December was never fetched, so it is a miss the screen has to explain. The API reported engine 1.2.1 throughout; the demo pretends a 1.2.2 release happened while the phone was away. Note the line after it: the chart was still served from cache, because nothing had told the app yet. Launch refreshes today's panchang network-first, that response carries the new version, and from then on the chart misses and is refetched. The 9 December entry, fetched under the old version, is still served offline - labelled - rather than leaving the screen empty.

Sizes and housekeeping

  • It is small. In this run a chart entry was 1,475 bytes and a panchang day about 600, so a full year of daily panchang for one city is roughly 220 KB.
  • Today is the place's date. Compute "today" in the zone of the place the panchang is for, not the phone's zone and not UTC - a traveller's home-city panchang should follow the home city's day.
  • Birth data on the device is personal data. Clear the cache when the user signs out or deletes a profile; storing birth data covers the server side.
  • Server-side caching is separate. Your backend can cache the same responses for all users - see cache charts by birth hash - which cuts API calls; the device cache cuts round trips and works offline.

Questions

What do I end up with?
A device cache that serves the chart and a week of panchang offline and refreshes after an engine release. The code is in Node.js.
Which endpoints does this recipe call, and in what order?
2 endpoints, in this order: Birth Chart (Kundli) (POST /v1/charts/birth), then Panchang (POST /v1/panchang).