# Kundli matching in Remix: an action, a .server module and a blank field

> In Remix the server boundary is the route module's `loader` and `action`: they run on the server, and what they return is serialised to the browser. Put the AstroNode call in a `.server.ts` module, call it from the action, and return only what the page draws.

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

**How this page was verified:** `app/lib/astronode.server.ts` and the route's `action` were executed on Node 24 against the in-memory API, by calling `action` with a form-encoded web `Request`. `@remix-run/react` and the JSX runtime were stubbed so the module could load; the component was not rendered. The 19/36, 27/36 and 400 results below are from those runs.

## The .server module

`app/lib/astronode.server.ts`:

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

export type Birth = {
  date: string;
  time: string;
  tz_offset_minutes: number;
  lat: number;
  lng: number;
};

type Koot = { name: string; score: number; max: number; cancellation_note: string };
type Match = {
  total: { score: number; max: number; bucket: string };
  koots: Koot[];
  manglik_match: { status: string; note: string };
};
type ApiError = { code: string; message: string; details?: { instancePath: string; message: string }[] };

export async function gunMilan(
  person_a: Birth,
  person_b: Birth,
): Promise<{ ok: true; data: Match } | { ok: false; status: number; error: ApiError }> {
  const res = await fetch(`${BASE}/v1/compatibility`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.ASTRONODE_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ person_a, person_b }),
  });
  const json = await res.json();
  return res.ok ? { ok: true, data: json.data } : { ok: false, status: res.status, error: json.error };
}
```

The `.server` in the file name is a promise to the compiler: this module never goes to the browser. With the Vite plugin, a component that imports it directly is a build error, so the key cannot be bundled by accident. On Node it reads `process.env`. On Cloudflare there is no `process.env`, and the bindings arrive on the action's `context`, so pass the key in as an argument there.

## The route

`app/routes/match.tsx`:

```tsx
import { Form, useActionData } from "@remix-run/react";
import type { ActionFunctionArgs } from "@remix-run/node";
import { gunMilan, type Birth } from "~/lib/astronode.server";

// Number("") is 0, a valid UTC offset. Blank must fail, not mean Greenwich.
const num = (v: FormDataEntryValue | null) => (v === null || v === "" ? NaN : Number(v));

const birthFrom = (form: FormData, p: "a" | "b"): Birth => ({
  date: String(form.get(`${p}_date`)),
  time: String(form.get(`${p}_time`)), // <input type="time"> sends "21:15" - accepted as is
  tz_offset_minutes: num(form.get(`${p}_tz`)),
  lat: num(form.get(`${p}_lat`)),
  lng: num(form.get(`${p}_lng`)),
});

export async function action({ request }: ActionFunctionArgs) {
  const form = await request.formData();
  const result = await gunMilan(birthFrom(form, "a"), birthFrom(form, "b"));
  if (!result.ok) {
    return { error: result.error.message, fields: result.error.details?.map((d) => d.instancePath) ?? [] };
  }
  // Everything returned here is serialised into the page: send what the UI renders.
  const { total, koots, manglik_match } = result.data;
  return {
    total,
    koots: koots.map((k) => ({ name: k.name, score: k.score, max: k.max, note: k.cancellation_note })),
    manglik: manglik_match.status,
  };
}

export default function MatchRoute() {
  const result = useActionData<typeof action>();
  return (
    <Form method="post">
      {/* a_date, a_time, a_tz, a_lat, a_lng and the same five for b_ */}
      <button type="submit">Match</button>
      {result && "error" in result && <p role="alert">{result.error}: {result.fields.join(", ")}</p>}
      {result && "total" in result && (
        <table>
          <caption>{result.total.score} / {result.total.max} ({result.total.bucket})</caption>
          <tbody>
            {result.koots.map((k) => (
              <tr key={k.name}><th>{k.name}</th><td>{k.score} / {k.max}</td><td>{k.note}</td></tr>
            ))}
          </tbody>
        </table>
      )}
    </Form>
  );
}
```

The action receives a standard `Request`, so `request.formData()` is the web API, not a Remix one. A plain object returned from the action is serialised for you, and `useActionData<typeof action>()` gives the component the union of the success and error shapes. On older Remix versions, wrap the object in `json()`.

## What came back

*Person A: 15 Aug 1990, 06:40, Bengaluru. Person B: 3 Feb 1988, 21:15, Delhi. Both +330.*

| Koot | Score | Note from the API |
| --- | --- | --- |
| varna | 1 / 1 | Varna Dosha mitigated (strong Moon in the boy's chart) |
| tara | 2 / 3 | Tara Dosha partially cancelled (only one direction has dosha) |
| graha_maitri | 3 / 5 | Maitri Dosha cancelled due to both partners' strong Moons |
| gana | 3 / 6 | Gana Dosha cancelled due to both partners' strong Moons |
| bhakoot | 7 / 7 |  |
| nadi | 0 / 8 | Nadi Dosha Present |
| **total** | **19 / 36** | `bucket: "Moderate"`, manglik `compatible` |

The notes say "boy" and "girl". The API decides who is who from the order of the request, not from anything you send about gender (`slotting: { groom: "person_a", basis: "order" }`). With the two births swapped, the total was still 19, but the manglik note moved from "the boy" to "the girl". Label the form's two halves to match, or show the notes without those words. The scoring itself: [Ashtakoot gun milan scoring](https://astronode.dev/guides/ashtakoot-gun-milan-scoring). The endpoint needs the Hobby plan; a Free key gets [`403 PLAN_REQUIRED`](https://astronode.dev/docs/errors/plan-required).

## The mistake that bites first: Number("") is 0

`FormData` values are strings, and the obvious conversion is `Number(...)`. But `Number("")` is `0`, and `0` is a valid `tz_offset_minutes`: Greenwich. With an earlier version of `birthFrom` that used bare `Number`, leaving person B's offset blank did not produce an error. It moved the Delhi birth by five and a half hours, and the same couple scored **27 / 36, "Good"** with nadi 8/8, instead of 19.

The `num` helper above turns a blank field into `NaN`, which `JSON.stringify` sends as `null`, so AstroNode refuses it. The guarded action returned `{ error: "Request validation failed", fields: ["/person_b/tz_offset_minutes"] }`, which tells the form which input to highlight. The same check applies to `lat` and `lng`, where `0` is also a real place (in the Gulf of Guinea). How to get the right offset for a birth: [birth time and time zones](https://astronode.dev/guides/birth-time-and-time-zones).

## Questions

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

1 endpoint: Kundli Matching (Ashtakoot Gun Milan) (`POST /v1/compatibility`).

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

`app/lib/astronode.server.ts` and the route's `action` were executed on Node 24 against the in-memory API, by calling `action` with a form-encoded web `Request`. `@remix-run/react` and the JSX runtime were stubbed so the module could load; the component was not rendered. The 19/36, 27/36 and 400 results below are from those runs.

## Endpoints

- [`POST /v1/compatibility`](https://astronode.dev/capabilities/compatibility/compatibility) - Kundli Matching (Ashtakoot Gun Milan) API
