# A daily panchang in Astro that is not stuck on the day you built it

> Astro prerenders pages by default, so a `fetch` in a page's frontmatter runs once, during `astro build`. That suits a birth chart and is wrong for a panchang, which changes every day. This page renders on demand, keeps the key in `astro:env`, and works out "today" in the city's time zone.

Source: https://astronode.dev/integrations/astro · Updated: 2026-12-05

**How this page was verified:** `src/lib/panchang.ts` and the `GET` endpoint in `src/pages/api/panchang.ts` were executed on Node 24 against the in-memory API (the endpoint called with a `URL` and a `Request`, as Astro passes them), with `astro:env/server` replaced by a stand-in that reads the same two variables. `astro.config.mjs` and the `.astro` page were not run, because Astro is not installed on the build machine.

## Built once vs rendered per request

The panchang below was fetched for Varanasi on two consecutive days. On a prerendered page, whichever day the build ran is the one visitors see until the next deploy:

| Field | 5 December 2026 | 6 December 2026 |
| --- | --- | --- |
| vara | Shanivara | Ravivara |
| tithi | Krishna Dwadashi, until 6 Dec 00:52 | Krishna Trayodashi, until 7 Dec 02:22 |
| nakshatra | Chitra | Swati |
| sunrise / sunset | 06:29 / 17:07 | 06:30 / 17:07 |

There are two ways out. You can mark the page `export const prerender = false` and add an adapter, so it renders per request; that is what this page does. Or you can keep it static and rebuild every day from a scheduled job. The scheduled rebuild is cheaper to serve, but the page is wrong for whoever loads it between midnight and the build.

## Config: an adapter and an env schema

`astro.config.mjs`:

```js
import node from "@astrojs/node";
import { defineConfig, envField } from "astro/config";

export default defineConfig({
  adapter: node({ mode: "standalone" }), // or Vercel, Netlify, Cloudflare...
  env: {
    schema: {
      ASTRONODE_API_KEY: envField.string({ context: "server", access: "secret" }),
      ASTRONODE_BASE_URL: envField.string({
        context: "server",
        access: "public",
        default: "https://api.astronode.dev",
      }),
    },
  },
});
```

A variable declared `context: "server", access: "secret"` is importable only from `astro:env/server` and is not part of the build output; the server reads it from its environment when it runs. Values read through `import.meta.env` are different: Astro replaces them in the code at build time, so the key ends up in a file in `dist/`, and changing it means rebuilding.

## The panchang module and endpoint

`src/lib/panchang.ts`:

```ts
import { ASTRONODE_API_KEY, ASTRONODE_BASE_URL } from "astro:env/server";

export type City = { name: string; tz: number; lat: number; lng: number };

export const CITIES: Record<string, City> = {
  varanasi: { name: "Varanasi", tz: 330, lat: 25.3176, lng: 82.9739 },
  kathmandu: { name: "Kathmandu", tz: 345, lat: 27.7172, lng: 85.324 },
};

// "Today" in the city, not on the server (which is usually UTC).
export const cityDate = (tz: number, now = Date.now()): string =>
  new Date(now + tz * 60_000).toISOString().slice(0, 10);

// The API returns UTC instants; show them on the city's clock ("2026-12-06 00:52").
const local = (iso: string, tz: number) =>
  new Date(Date.parse(iso) + tz * 60_000).toISOString().slice(0, 16).replace("T", " ");

export async function panchangFor(city: City, date = cityDate(city.tz)) {
  const res = await fetch(`${ASTRONODE_BASE_URL}/v1/panchang`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${ASTRONODE_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ date, tz_offset_minutes: city.tz, lat: city.lat, lng: city.lng }),
  });
  const json = await res.json();
  if (!res.ok) throw new Error(`${json.error.code}: ${json.error.message}`);
  const p = json.data;
  return {
    date,
    vara: p.vara.name,
    tithi: `${p.tithi.paksha} ${p.tithi.name}`,
    tithiEnds: local(p.tithi.end, city.tz), // often after midnight
    nakshatra: p.nakshatra.name,
    sunrise: local(p.sunrise, city.tz).slice(11),
    sunset: local(p.sunset, city.tz).slice(11),
  };
}
```

`src/pages/api/panchang.ts` - for client-side widgets that want JSON:

```ts
import type { APIRoute } from "astro";
import { CITIES, panchangFor } from "../../lib/panchang";

export const prerender = false; // run per request, not once at build time

export const GET: APIRoute = async ({ url }) => {
  const city = CITIES[url.searchParams.get("city") ?? ""];
  if (!city) return Response.json({ error: "unknown city" }, { status: 404 });
  const today = await panchangFor(city);
  return Response.json(today, {
    // Same city + same date = same answer; let the CDN hold it briefly.
    headers: { "Cache-Control": "public, s-maxage=900" },
  });
};
```

`GET /api/panchang?city=kathmandu` returned Krishna Dwadashi ending `2026-12-06 01:07`, sunrise 06:39. That is the same instant as Varanasi's 00:52, shown on a +5:45 clock; an unknown city returned `404`. The tithi often ends after midnight, so the module keeps the date in `tithiEnds`. Sunrise and sunset come back as UTC instants and are shifted by the city's offset, not by the server's. Which sunrise convention the panchang uses: [panchang sunrise conventions](https://astronode.dev/guides/panchang-sunrise-conventions).

## The page

`src/pages/panchang/[city].astro`:

```astro
---
import { CITIES, panchangFor } from "../../lib/panchang";

export const prerender = false;

const city = CITIES[Astro.params.city ?? ""];
if (!city) return Astro.redirect("/panchang/varanasi");
const p = await panchangFor(city);
Astro.response.headers.set("Cache-Control", "public, s-maxage=900");
---
<h1>Panchang for {city.name}, {p.date}</h1>
<p>{p.vara} · {p.tithi} (until {p.tithiEnds}) · {p.nakshatra}</p>
<p>Sunrise {p.sunrise} · Sunset {p.sunset}</p>
```

Frontmatter runs on the server, so the page calls `panchangFor` directly; there is no reason to go through its own `/api` route. `s-maxage=900` lets a CDN serve the same HTML for 15 minutes, so a busy page still makes only a few API calls per city per hour.

## Two traps: PUBLIC_ and the server's date

- **`PUBLIC_ASTRONODE_API_KEY`.** Any `PUBLIC_` variable can be read in client code, so it is inlined into the JavaScript sent to browsers, including the island that called the API directly "just to test". Treat a key that has had that prefix as leaked.
- **"Today" from `new Date().toISOString()`.** Servers usually run in UTC. At `2026-12-05T20:00Z` that gives 5 December, but it is already 01:30 on 6 December in Varanasi, so the page would show yesterday's tithi for the first five and a half hours of each Indian day. `cityDate(330, now)` returned `2026-12-06` for that instant.

## Questions

**Which AstroNode endpoints does the Astro example call?**

1 endpoint: Panchang (`POST /v1/panchang`).

**Was the Astro code on this page actually run?**

`src/lib/panchang.ts` and the `GET` endpoint in `src/pages/api/panchang.ts` were executed on Node 24 against the in-memory API (the endpoint called with a `URL` and a `Request`, as Astro passes them), with `astro:env/server` replaced by a stand-in that reads the same two variables. `astro.config.mjs` and the `.astro` page were not run, because Astro is not installed on the build machine.

## Endpoints

- [`POST /v1/panchang`](https://astronode.dev/capabilities/vedic/panchang) - Panchang API
