A small Node server and one page for matrimony and matchmaking products: two people's birth details in, the Ashtakoot score out of 36 with all eight kootas, the match verdict, and each person's manglik status with its cancellations.
unzip matrimony-starter.zip && cd matrimony-starter
cp .env.example .env # put your key in ASTRONODE_API_KEY
node --env-file=.env server.js # http://localhost:3000
Files (13)
.env.example1 KB
.gitignore1 KB
README.md3 KB
lib.js6 KB
package.json1 KB
public/app.js3 KB
public/index.html6 KB
server.js3 KB
test/fixtures/compatibility.json3 KB
test/fixtures/error-unauthorized.json1 KB
test/fixtures/mangal-person-a.json1 KB
test/fixtures/mangal-person-b.json1 KB
test/match.test.js7 KB
lib.js
javascript
// AstroNode matrimony starter - request building, API calls and response mapping.
// Kept free of any server code so it can be unit-tested without network or a key.
export const DEFAULT_API_URL = "https://api.astronode.dev";
/** Display names for the 8 Ashtakoot kootas, in the order the API returns them. */
export const KOOTA_LABELS = {
varna: "Varna",
vashya: "Vashya",
tara: "Tara",
yoni: "Yoni",
graha_maitri: "Graha Maitri",
gana: "Gana",
bhakoot: "Bhakoot",
nadi: "Nadi",
};
/** A problem with what the user typed. The server answers it with HTTP 400. */
export class InputError extends Error {
constructor(message) {
super(message);
this.name = "InputError";
}
}
/** An error envelope (`{ error: { code, message } }`) returned by the AstroNode API. */
export class AstroNodeError extends Error {
constructor(status, code, message, requestId) {
super(message);
this.name = "AstroNodeError";
this.status = status;
this.code = code;
this.requestId = requestId;
}
}
export function readConfig(env = process.env) {
const apiKey = (env.ASTRONODE_API_KEY ?? "").trim();
const baseUrl = (env.ASTRONODE_API_URL ?? "").trim() || DEFAULT_API_URL;
return { apiKey, baseUrl: baseUrl.replace(/\/+$/, "") };
}
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
const TIME_RE = /^\d{2}:\d{2}(:\d{2})?$/;
function toNumber(value, field, label, min, max) {
const n = typeof value === "number" ? value : Number(String(value ?? "").trim());
if (String(value ?? "").trim() === "" || !Number.isFinite(n)) {
throw new InputError(`${label}: ${field} must be a number`);
}
if (n < min || n > max) {
throw new InputError(`${label}: ${field} must be between ${min} and ${max}`);
}
return n;
}
/**
* Validates one person's form fields and turns them into the API's birth input.
* `tz_offset_minutes` is minutes east of UTC (330 for IST, -300 for US Eastern).
*/
export function parsePerson(raw, label) {
if (!raw || typeof raw !== "object") throw new InputError(`${label}: birth details are missing`);
const name = String(raw.name ?? "").trim() || label;
const date = String(raw.date ?? "").trim();
const time = String(raw.time ?? "").trim();
if (!DATE_RE.test(date)) throw new InputError(`${label}: date must look like 1993-07-04`);
if (!TIME_RE.test(time)) throw new InputError(`${label}: time must look like 09:27 (24-hour)`);
const tz = toNumber(raw.tz_offset_minutes, "timezone offset", label, -840, 840);
if (!Number.isInteger(tz)) throw new InputError(`${label}: timezone offset must be whole minutes`);
const gender = raw.gender === "male" || raw.gender === "female" ? raw.gender : undefined;
return {
name,
gender,
birth: {
date,
time,
tz_offset_minutes: tz,
lat: toNumber(raw.lat, "latitude", label, -90, 90),
lng: toNumber(raw.lng, "longitude", label, -180, 180),
},
};
}
/** Body for `POST /v1/compatibility`. Genders decide who is scored as groom/bride. */
export function buildCompatibilityBody(a, b) {
const body = { person_a: a.birth, person_b: b.birth };
const genders = {};
if (a.gender) genders.person_a = a.gender;
if (b.gender) genders.person_b = b.gender;
if (Object.keys(genders).length > 0) body.genders = genders;
return body;
}
function mapManglik(person, mangal) {
const present = Boolean(mangal.present);
const cancelled = Boolean(mangal.cancelled);
const effective = present && !cancelled;
let summary;
if (!present) summary = "Not manglik";
else if (cancelled) summary = "Manglik (cancelled)";
else summary = `Manglik (${mangal.severity})`;
return {
name: person.name,
manglik: effective,
present,
cancelled,
severity: mangal.severity,
house_of_mars: mangal.house_of_mars,
reasons: Array.isArray(mangal.cancellation_reasons) ? mangal.cancellation_reasons : [],
summary,
};
}
/**
* Maps the three API responses (compatibility + one mangal dosha per person)
* into the shape the page renders.
*/
export function mapMatch({ a, b, compatibility, mangalA, mangalB }) {
const c = compatibility.data;
return {
people: [a.name, b.name],
total: { score: c.total.score, max: c.total.max, bucket: c.total.bucket },
match_percentage: c.match_percentage,
kootas: c.koots.map((k) => ({
key: k.name,
label: KOOTA_LABELS[k.name] ?? k.name,
score: k.score,
initial_score: k.initial_score,
max: k.max,
pass: k.pass,
note: k.cancellation_note,
})),
manglik: {
status: c.manglik_match.status,
note: c.manglik_match.note,
people: [mapManglik(a, mangalA.data), mapManglik(b, mangalB.data)],
},
groom: c.slotting.groom === "person_a" ? a.name : b.name,
request_ids: [compatibility.request_id, mangalA.request_id, mangalB.request_id],
};
}
/** POSTs a JSON body to the API and returns the parsed JSON, or throws AstroNodeError. */
export async function callAstroNode(config, path, body, fetchImpl = globalThis.fetch) {
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),
});
const text = await res.text();
let json;
try {
json = text ? JSON.parse(text) : undefined;
} catch {
json = undefined;
}
if (!res.ok || !json || json.error) {
const err = json?.error;
throw new AstroNodeError(
res.status,
err?.code ?? "HTTP_ERROR",
err?.message ?? `AstroNode API returned HTTP ${res.status}`,
json?.request_id,
);
}
return json;
}
/** Validates both people, calls the three endpoints in parallel and maps the result. */
export async function runMatch(config, rawA, rawB, fetchImpl = globalThis.fetch) {
const a = parsePerson(rawA, "Person 1");
const b = parsePerson(rawB, "Person 2");
const [compatibility, mangalA, mangalB] = await Promise.all([
callAstroNode(config, "/v1/compatibility", buildCompatibilityBody(a, b), fetchImpl),
callAstroNode(config, "/v1/dosha/mangal", a.birth, fetchImpl),
callAstroNode(config, "/v1/dosha/mangal", b.birth, fetchImpl),
]);
return mapMatch({ a, b, compatibility, mangalA, mangalB });
}
server.js
javascript
// AstroNode matrimony starter - a zero-dependency Node 20+ server.
// The browser only talks to this server; the API key never leaves it.
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { AstroNodeError, InputError, readConfig, runMatch } from "./lib.js";
const PUBLIC_DIR = new URL("./public/", import.meta.url);
const STATIC_FILES = {
"/": { file: "index.html", type: "text/html; charset=utf-8" },
"/app.js": { file: "app.js", type: "text/javascript; charset=utf-8" },
};
const MAX_BODY_BYTES = 16 * 1024;
function sendJson(res, status, payload) {
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
res.end(JSON.stringify(payload));
}
async function readJsonBody(req) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > MAX_BODY_BYTES) throw new InputError("Request body is too large");
chunks.push(chunk);
}
try {
return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
} catch {
throw new InputError("Request body must be JSON");
}
}
/** Builds the request handler. `fetchImpl` is injectable so tests can run offline. */
export function createHandler(config, fetchImpl = globalThis.fetch) {
return async function handler(req, res) {
const url = new URL(req.url ?? "/", "http://localhost");
try {
if (req.method === "GET" && STATIC_FILES[url.pathname]) {
const { file, type } = STATIC_FILES[url.pathname];
const body = await readFile(new URL(file, PUBLIC_DIR));
res.writeHead(200, { "Content-Type": type });
res.end(body);
return;
}
if (req.method === "GET" && url.pathname === "/healthz") {
sendJson(res, 200, { ok: true });
return;
}
if (req.method === "POST" && url.pathname === "/api/match") {
const { person_a, person_b } = await readJsonBody(req);
const result = await runMatch(config, person_a, person_b, fetchImpl);
sendJson(res, 200, result);
return;
}
sendJson(res, 404, { error: { code: "NOT_FOUND", message: "Not found" } });
} catch (err) {
if (err instanceof InputError) {
sendJson(res, 400, { error: { code: "INVALID_INPUT", message: err.message } });
} else if (err instanceof AstroNodeError) {
// Pass the API's own status and message through so the page can show it.
const status = err.status >= 400 && err.status < 600 ? err.status : 502;
sendJson(res, status, {
error: { code: err.code, message: `AstroNode API: ${err.message}`, request_id: err.requestId },
});
} else {
console.error(err);
sendJson(res, 502, {
error: { code: "UPSTREAM_UNREACHABLE", message: `Could not reach the AstroNode API (${err.message})` },
});
}
}
};
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const config = readConfig();
if (!config.apiKey) {
console.error("ASTRONODE_API_KEY is not set. Copy .env.example to .env and add your key.");
process.exit(1);
}
const port = Number(process.env.PORT) || 3000;
createServer(createHandler(config)).listen(port, () => {
console.log(`Matrimony starter on http://localhost:${port} (API: ${config.baseUrl})`);
});
}
What it does
One page with two birth-detail forms; the browser posts to the template's own /api/match, never to AstroNode.
Shows the total out of 36, the verdict, and each koota's score against its maximum - including kootas raised by a cancellation, such as a Bhakoot cancelled to full marks.
Shows each person's Mangal dosha result next to the pair's manglik compatibility, because the two answer different questions (see the FAQ).
Three API calls per match. Rejects bad input with a 400 and refuses to start without a key.
Endpoints and plan
API calls the template makes
Endpoint
Used for
Plan
POST /v1/compatibility
Ashtakoot: eight kootas, total out of 36, verdict, manglik match
Hobby
POST /v1/dosha/mangal
Each person's own Mangal dosha and its cancellations (called twice)
Free
It needs a Hobby key or above: at least one endpoint it calls is not on the Free plan. See pricing.
Where things live
File
What it holds
lib.js
Input checks, request bodies, the three API calls, response mapping
server.js
node:http server: static files and POST /api/match
public/index.html, public/app.js
The page and its script
test/match.test.js
Tests, including the real server against a stub replaying recorded responses
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.
Runs anywhere Node 20 runs, with no npm install: a VM, a container, or a platform such as Render or Fly.
Matching is usually behind sign-in on a matrimony site; if this page is public, rate-limit /api/match.
Questions
Why does the match say a person is not manglik when their own report says they are?
In the compatibility response, boy_present and girl_present mean manglik after cancellations, while POST /v1/dosha/mangal reports the dosha as present and cancelled. The template shows both so the difference is visible.
Which plan does the matrimony starter need?
Hobby or above, for POST /v1/compatibility. The Mangal dosha calls are on the Free plan.
Can it match one profile against many?
This starter matches one pair. For one profile against a list, use POST /v1/compatibility/batch, covered in the matrimony use case.