← Integrations

Web framework · TypeScript

A Western natal chart in Angular, served through server.ts

An Angular app with server-side rendering already has a Node server: the Express app in server.ts. Add an /api route there, keep the AstroNode key in its environment, and let HttpClient call your route. Without SSR the same route lives in any small Node service.

Updated

How this page was checked: src/server/astro-routes.ts was executed on Node 24 against the in-memory API, mounted on a real Express app (Express 4.22 and 5.3, both from the workspace) next to a catch-all that stands in for the Angular renderer. The request the NatalService makes was sent to that app with Node's fetch. Angular itself (the service, environment.ts, server.ts) is not installed on the build machine and was not run.

environment.ts is not a secrets file

ts
// src/environments/environment.ts - compiled into the browser bundle.
// fileReplacements swaps in environment.prod.ts for production builds;
// that file ships to every browser too.
export const environment = {
  apiBase: "/api", // your own server - never AstroNode, never a key
};

environment.ts is ordinary TypeScript that the application imports, so the compiler bundles it into main-*.js. The fileReplacements setting in angular.json decides which file is bundled, not whether it is shipped to the browser. Anything in it can be read in the browser's developer tools. It is the right place for the URL of your own API, and the wrong place for an AstroNode key.

The server route

src/server/astro-routes.ts:

ts
import express, { type Express } from "express";

const ASTRONODE = process.env["ASTRONODE_BASE_URL"] ?? "https://api.astronode.dev";
const HOUSE_SYSTEMS = new Set(["placidus", "koch", "equal", "whole-sign", "porphyry"]);

type Body = Partial<Record<"date" | "time" | "house_system", string>> &
  Partial<Record<"tz_offset_minutes" | "lat" | "lng", number>>;

export function registerAstroRoutes(app: Express): void {
  app.post("/api/natal", express.json({ limit: "2kb" }), async (req, res) => {
    const { date, time, tz_offset_minutes, lat, lng, house_system } = (req.body ?? {}) as Body;
    const body = {
      date, time, tz_offset_minutes, lat, lng,
      // Optional on this endpoint; forward it only if it is one the API knows.
      ...(house_system && HOUSE_SYSTEMS.has(house_system) ? { house_system } : {}),
    };
    try {
      const upstream = await fetch(`${ASTRONODE}/v1/western/natal/chart`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${process.env["ASTRONODE_API_KEY"]}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify(body),
        signal: AbortSignal.timeout(10_000),
      });
      const json = await upstream.json();
      if (!upstream.ok) {
        res.status(upstream.status >= 500 ? 502 : upstream.status).json({ code: json.error.code });
        return;
      }
      const c = json.data;
      res.json({
        houseSystem: c.meta.house_system,
        ascendant: `${c.ascendant.sign} ${c.ascendant.degree.toFixed(2)}`,
        midheaven: `${c.midheaven.sign} ${c.midheaven.degree.toFixed(2)}`,
        planets: c.planets.map((p: { planet: string; sign: string; degree_in_sign: number; house: number; retrograde: boolean }) => ({
          name: p.planet, sign: p.sign, degree: +p.degree_in_sign.toFixed(2), house: p.house, retrograde: p.retrograde,
        })),
      });
    } catch {
      res.status(504).json({ code: "UPSTREAM_TIMEOUT" });
    }
  });
}
ts
// server.ts, as generated by `ng new --ssr` or `ng add @angular/ssr`
import { registerAstroRoutes } from "./src/server/astro-routes";

// ...inside the function that creates the Express app:
registerAstroRoutes(server); // before express.static and the Angular render handler

Order matters. The generated server.ts ends with a handler that renders Angular for every remaining request, and a route registered after it never runs. In the test app, /api/natal returned JSON and any other path fell through to the stand-in renderer. Read the key with process.env["ASTRONODE_API_KEY"]: the bracket form keeps Angular's strict noPropertyAccessFromIndexSignature setting happy.

The service

src/app/natal.service.ts:

ts
import { HttpClient } from "@angular/common/http";
import { Injectable, inject } from "@angular/core";
import { environment } from "../environments/environment";

export type Birth = {
  date: string; time: string; tz_offset_minutes: number; lat: number; lng: number;
  house_system?: "placidus" | "koch" | "equal" | "whole-sign" | "porphyry";
};
export type NatalSummary = {
  houseSystem: string; ascendant: string; midheaven: string;
  planets: { name: string; sign: string; degree: number; house: number; retrograde: boolean }[];
};

@Injectable({ providedIn: "root" })
export class NatalService {
  private http = inject(HttpClient);

  chart(birth: Birth) {
    return this.http.post<NatalSummary>(`${environment.apiBase}/natal`, birth);
  }
}

With SSR enabled, register provideHttpClient(withFetch()) in app.config.ts; Angular recommends the fetch backend for server rendering and warns when it is missing. Without SSR, run the route in a separate Node process and proxy /api to it during ng serve:

proxy.conf.json, referenced from the serve target's proxyConfig:

json
{
  "/api": { "target": "http://localhost:4000", "secure": false }
}

What came back

15 August 1990, 06:40 BST (`tz_offset_minutes: 60`), London
PointPositionHouse (Placidus)House (whole-sign)
AscendantVirgo 0.66°--
MidheavenTaurus 20.69°--
SunLeo 22.15°1212
MoonGemini 13.06°1010
VenusLeo 1.61°1112
MarsTaurus 21.23°109
SaturnCapricorn 19.88°, retrograde55

The Western endpoints are tropical and default to Placidus; house_system is the one optional field this endpoint accepts besides the birth. With an ascendant at 0.66° Virgo, Venus and Mars change houses between systems, which is the kind of row users report as a bug, so show the system (houseSystem in the response) next to the table. The route drops values it does not recognise: "regiomontanus" came back as Placidus rather than as an error. See house systems. The natal endpoints need the Hobby plan.

The mistakes that bite first

  • The key in `environment.prod.ts`, on the theory that production builds are minified. Minifying does not hide the string. Revoke it and move the call behind the route.
  • Numbers that arrive as strings. Reactive forms keep a text input's value as a string. Posting tz_offset_minutes: "60" came back as 400 VALIDATION_ERROR. Use type="number" inputs (Angular's number accessor yields numbers) or convert before calling the service.
  • No JSON body parser on the route. The generated server.ts does not parse JSON bodies. Without the route's express.json() middleware, or when a client sends text/plain, the body is empty and AstroNode answers 400. The route does both checks itself.

Questions

Which AstroNode endpoints does the Angular example call?
1 endpoint: Western Natal Chart (POST /v1/western/natal/chart).
Was the Angular code on this page actually run?
src/server/astro-routes.ts was executed on Node 24 against the in-memory API, mounted on a real Express app (Express 4.22 and 5.3, both from the workspace) next to a catch-all that stands in for the Angular renderer. The request the NatalService makes was sent to that app with Node's fetch. Angular itself (the service, environment.ts, server.ts) is not installed on the build machine and was not run.