A small Node server and a framework-free script that show today's panchang for any coordinates - tithi with its end time, nakshatra, yoga, karana, sunrise, sunset and Rahu Kaal in the place's own time - styled your way and paid for by your own key.
unzip panchang-widget.zip && cd panchang-widget
cp .env.example .env # put your key in ASTRONODE_API_KEY
npm run dev # demo page at http://localhost:3000
"use strict";
/**
* Panchang widget logic: input validation, the upstream request bodies,
* response mapping and the in-memory cache. No I/O of its own except the
* injected `fetch`, so all of it is testable without a network or a key.
*/
const DEFAULT_API_URL = "https://api.astronode.dev";
/** Coordinates are rounded to 2 decimals (about 1 km) before calling the API and before caching. */
const COORD_DECIMALS = 2;
class InputError extends Error {
constructor(message, field) {
super(message);
this.name = "InputError";
this.field = field;
}
}
class UpstreamError extends Error {
/**
* @param {number} status HTTP status the API returned (0 = never reached it)
* @param {string} code the API's machine-readable error code
* @param {string} message
*/
constructor(status, code, message) {
super(message);
this.name = "UpstreamError";
this.status = status;
this.code = code;
}
}
// ---------------------------------------------------------------------------
// Time zones
// ---------------------------------------------------------------------------
/** True when `zone` is an IANA zone this runtime knows (e.g. "Asia/Kolkata"). */
const isValidTimeZone = (zone) => {
if (typeof zone !== "string" || zone.length === 0 || zone.length > 64) return false;
try {
new Intl.DateTimeFormat("en-US", { timeZone: zone });
return true;
} catch {
return false;
}
};
/** UTC offset in minutes (east positive: IST = +330) that `zone` observes at the instant `instantMs`. */
const zoneOffsetMinutes = (instantMs, zone) => {
const dtf = new Intl.DateTimeFormat("en-US", {
timeZone: zone,
hourCycle: "h23",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
const p = {};
for (const part of dtf.formatToParts(new Date(instantMs))) {
if (part.type !== "literal") p[part.type] = part.value;
}
const asZoneUtc = Date.UTC(
Number(p.year),
Number(p.month) - 1,
Number(p.day),
Number(p.hour),
Number(p.minute),
Number(p.second),
);
return Math.round((asZoneUtc - instantMs) / 60000);
};
/**
* The `tz_offset_minutes` in force at a local wall-clock time in `zone`.
* Two passes so a DST change on that day resolves correctly.
*/
const offsetMinutesForLocalTime = (dateIso, timeHhmm, zone) => {
const [y, mo, d] = dateIso.split("-").map(Number);
const [hh, mm] = timeHhmm.split(":").map(Number);
const wallAsUtc = Date.UTC(y, mo - 1, d, hh, mm, 0);
const first = zoneOffsetMinutes(wallAsUtc, zone);
return zoneOffsetMinutes(wallAsUtc - first * 60000, zone);
};
/** Today's date (YYYY-MM-DD) in `zone`. */
const localDate = (zone, now = new Date()) =>
new Intl.DateTimeFormat("en-CA", { timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit" }).format(now);
// ---------------------------------------------------------------------------
// Input validation
// ---------------------------------------------------------------------------
const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
const NUMBER_RE = /^[+-]?(\d+(\.\d*)?|\.\d+)$/;
const isRealDate = (s) => {
const m = DATE_RE.exec(s);
if (!m) return false;
const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
if (y < 1900 || y > 2100) return false;
const t = new Date(Date.UTC(y, mo - 1, d));
return t.getUTCFullYear() === y && t.getUTCMonth() === mo - 1 && t.getUTCDate() === d;
};
const parseCoord = (raw, name, limit) => {
if (typeof raw !== "string" || !NUMBER_RE.test(raw.trim())) {
throw new InputError(`${name} must be a number`, name);
}
const n = Number(raw.trim());
if (!Number.isFinite(n) || n < -limit || n > limit) {
throw new InputError(`${name} must be between -${limit} and ${limit}`, name);
}
return n;
};
const roundCoord = (n) => {
const f = 10 ** COORD_DECIMALS;
const r = Math.round(n * f) / f;
return Object.is(r, -0) ? 0 : r;
};
/**
* Validate the `/api/panchang` query. `query` is a URLSearchParams.
* Returns `{ lat, lng, tz, date }` with lat/lng already rounded, or throws InputError.
* `date` defaults to today in the place's own time zone.
*/
const parsePanchangQuery = (query, now = new Date()) => {
const lat = roundCoord(parseCoord(query.get("lat"), "lat", 90));
const lng = roundCoord(parseCoord(query.get("lng"), "lng", 180));
const tz = query.get("tz");
if (!isValidTimeZone(tz)) throw new InputError("tz must be an IANA time zone such as Asia/Kolkata", "tz");
const rawDate = query.get("date");
let date;
if (rawDate === null || rawDate === "") {
date = localDate(tz, now);
} else if (isRealDate(rawDate)) {
date = rawDate;
} else {
throw new InputError("date must be a real calendar date, YYYY-MM-DD, between 1900 and 2100", "date");
}
return { lat, lng, tz, date };
};
// ---------------------------------------------------------------------------
// Upstream request + response mapping
// ---------------------------------------------------------------------------
/**
* Body for POST /v1/panchang and POST /v1/muhurta/inauspicious. The offset is
* the one in force at LOCAL NOON that day: that is what decides which local
* day the panchang describes, and it is right on DST-change days too.
*/
const buildUpstreamBody = ({ lat, lng, tz, date }) => ({
date,
tz_offset_minutes: offsetMinutesForLocalTime(date, "12:00", tz),
lat,
lng,
});
/**
* Format an ISO instant as local wall-clock time in `zone`: "06:57", or
* "00:52 (6 Dec)" when it falls on a different local day than `date`.
*/
const formatLocal = (iso, zone, date) => {
const t = new Date(iso);
if (Number.isNaN(t.getTime())) return "";
const hm = new Intl.DateTimeFormat("en-GB", { timeZone: zone, hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(t);
if (localDate(zone, t) === date) return hm;
const dm = new Intl.DateTimeFormat("en-GB", { timeZone: zone, day: "numeric", month: "short" }).format(t);
return `${hm} (${dm})`;
};
const str = (v) => (typeof v === "string" ? v : "");
const timeOf = (iso, tz, date) => ({ iso: str(iso), local: iso ? formatLocal(iso, tz, date) : "" });
/**
* Compact widget JSON from the two API payloads (`data` of each envelope).
* Every value the browser renders is a plain string or number.
*/
const mapPanchang = (panchang, inauspicious, place) => {
const { tz, date } = place;
const p = panchang || {};
const rk = (inauspicious && inauspicious.rahu_kaal) || {};
return {
date: str(p.date) || date,
place: { lat: place.lat, lng: place.lng, tz },
tz_offset_minutes: buildUpstreamBody(place).tz_offset_minutes,
vara: { name: str(p.vara && p.vara.name), lord: str(p.vara && p.vara.lord) },
tithi: {
name: str(p.tithi && p.tithi.name),
paksha: str(p.tithi && p.tithi.paksha),
end: timeOf(p.tithi && p.tithi.end, tz, date),
},
nakshatra: { name: str(p.nakshatra && p.nakshatra.name) },
yoga: { name: str(p.yoga && p.yoga.name) },
karana: { name: str(p.karana && p.karana.name) },
sunrise: timeOf(p.sunrise, tz, date),
sunset: timeOf(p.sunset, tz, date),
rahu_kaal: { start: timeOf(rk.start, tz, date), end: timeOf(rk.end, tz, date) },
};
};
// ---------------------------------------------------------------------------
// Cache
// ---------------------------------------------------------------------------
const cacheKey = ({ lat, lng, tz, date }) => `${lat.toFixed(COORD_DECIMALS)}|${lng.toFixed(COORD_DECIMALS)}|${date}|${tz}`;
/**
* Small in-memory TTL cache with a size bound (oldest entry evicted first).
* Stores promises, so concurrent requests for the same key share one upstream
* call. A rejected promise is removed, so failures are never cached.
*/
const createCache = ({ ttlMs = 36 * 3_600_000, maxEntries = 5_000, now = () => Date.now() } = {}) => {
const map = new Map();
return {
get size() {
return map.size;
},
/** Return the cached value for `key`, or run `load()` once and cache it. */
async getOrLoad(key, load) {
const hit = map.get(key);
if (hit && hit.expires > now()) return hit.value;
if (hit) map.delete(key);
const value = Promise.resolve().then(load);
map.set(key, { value, expires: now() + ttlMs });
while (map.size > maxEntries) map.delete(map.keys().next().value);
try {
return await value;
} catch (err) {
if (map.get(key) && map.get(key).value === value) map.delete(key);
throw err;
}
},
clear() {
map.clear();
},
};
};
// ---------------------------------------------------------------------------
// Service
// ---------------------------------------------------------------------------
/** POST one API path and return the envelope's `data`, or throw UpstreamError. */
const postJson = async ({ fetchImpl, apiUrl, apiKey, path, body }) => {
let res;
try {
res = await fetchImpl(`${apiUrl.replace(/\/+$/, "")}${path}`, {
method: "POST",
headers: {
authorization: `Bearer ${apiKey}`,
"content-type": "application/json",
accept: "application/json",
"user-agent": "astronode-panchang-widget-template",
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(15_000),
});
} catch (err) {
throw new UpstreamError(0, "UPSTREAM_UNREACHABLE", `Could not reach the AstroNode API (${err && err.name ? err.name : "error"})`);
}
let json = null;
try {
json = await res.json();
} catch {
json = null;
}
if (!res.ok) {
const e = (json && json.error) || {};
throw new UpstreamError(res.status, str(e.code) || `HTTP_${res.status}`, str(e.message) || `AstroNode API returned HTTP ${res.status}`);
}
if (!json || typeof json.data !== "object" || json.data === null) {
throw new UpstreamError(res.status, "BAD_UPSTREAM_RESPONSE", `AstroNode API returned no data for ${path}`);
}
return json.data;
};
/**
* The panchang service the HTTP server calls. `fetchImpl` defaults to the
* global fetch; tests pass a fake.
*/
const createPanchangService = ({ apiKey, apiUrl = DEFAULT_API_URL, fetchImpl = globalThis.fetch, cache = createCache() }) => {
if (!apiKey) throw new Error("ASTRONODE_API_KEY is required");
const get = (place) =>
cache.getOrLoad(cacheKey(place), async () => {
const body = buildUpstreamBody(place);
const [panchang, inauspicious] = await Promise.all([
postJson({ fetchImpl, apiUrl, apiKey, path: "/v1/panchang", body }),
postJson({ fetchImpl, apiUrl, apiKey, path: "/v1/muhurta/inauspicious", body }),
]);
return mapPanchang(panchang, inauspicious, place);
});
return { get, cache };
};
module.exports = {
DEFAULT_API_URL,
InputError,
UpstreamError,
isValidTimeZone,
offsetMinutesForLocalTime,
localDate,
parsePanchangQuery,
roundCoord,
buildUpstreamBody,
formatLocal,
mapPanchang,
cacheKey,
createCache,
createPanchangService,
};
public/widget.js
javascript
/*
* AstroNode panchang widget - framework-free, no dependencies.
*
* <div data-astronode-panchang data-lat="19.076" data-lng="72.8777" data-tz="Asia/Kolkata"></div>
* <script src="/widget.js" defer></script>
*
* Optional attributes:
* data-date="2026-12-05" a fixed day (default: today in the place's time zone)
* data-title="Mumbai" heading text (default: "Panchang")
* data-theme="dark|light" force a theme (default: follows prefers-color-scheme)
* data-endpoint="https://widgets.example.com/api/panchang" (default: /api/panchang
* on the origin this script was loaded from)
*
* Restyle it by overriding the --anp-* CSS variables on .anp (see STYLE below).
* Every API value is written with textContent, never innerHTML.
*/
(function (root) {
"use strict";
var STYLE = [
".anp{--anp-bg:#fffdf8;--anp-fg:#1f1a14;--anp-muted:#6b6256;--anp-accent:#b45309;--anp-border:#eadfcd;--anp-warn-bg:#fef2f2;--anp-warn-fg:#991b1b;",
"font:14px/1.45 system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;color:var(--anp-fg);background:var(--anp-bg);",
"border:1px solid var(--anp-border);border-radius:12px;padding:16px 18px;max-width:360px;box-sizing:border-box}",
"@media (prefers-color-scheme:dark){.anp:not([data-theme=light]){--anp-bg:#17140f;--anp-fg:#f3ede4;--anp-muted:#a99f91;--anp-accent:#f59e0b;--anp-border:#332c22;--anp-warn-bg:#3b1414;--anp-warn-fg:#fecaca}}",
".anp[data-theme=dark]{--anp-bg:#17140f;--anp-fg:#f3ede4;--anp-muted:#a99f91;--anp-accent:#f59e0b;--anp-border:#332c22;--anp-warn-bg:#3b1414;--anp-warn-fg:#fecaca}",
".anp-head{display:flex;justify-content:space-between;align-items:baseline;gap:8px;margin:0 0 10px}",
".anp-title{font-size:16px;font-weight:650;margin:0}",
".anp-date{color:var(--anp-muted);font-size:12px}",
".anp-list{margin:0;display:grid;grid-template-columns:auto 1fr;gap:6px 14px}",
".anp-list dt{color:var(--anp-muted)}",
".anp-list dd{margin:0;text-align:right;font-variant-numeric:tabular-nums}",
".anp-sub{display:block;color:var(--anp-muted);font-size:12px}",
".anp-rahu dd{color:var(--anp-accent);font-weight:600}",
".anp-foot{margin:12px 0 0;color:var(--anp-muted);font-size:11px}",
".anp-msg{margin:0;color:var(--anp-muted)}",
".anp-err{margin:0;padding:8px 10px;border-radius:8px;background:var(--anp-warn-bg);color:var(--anp-warn-fg)}",
].join("");
/** The rows the widget shows, as plain strings, from the server's compact JSON. */
function rowsFor(d) {
var t = function (x) {
return (x && x.local) || "-";
};
return [
{ label: "Tithi", value: [d.tithi.paksha, d.tithi.name].filter(Boolean).join(" ") || "-", sub: d.tithi.end.local ? "until " + d.tithi.end.local : "" },
{ label: "Nakshatra", value: d.nakshatra.name || "-" },
{ label: "Yoga", value: d.yoga.name || "-" },
{ label: "Karana", value: d.karana.name || "-" },
{ label: "Sunrise", value: t(d.sunrise) },
{ label: "Sunset", value: t(d.sunset) },
{ label: "Rahu Kaal", value: t(d.rahu_kaal.start) + " - " + t(d.rahu_kaal.end), className: "anp-rahu" },
];
}
/** The URL to fetch for one widget element. */
function urlFor(attrs, defaultEndpoint) {
var endpoint = attrs.endpoint || defaultEndpoint;
var q = "lat=" + encodeURIComponent(attrs.lat || "") + "&lng=" + encodeURIComponent(attrs.lng || "") + "&tz=" + encodeURIComponent(attrs.tz || "");
if (attrs.date) q += "&date=" + encodeURIComponent(attrs.date);
return endpoint + (endpoint.indexOf("?") === -1 ? "?" : "&") + q;
}
if (typeof module === "object" && module.exports) {
module.exports = { rowsFor: rowsFor, urlFor: urlFor };
}
if (!root || !root.document) return;
var doc = root.document;
var script = doc.currentScript;
var defaultEndpoint = (function () {
try {
return new URL("/api/panchang", script && script.src ? script.src : root.location.href).href;
} catch (e) {
return "/api/panchang";
}
})();
function el(tag, className, text) {
var n = doc.createElement(tag);
if (className) n.className = className;
if (text !== undefined) n.textContent = text;
return n;
}
function injectStyle() {
if (doc.getElementById("anp-style")) return;
var s = el("style");
s.id = "anp-style";
s.textContent = STYLE;
doc.head.appendChild(s);
}
function frame(node, title) {
node.classList.add("anp");
node.textContent = "";
var head = el("div", "anp-head");
head.appendChild(el("p", "anp-title", title));
node.appendChild(head);
return head;
}
function render(node, d) {
var head = frame(node, node.getAttribute("data-title") || "Panchang");
var dateText = d.date + (d.vara && d.vara.name ? " · " + d.vara.name : "");
head.appendChild(el("span", "anp-date", dateText));
var dl = el("dl", "anp-list");
rowsFor(d).forEach(function (r) {
var wrap = el("div");
wrap.style.display = "contents";
if (r.className) wrap.className = r.className;
wrap.appendChild(el("dt", "", r.label));
var dd = el("dd", "", r.value);
if (r.sub) dd.appendChild(el("span", "anp-sub", r.sub));
wrap.appendChild(dd);
dl.appendChild(wrap);
});
node.appendChild(dl);
node.appendChild(el("p", "anp-foot", "Times in " + d.place.tz + " · Powered by AstroNode"));
node.setAttribute("aria-busy", "false");
}
function renderError(node, message) {
frame(node, node.getAttribute("data-title") || "Panchang");
node.appendChild(el("p", "anp-err", message));
node.setAttribute("aria-busy", "false");
}
function load(node) {
var attrs = {
lat: node.getAttribute("data-lat"),
lng: node.getAttribute("data-lng"),
tz: node.getAttribute("data-tz"),
date: node.getAttribute("data-date"),
endpoint: node.getAttribute("data-endpoint"),
};
frame(node, node.getAttribute("data-title") || "Panchang");
node.appendChild(el("p", "anp-msg", "Loading…"));
node.setAttribute("aria-busy", "true");
root
.fetch(urlFor(attrs, defaultEndpoint), { headers: { accept: "application/json" } })
.then(function (res) {
return res
.json()
.catch(function () {
return null;
})
.then(function (body) {
if (!res.ok || !body) {
var m = body && body.error && body.error.message ? body.error.message : "HTTP " + res.status;
throw new Error(m);
}
return body;
});
})
.then(function (d) {
render(node, d);
})
.catch(function (err) {
renderError(node, "Could not load the panchang: " + (err && err.message ? err.message : "network error"));
});
}
function init() {
injectStyle();
var nodes = doc.querySelectorAll("[data-astronode-panchang]");
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].getAttribute("data-anp-ready")) continue;
nodes[i].setAttribute("data-anp-ready", "1");
load(nodes[i]);
}
}
root.AstroNodePanchang = { init: init };
if (doc.readyState === "loading") doc.addEventListener("DOMContentLoaded", init);
else init();
})(typeof window !== "undefined" ? window : null);
What it does
GET /api/panchang?lat=&lng=&tz=&date= on your server calls both endpoints in parallel and returns compact JSON; the browser never sees your key.
Works out the UTC offset at the place's local noon from its IANA zone, so daylight-saving changes come out right.
Caches per place (coordinates rounded to two decimals) and date, shares in-flight requests, and never caches a failure.
public/widget.js renders into any <div data-astronode-panchang data-lat data-lng data-tz> with textContent only; colours are CSS variables, with a dark scheme.
Times on another local day carry the date, for example a tithi ending at 00:52 the next morning.
Endpoints and plan
API calls the template makes
Endpoint
Used for
Plan
POST /v1/panchang
Tithi, nakshatra, yoga, karana, sunrise, sunset
Free
POST /v1/muhurta/inauspicious
Rahu Kaal
Hobby
It needs a Hobby key or above: at least one endpoint it calls is not on the Free plan. See pricing.
Where things live
File
What it holds
server.js
The HTTP server: the JSON endpoint and the static files
src/panchang.js
Validation, offsets, the two API calls, the cache, response mapping
public/widget.js
The framework-free widget
public/index.html
A demo page with three widgets
Keys and deployment
The API key is read from the server's environment and sent as Authorization: Bearer <key>; it never reaches a browser or an app bundle.
npm run check runs 22 tests offline - validation, request bodies, daylight-saving offsets, mapping against recorded responses, the cache and the HTTP server - with no key and no network.
Run the server anywhere Node runs and point the widget's script at it; or move src/panchang.js into your own backend's route.
Upstream rate limits come back as 429; other API failures become 502, or 504 when the API cannot be reached.
Questions
Why does the panchang widget need the Hobby plan?
Rahu Kaal comes from POST /v1/muhurta/inauspicious, a Hobby endpoint. The panchang itself is on Free; drop the Rahu Kaal call to run it on a Free key.
How many API calls does it make?
Two per place per day, whatever the traffic: the answer is cached per rounded location and date.