# Call the astrology API from Next.js without leaking the key

> In Next.js the API key belongs in code that only ever runs on the server: a route handler, a server component or a server action. Here is the smallest layout that keeps it there, with a real chart rendered from the response.

Source: https://astronode.dev/integrations/nextjs · Updated: 2026-12-01

**How this page was verified:** `lib/astronode.ts` and the route handler were executed on Node 24 against the in-memory API (a web-standard `Request` in, `Response` out - exactly what Next.js passes). The server component is JSX and was not rendered.

## Where the key lives

Put `ASTRONODE_API_KEY` in `.env.local` (and in your host's environment for production) **without** a `NEXT_PUBLIC_` prefix. Unprefixed variables are only available to server code. Then keep every AstroNode call in one module that starts with `import "server-only"`: if a client component ever imports it, the build fails instead of quietly bundling the call.

`.env.local` - never committed:

```bash
ASTRONODE_API_KEY=aie_live_...
# optional, e.g. a staging host
ASTRONODE_BASE_URL=https://api.astronode.dev
```

## One module for the call

`lib/astronode.ts`:

```ts
import "server-only";

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

export type Birth = {
  date: string; // "1973-04-24"
  time: string; // "17:25:00" - local wall-clock time
  tz_offset_minutes: number; // 330 for IST, east-positive
  lat: number;
  lng: number;
};

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

export type BirthChart = {
  ascendant: { sign: string; degree: number };
  planets: Planet[];
};

export async function birthChart(birth: Birth): Promise<BirthChart> {
  const res = await fetch(`${BASE}/v1/charts/birth`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.ASTRONODE_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(birth),
    cache: "no-store",
  });
  const json = await res.json();
  if (!res.ok) throw new Error(`${json.error.code}: ${json.error.message}`);
  return json.data;
}
```

`cache: "no-store"` makes the intent explicit across Next.js versions (older App Router releases cached `fetch` by default). Caching is still worth doing - the engine returns the same chart for the same birth - but do it deliberately, keyed on the birth data, rather than by accident.

## Expose it to the browser through a route handler

If a client component needs the chart (a form that submits birth details), give it your own endpoint. The browser talks to `/api/chart`; only the server talks to AstroNode.

`app/api/chart/route.ts`:

```ts
import { birthChart, type Birth } from "@/lib/astronode";

export async function POST(request: Request) {
  const birth = (await request.json()) as Birth;
  try {
    return Response.json(await birthChart(birth));
  } catch (err) {
    return Response.json({ message: (err as Error).message }, { status: 400 });
  }
}
```

Forward only the five birth fields. The birth input rejects unknown keys, so a form that also posts a `place` label gets a real `400` back: `{"message": "VALIDATION_ERROR: Request validation failed"}` from the handler above. Strip display-only fields before the call - see [VALIDATION_ERROR](https://astronode.dev/docs/errors/validation-error).

## Render it in a server component

When the birth data is already on the server (a saved profile), skip the route handler and call the module directly from the page. Nothing about the request reaches the client except the HTML.

`app/chart/page.tsx`:

```tsx
import { birthChart } from "@/lib/astronode";

export default async function ChartPage() {
  const chart = await birthChart({
    date: "1973-04-24", time: "17:25:00", tz_offset_minutes: 330, lat: 19.076, lng: 72.8777,
  });
  return (
    <table>
      <caption>Ascendant {chart.ascendant.sign} {chart.ascendant.degree.toFixed(2)}°</caption>
      <tbody>
        {chart.planets.map((p) => (
          <tr key={p.name}>
            <th>{p.name}{p.retrograde ? " (R)" : ""}</th>
            <td>{p.sign} {p.degree_in_sign.toFixed(2)}°</td>
            <td>House {p.house}</td>
            <td>{p.nakshatra} {p.nakshatra_pada}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}
```

*First rows the handler returned for the sample birth*

| Field | Value |
| --- | --- |
| `ascendant` | Virgo 19.76° |
| Sun | Aries 10.67°, house 8, Ashwini pada 4 |
| Moon | Sagittarius 26.79°, house 4, Uttara Ashadha pada 1 |
| Rahu / Ketu | `retrograde: true` - the nodes always are |

Houses are whole-sign and longitudes are sidereal Lahiri (`data.meta.house_system`, `data.meta.ayanamsa`). If you compare with another program, read [house systems](https://astronode.dev/guides/house-systems) and [ayanamsa](https://astronode.dev/guides/ayanamsa) first.

## The mistake that bites first: NEXT_PUBLIC_

The request works from a client component the moment you rename the variable to `NEXT_PUBLIC_ASTRONODE_API_KEY` - which is exactly why it is tempting. Next.js inlines every `NEXT_PUBLIC_` value into the JavaScript it sends to browsers at build time, so the key is now in a public file that anyone can read and reuse against your quota.

- If a key has ever been built into a `NEXT_PUBLIC_` variable, treat it as leaked: revoke it in the dashboard and issue a new one.
- `import "server-only"` at the top of `lib/astronode.ts` turns the mistake into a build error.
- Server actions are server code too - calling `birthChart` from a `"use server"` function is fine; calling it from a `"use client"` file is not.

## Questions

**Which AstroNode endpoints does the Next.js example call?**

1 endpoint: Birth Chart (Kundli) (`POST /v1/charts/birth`).

**Was the Next.js code on this page actually run?**

`lib/astronode.ts` and the route handler were executed on Node 24 against the in-memory API (a web-standard `Request` in, `Response` out - exactly what Next.js passes). The server component is JSX and was not rendered.

## Endpoints

- [`POST /v1/charts/birth`](https://astronode.dev/capabilities/vedic/charts-birth) - Birth Chart (Kundli) API
