Next.js kundli app

A kundli app in Next.js, ready to run

A Next.js App Router app that turns a name, birth date, time and place into a kundli: a North Indian chart drawn as SVG, every planet's sign, degree, house and nakshatra, and the Vimshottari mahadasha timeline with the period running now.

Updated

Download nextjs-kundli-app.zip19 files · runs on a Free-plan key

Run it

bash
unzip nextjs-kundli-app.zip && cd nextjs-kundli-app
cp .env.example .env.local   # put your key in ASTRONODE_API_KEY
npm install
npm run dev                  # http://localhost:3000
Files (19)
  • .env.example1 KB
  • .gitignore1 KB
  • README.md3 KB
  • app/actions.ts1 KB
  • app/api/kundli/route.ts1 KB
  • app/globals.css2 KB
  • app/layout.tsx1 KB
  • app/page.tsx1 KB
  • components/KundliForm.tsx5 KB
  • components/NorthIndianChart.tsx3 KB
  • lib/astronode.ts8 KB
  • lib/chart-layout.ts2 KB
  • package.json1 KB
  • test/fixtures/charts-birth.json3 KB
  • test/fixtures/dasha-vimshottari.json25 KB
  • test/fixtures/error-unauthorized.json1 KB
  • test/kundli.test.ts5 KB
  • tsconfig.json1 KB
  • tsconfig.test.json1 KB

lib/astronode.ts

typescript
// AstroNode API client for this template: input validation, request bodies,
// the HTTP call and response mapping. Pure TypeScript with an injectable
// fetch, so it runs in the offline tests as well as on the server.
// Import it only from server code (the server action and the route handler):
// it reads the API key from the environment.

export const DEFAULT_API_URL = "https://api.astronode.dev";

export interface AstroNodeConfig {
  apiKey: string;
  baseUrl: string;
}

/** Birth input accepted by /v1/charts/birth and /v1/dasha/vimshottari. */
export interface BirthInput {
  date: string; // YYYY-MM-DD
  time: string; // HH:MM or HH:MM:SS, local time at the birth place
  tz_offset_minutes: number; // minutes east of UTC, e.g. 330 for IST
  lat: number;
  lng: number;
}

export interface BirthForm {
  name: string;
  input: BirthInput;
}

// ---- Raw API response shapes (only the fields this template uses) ----

export interface ApiPlanet {
  name: string;
  sign: string;
  house: number;
  degree_in_sign: number;
  nakshatra: string;
  nakshatra_pada: number;
  retrograde: boolean;
}

export interface BirthChartResponse {
  request_id: string;
  data: {
    ascendant: { sign: string; degree: number };
    planets: ApiPlanet[];
    meta: { ayanamsa: string; house_system: string; engine_version: string };
  };
}

export interface DashaPeriod {
  lord: string;
  start: string;
  end: string;
  years: number;
  antardasha?: DashaPeriod[];
}

export interface VimshottariResponse {
  request_id: string;
  data: {
    birth_balance?: { lord: string; remaining_years: number };
    mahadasha: DashaPeriod[];
  };
}

// ---- What the page renders ----

export interface PlanetRow {
  name: string;
  sign: string;
  house: number;
  degree: string; // DD°MM'
  nakshatra: string;
  pada: number;
  retrograde: boolean;
}

export interface DashaRow {
  lord: string;
  start: string; // YYYY-MM-DD
  end: string;
  current: boolean;
}

export interface Kundli {
  name: string;
  input: BirthInput;
  ascendant: { sign: string; degree: string };
  planets: PlanetRow[];
  ayanamsa: string;
  houseSystem: string;
  dasha: {
    mahadashas: DashaRow[];
    current: { mahadasha: string; antardasha: string | null; until: string } | null;
  };
}

/** A problem with what the user typed. */
export class InputError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "InputError";
  }
}

/** An error envelope (`{ error: { code, message } }`) returned by the API. */
export class AstroNodeError extends Error {
  constructor(
    readonly status: number,
    readonly code: string,
    message: string,
    readonly requestId?: string,
  ) {
    super(message);
    this.name = "AstroNodeError";
  }
}

