# An Express endpoint for Mangal Dosha, with caching and idempotency

> Most Node backends that use AstroNode are an Express route in front of one or two endpoints. This one is complete: input shaping, a cache keyed on the birth data, an `Idempotency-Key`, error mapping - and the middleware line whose absence produces the most confusing 400 you will see.

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

**How this page was verified:** The server below was executed as written on Express 4.22 and Node 24 against the in-memory API: the 200, the cache hit, the `lat: 95` 400 and the missing-body-parser 400 are all from that run. The code also runs on Express 5.

## The route

`server.js` - Node 18+ (built-in `fetch`), `ASTRONODE_API_KEY` in the environment:

```js
import { createHash } from "node:crypto";
import express from "express";

const ASTRONODE = process.env.ASTRONODE_BASE_URL ?? "https://api.astronode.dev";
const app = express();
app.use(express.json({ limit: "4kb" })); // without this, req.body is undefined

const BIRTH_KEYS = ["date", "time", "tz_offset_minutes", "lat", "lng"];
const cache = new Map(); // swap for Redis in production

app.post("/api/mangal-dosha", async (req, res, next) => {
  try {
    // Forward only the fields AstroNode accepts, in a fixed order.
    const birth = Object.fromEntries(BIRTH_KEYS.map((k) => [k, req.body?.[k]]));
    const key = createHash("sha256").update(JSON.stringify(birth)).digest("hex");
    if (cache.has(key)) return res.json(cache.get(key));

    const upstream = await fetch(`${ASTRONODE}/v1/dosha/mangal`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.ASTRONODE_API_KEY}`,
        "Content-Type": "application/json",
        "Idempotency-Key": key,
      },
      body: JSON.stringify(birth),
      signal: AbortSignal.timeout(15_000),
    });
    const json = await upstream.json();
    if (!upstream.ok) {
      // 4xx: the caller's input; 5xx/429: ours to retry or surface.
      return res.status(upstream.status < 500 ? upstream.status : 502).json(json.error);
    }
    cache.set(key, json.data); // same birth, same answer: the engine is deterministic
    res.json(json.data);
  } catch (err) {
    next(err); // Express 4 does not catch rejected promises on its own
  }
});

app.listen(3000);
```

- **Whitelisting the five keys** means a client that also sends `name` still gets an answer (the run above returned the same result and the cache still held one entry). Forwarding `req.body` as-is would turn every extra field into a `400`, because the birth input rejects unknown keys.
- **The cache key is the birth data itself.** Output is deterministic for the same input and engine version ([why](https://astronode.dev/guides/deterministic-astrology-calculations)), so a hit never needs revalidating; drop the cache when `meta.engine_version` changes if you want to pick up engine fixes.
- **`Idempotency-Key`** makes a retried POST (after a timeout, say) replay the stored response for 24 hours instead of computing it again. A replay is still recorded as a request, so it is not a way to save quota - the in-process cache is.

## What comes back

`POST /api/mangal-dosha` with the 24 April 1973, 17:25, Mumbai birth:

```json
{
  "present": false,
  "house_of_mars": 5,
  "severity": "none",
  "cancelled": false,
  "cancellation_reasons": [],
  "references": [
    { "from": "lagna", "house": 5, "present": false },
    { "from": "moon",  "house": 2, "present": false },
    { "from": "venus", "house": 10, "present": false }
  ]
}
```

Render `present` and `severity` first, then the three `references`: users who were told "you are manglik" elsewhere usually want to see which reference point (Lagna, Moon or Venus) the claim rests on. With `lat: 95` the route passed through AstroNode's `400` - `{"code": "VALIDATION_ERROR", ... "message": "Too big: expected number to be <=90"}` - so the form can highlight the field.

## The mistake that bites first: no body parser

Express does not parse JSON unless you add `express.json()`, and that middleware only runs when the request's `Content-Type` is `application/json`. Miss either and `req.body` is `undefined`, every birth field is `undefined`, `JSON.stringify` drops them, and AstroNode answers with a 400 that looks like the API's fault:

Real response when the client sent the same JSON as `text/plain`:

```json
{
  "code": "VALIDATION_ERROR",
  "message": "Request validation failed",
  "details": [
    { "instancePath": "/date", "message": "Invalid input: expected string, received undefined" },
    { "instancePath": "/time", "message": "Invalid input: expected string, received undefined" },
    ...
  ]
}
```

"received undefined" for **every** field means your server never read the body. Check the middleware and the client's `Content-Type` before anything else. The other Express trap is version-specific: Express 4 does not route a rejected promise to your error handler, so an `async` handler without `try`/`catch` + `next(err)` leaves the request hanging when `fetch` throws. Express 5 forwards it for you.

## Questions

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

1 endpoint: Mangal Dosha (Manglik) (`POST /v1/dosha/mangal`).

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

The server below was executed as written on Express 4.22 and Node 24 against the in-memory API: the 200, the cache hit, the `lat: 95` 400 and the missing-body-parser 400 are all from that run. The code also runs on Express 5.

## Endpoints

- [`POST /v1/dosha/mangal`](https://astronode.dev/capabilities/vedic/dosha-mangal) - Mangal Dosha (Manglik) API
