# Planet positions from Bun: a Bun.serve endpoint and a compiled CLI

> Bun runs TypeScript directly, serves HTTP with `Bun.serve` and can compile a script into a single executable. Here one small module fetches the current sidereal planet positions and is used twice: by a web endpoint and by a command-line tool.

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

**How this page was verified:** `astronode.ts`, the `sky` handler from `server.ts` and `cli.ts` were executed on Node 24 against the in-memory API (they use only `fetch`, `process.env` and web-standard `Request`/`Response`); the CLI output below is from that run. Bun is not installed on the build machine, so `Bun.serve`, `.env` auto-loading and `bun build --compile` were not run.

## One module for the call

`astronode.ts`:

```ts
const BASE = process.env.ASTRONODE_BASE_URL ?? "https://api.astronode.dev";
const KEY = process.env.ASTRONODE_API_KEY ?? "";

// Bun loads .env files on its own. Refuse a test key in production instead of
// finding out from the bill or the data.
if (process.env.NODE_ENV === "production" && !KEY.startsWith("aie_live_")) {
  throw new Error("production needs an aie_live_ key - check which .env file was loaded");
}

export type Planet = { name: string; sign: string; degree_in_sign: number; nakshatra: string; retrograde: boolean };

export async function planetsAt(at: Date, lat = 0, lng = 0): Promise<Planet[]> {
  const iso = at.toISOString(); // UTC, so tz_offset_minutes is 0
  const res = await fetch(`${BASE}/v1/planets`, {
    method: "POST",
    headers: { Authorization: `Bearer ${KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({ date: iso.slice(0, 10), time: iso.slice(11, 19), tz_offset_minutes: 0, lat, lng }),
  });
  const json = await res.json();
  if (!res.ok) throw new Error(`${res.status} ${json.error.code}: ${json.error.message}`);
  return json.data.planets;
}
```

Sending the instant as UTC with `tz_offset_minutes: 0` avoids any time-zone arithmetic: the planets' positions depend only on the instant. `lat` and `lng` affect only the `house` field, which this tool ignores. `POST /v1/planets` is on the Free plan.

## As a web endpoint with Bun.serve

`server.ts` - `bun server.ts`, then `GET /sky?at=2026-12-05T12:00:00Z`:

```ts
import { planetsAt } from "./astronode.ts";

export async function sky(req: Request): Promise<Response> {
  const param = new URL(req.url).searchParams.get("at");
  const at = param ? new Date(param) : new Date();
  if (Number.isNaN(at.getTime())) return Response.json({ error: "bad at" }, { status: 400 });
  try {
    return Response.json(await planetsAt(at));
  } catch (err) {
    return Response.json({ error: (err as Error).message }, { status: 502 });
  }
}

if (import.meta.main) Bun.serve({ port: 3000, fetch: sky });
```

`Bun.serve` takes a plain `fetch(Request) => Response` function, so the handler is an ordinary export you can call in `bun test` without a server. Without the `isNaN` check, `?at=not-a-date` would reach `toISOString()` and throw inside `planetsAt`; with it, the endpoint returns its own `400`.

## As a single binary

`cli.ts`:

```ts
import { planetsAt } from "./astronode.ts";

const at = process.argv[2] ? new Date(process.argv[2]) : new Date();
console.log(`Sidereal (Lahiri) positions at ${at.toISOString()}`);
for (const p of await planetsAt(at)) {
  const deg = p.degree_in_sign.toFixed(2).padStart(5);
  console.log(`${p.name.padEnd(8)} ${p.sign.padEnd(11)} ${deg}°  ${p.nakshatra}${p.retrograde ? "  (R)" : ""}`);
}
```

```bash
bun build --compile cli.ts --outfile sky
ASTRONODE_API_KEY=aie_live_... ./sky 2026-12-05T12:00:00Z
```

Output (from the run of `cli.ts`):

```text
Sidereal (Lahiri) positions at 2026-12-05T12:00:00.000Z
Sun      Scorpio     19.12°  Jyeshtha
Moon     Libra        9.62°  Swati
Mars     Leo          9.31°  Magha
Mercury  Scorpio      4.47°  Anuradha
Jupiter  Leo          2.70°  Magha
Venus    Libra        6.52°  Chitra
Saturn   Pisces      13.72°  Uttara Bhadrapada  (R)
Rahu     Aquarius     0.01°  Dhanishta  (R)
Ketu     Leo          0.01°  Magha  (R)
```

Rahu at 0.01° Aquarius is a sign change in progress: the node moves backwards, its longitude was 300.0001° at 17:00 UTC that day and 299.998° at 18:00. That second reading is Capricorn 29.998°, which `toFixed(2)` prints as "Capricorn 30.00°" - a degree that does not exist. If you display positions near a boundary, truncate (`Math.floor(d * 100) / 100`) rather than round. The compiled binary bundles the Bun runtime, so the target machine needs nothing installed; `--target` cross-compiles for another OS.

## The mistake that bites first: .env files you did not mean to load

Bun reads `.env`, then `.env.production`, `.env.development` or `.env.test` according to `NODE_ENV`, then `.env.local`, from the working directory - with no import and no flag. That is convenient on a laptop and a trap on a server:

- **A Dockerfile with `COPY . .`** copies your local `.env` into the image, so the container quietly runs with your development key, and the key now sits in an image layer. Exclude it with `**/.env*` in `.dockerignore` (a bare `.env` pattern matches only at the root of the build context) and set the variable in the platform's environment instead.
- **A missing production variable no longer fails loudly** if any `.env` file supplies a value. The start-up check in `astronode.ts` turns that into an error: run with `NODE_ENV=production` and a test key, it threw before serving anything.
- **Do not bake the key into the binary.** `bun build --env=inline` (or a `--define` for the variable) replaces `process.env.ASTRONODE_API_KEY` with its value at build time, and anyone with the file can read the string out of it. Leave `process.env` references as they are, so the key is supplied when the binary runs.

When no key reaches the process at all, AstroNode's answer is explicit - from the run with an empty `ASTRONODE_API_KEY`: `401 UNAUTHORIZED: Missing or invalid Authorization header`.

## Questions

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

1 endpoint: Planet Positions (Sidereal) (`POST /v1/planets`).

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

`astronode.ts`, the `sky` handler from `server.ts` and `cli.ts` were executed on Node 24 against the in-memory API (they use only `fetch`, `process.env` and web-standard `Request`/`Response`); the CLI output below is from that run. Bun is not installed on the build machine, so `Bun.serve`, `.env` auto-loading and `bun build --compile` were not run.

## Endpoints

- [`POST /v1/planets`](https://astronode.dev/capabilities/vedic/planets) - Planet Positions (Sidereal) API