export function readConfig(env: Record<string, string | undefined> = process.env): AstroNodeConfig {
  const apiKey = (env.ASTRONODE_API_KEY ?? "").trim();
  if (!apiKey) {
    throw new InputError("ASTRONODE_API_KEY is not set on the server. Copy .env.example to .env.local and add your key.");
  }
  const baseUrl = ((env.ASTRONODE_API_URL ?? "").trim() || DEFAULT_API_URL).replace(/\/+$/, "");
  return { apiKey, baseUrl };
}

const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
const TIME_RE = /^\d{2}:\d{2}(:\d{2})?$/;

function toNumber(value: unknown, field: string, min: number, max: number): number {
  const text = String(value ?? "").trim();
  const n = Number(text);
  if (text === "" || !Number.isFinite(n)) throw new InputError(`${field} must be a number`);
  if (n < min || n > max) throw new InputError(`${field} must be between ${min} and ${max}`);
  return n;
}

/** Validates form fields (strings from FormData or JSON) into a BirthForm. */
export function parseBirthForm(fields: Record<string, unknown>): BirthForm {
  const name = String(fields.name ?? "").trim();
  const date = String(fields.date ?? "").trim();
  const time = String(fields.time ?? "").trim();
  if (!DATE_RE.test(date)) throw new InputError("Birth date must look like 1993-07-04");
  if (!TIME_RE.test(time)) throw new InputError("Birth time must look like 09:27 (24-hour)");
  const tz = toNumber(fields.tz_offset_minutes, "UTC offset (minutes)", -840, 840);
  if (!Number.isInteger(tz)) throw new InputError("UTC offset must be whole minutes");
  return {
    name: name || "Unnamed",
    input: {
      date,
      time,
      tz_offset_minutes: tz,
      lat: toNumber(fields.lat, "Latitude", -90, 90),
      lng: toNumber(fields.lng, "Longitude", -180, 180),
    },
  };
}

/** 9.9358 -> "09°56'" */
export function formatDegree(deg: number): string {
  let d = Math.floor(deg);
  let m = Math.round((deg - d) * 60);
  if (m === 60) {
    d += 1;
    m = 0;
  }
  return `${String(d).padStart(2, "0")}°${String(m).padStart(2, "0")}'`;
}

export function mapChart(res: BirthChartResponse) {
  const { ascendant, planets, meta } = res.data;
  return {
    ascendant: { sign: ascendant.sign, degree: formatDegree(ascendant.degree) },
    planets: planets.map(
      (p): PlanetRow => ({
        name: p.name,
        sign: p.sign,
        house: p.house,
        degree: formatDegree(p.degree_in_sign),
        nakshatra: p.nakshatra,
        pada: p.nakshatra_pada,
        retrograde: p.retrograde,
      }),
    ),
    ayanamsa: meta.ayanamsa,
    houseSystem: meta.house_system,
  };
}

export function mapDasha(res: VimshottariResponse, now: Date = new Date()): Kundli["dasha"] {
  const t = now.getTime();
  const isCurrent = (p: DashaPeriod) => Date.parse(p.start) <= t && t < Date.parse(p.end);
  const maha = res.data.mahadasha;
  const currentMaha = maha.find(isCurrent);
  const currentAntar = currentMaha?.antardasha?.find(isCurrent);
  return {
    mahadashas: maha.map((p) => ({
      lord: p.lord,
      start: p.start.slice(0, 10),
      end: p.end.slice(0, 10),
      current: p === currentMaha,
    })),
    current: currentMaha
      ? {
          mahadasha: currentMaha.lord,
          antardasha: currentAntar?.lord ?? null,
          until: (currentAntar ?? currentMaha).end.slice(0, 10),
        }
      : null,
  };
}

type FetchLike = (url: string, init: RequestInit) => Promise<Response>;

/** POSTs JSON to the API with the Bearer key; throws AstroNodeError on an error envelope. */
export async function callAstroNode<T>(
  config: AstroNodeConfig,
  path: string,
  body: unknown,
  fetchImpl: FetchLike = fetch,
): Promise<T> {
  const res = await fetchImpl(`${config.baseUrl}${path}`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${config.apiKey}`,
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify(body),
    cache: "no-store",
  });
  const text = await res.text();
  let json: { request_id?: string; error?: { code?: string; message?: string } } | undefined;
  try {
    json = text ? JSON.parse(text) : undefined;
  } catch {
    json = undefined;
  }
  if (!res.ok || !json || json.error) {
    throw new AstroNodeError(
      res.status,
      json?.error?.code ?? "HTTP_ERROR",
      json?.error?.message ?? `AstroNode API returned HTTP ${res.status}`,
      json?.request_id,
    );
  }
  return json as T;
}

/** Calls the birth chart and Vimshottari dasha endpoints in parallel and maps both. */
export async function getKundli(
  config: AstroNodeConfig,
  form: BirthForm,
  fetchImpl: FetchLike = fetch,
  now: Date = new Date(),
): Promise<Kundli> {
  const [chart, dasha] = await Promise.all([
    callAstroNode<BirthChartResponse>(config, "/v1/charts/birth", form.input, fetchImpl),
    callAstroNode<VimshottariResponse>(config, "/v1/dasha/vimshottari", { ...form.input, levels: 2 }, fetchImpl),
  ]);
  return { name: form.name, input: form.input, ...mapChart(chart), dasha: mapDasha(dasha, now) };
}

/** Turns any thrown error into a message that is safe and useful to show the user. */
export function errorMessage(err: unknown): string {
  if (err instanceof InputError) return err.message;
  if (err instanceof AstroNodeError) {
    return `AstroNode API error (${err.status} ${err.code}): ${err.message}`;
  }
  return `Could not reach the AstroNode API: ${err instanceof Error ? err.message : String(err)}`;
}

app/actions.ts

typescript
"use server";

// Server action behind the form. Runs only on the server, so the API key
// (read from the environment) never reaches the browser.

import { errorMessage, getKundli, parseBirthForm, readConfig, type Kundli } from "../lib/astronode";

export type FormFields = Record<"name" | "date" | "time" | "lat" | "lng" | "tz_offset_minutes", string>;

export type KundliState =
  | { status: "idle"; fields: FormFields }
  | { status: "error"; fields: FormFields; message: string }
  | { status: "ok"; fields: FormFields; kundli: Kundli };

const FIELD_NAMES: Array<keyof FormFields> = ["name", "date", "time", "lat", "lng", "tz_offset_minutes"];

export async function generateKundli(_prev: KundliState, formData: FormData): Promise<KundliState> {
  const fields = Object.fromEntries(FIELD_NAMES.map((k) => [k, String(formData.get(k) ?? "")])) as FormFields;
  try {
    const kundli = await getKundli(readConfig(), parseBirthForm(fields));
    return { status: "ok", fields, kundli };
  } catch (err) {
    return { status: "error", fields, message: errorMessage(err) };
  }
}

components/NorthIndianChart.tsx

tsx
// Self-contained North Indian (diamond) birth chart as SVG, inline styles only.
// Each house shows its sign number (Aries = 1) and the planets in it.

import {
  CHART_SIZE,
  HOUSE_CENTROIDS,
  labelsByHouse,
  signNumberForHouse,
  type ChartPlanet,
} from "../lib/chart-layout";

const COLORS = {
  background: "#fffdf8",
  frame: "#8a3b12",
  line: "#c9a58e",
  sign: "#8a6a55",
  planet: "#1f2430",
  retro: "#b42318",
  asc: "#8a3b12",
};

interface Props {
  ascendantSign: string;
  planets: ReadonlyArray<ChartPlanet>;
  /** Rendered width in px; the SVG scales down on narrow screens. */
  size?: number;
}

export function NorthIndianChart({ ascendantSign, planets, size = 400 }: Props) {
  const S = CHART_SIZE;
  const m = 4; // margin
  const byHouse = labelsByHouse(planets);

  return (
    <svg
      viewBox={`0 0 ${S} ${S}`}
      width={size}
      style={{ width: "100%", maxWidth: size, height: "auto", display: "block", fontFamily: "system-ui, sans-serif" }}
      role="img"
      aria-label={`North Indian birth chart, ${ascendantSign} ascendant`}
    >
      <rect x={m} y={m} width={S - 2 * m} height={S - 2 * m} style={{ fill: COLORS.background, stroke: COLORS.frame, strokeWidth: 1.5 }} />
      <line x1={m} y1={m} x2={S - m} y2={S - m} style={{ stroke: COLORS.line, strokeWidth: 1 }} />
      <line x1={S - m} y1={m} x2={m} y2={S - m} style={{ stroke: COLORS.line, strokeWidth: 1 }} />
      <polygon
        points={`${S / 2},${m} ${S - m},${S / 2} ${S / 2},${S - m} ${m},${S / 2}`}
        style={{ fill: "none", stroke: COLORS.frame, strokeWidth: 1.2 }}
      />

      {HOUSE_CENTROIDS.map((c, i) => {
        const house = i + 1;
        const labels = byHouse[house] ?? [];
        const cols = Math.min(Math.max(labels.length, 1), 3);
        return (
          <g key={house} transform={`translate(${c.x}, ${c.y})`}>
            <text x={0} y={-22} textAnchor="middle" style={{ fontSize: 11, fontWeight: 600, fill: COLORS.sign }}>
              {signNumberForHouse(ascendantSign, house)}
            </text>
            {house === 1 && (
              <text x={0} y={-36} textAnchor="middle" style={{ fontSize: 10, fontWeight: 700, fill: COLORS.asc }}>
                Asc
              </text>
            )}
            {labels.map((label, j) => {
              const x = (j % cols) * 24 - ((cols - 1) * 24) / 2;
              const y = 2 + Math.floor(j / cols) * 15;
              return (
                <text key={label.abbr} x={x} y={y} textAnchor="middle" style={{ fontSize: 13, fontWeight: 700, fill: COLORS.planet }}>
                  {label.abbr}
                  {label.retrograde && (
                    <tspan dy={-5} style={{ fontSize: 8, fill: COLORS.retro }}>
                      R
                    </tspan>
                  )}
                </text>
              );
            })}
          </g>
        );
      })}
    </svg>
  );
}

What it does

  • A form for name, date, local time, latitude, longitude and UTC offset; a server action makes the two API calls, so each kundli costs two calls.
  • Draws the North Indian (diamond) chart as a self-contained SVG component with inline styles - lift components/NorthIndianChart.tsx into any React app.
  • Lists the planets and shows the dasha timeline, marking the mahadasha and antardasha running today.
  • Also exposes POST /api/kundli returning the same data as JSON, for other clients.
  • Shows the API's own error message on the page for a bad key, a plan that is too low, or invalid input.

Endpoints and plan

API calls the template makes
EndpointUsed forPlan
POST /v1/charts/birthAscendant and the nine planets: sign, house, degree, nakshatra, retrogradeFree
POST /v1/dasha/vimshottariMahadashas with their antardashas (levels: 2)Free

Everything it calls is on the Free plan, so a Free test key runs the whole template.

Where things live

FileWhat it holds
lib/astronode.tsInput validation, the two API calls, response mapping - start here to show more fields
lib/chart-layout.tsHouse positions and label points for the diamond chart
components/NorthIndianChart.tsxThe SVG chart
components/KundliForm.tsxThe form and result tables (useActionState)
app/actions.tsThe server action holding the key
app/api/kundli/route.tsThe JSON route

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 the tests against API responses recorded in test/fixtures/ - no key and no network, so it can run in your CI.
  • Deploys as any Next.js app (next build && next start, or a Next.js host); set ASTRONODE_API_KEY in the host's environment, never with a NEXT_PUBLIC_ prefix.
  • On a public site, put rate limiting or sign-in in front of the form and /api/kundli: every submission spends your quota.
  • There is no place search: the form takes coordinates and the UTC offset. Add your own geocoder for a consumer product.

Questions

Does the Next.js kundli template need a paid plan?
No. Both endpoints it calls are on the Free plan, so a Free test key runs it end to end.
Can I use the chart component without the rest of the app?
Yes. components/NorthIndianChart.tsx and lib/chart-layout.ts have no dependencies besides React and take the birth-chart response as their input.
Why are Rahu and Ketu not marked retrograde?
The API returns retrograde: true for Rahu and Ketu, which always move backwards in mean-node terms, so the chart only marks the planets for which retrogression is news.