# Add towers to an existing portal

> Put a tower on a page of a portal you already run, with any backend.

Most portals already have a backend and a React front end. Adding towers takes one new endpoint on the backend and one component on the page.

```
browser  ──▶  your backend  ──▶  Towers API
  page         /api/programs/:id/towers      (key added here)
```

Your backend sits in the middle so that the key never leaves it, and so that your own login decides who may see which program.

1. **Add an endpoint to your backend**

   It loads the program from your system, calls the Towers API, and returns the answer. In Express:

   ```js title="server/towers.js"
   import { Router } from 'express';

   export const towers = Router();

   towers.get('/api/programs/:id/towers', requireLogin, async (req, res) => {
     const program = await loadProgram(req.params.id, req.user); // your own data and access checks
     if (!program) return res.sendStatus(404);

     const answer = await fetch(`${process.env.TOWERS_API_URL}/api/v1/towers`, {
       method: 'POST',
       headers: {
         Authorization: `Bearer ${process.env.TOWERS_API_KEY}`,
         'Content-Type': 'application/json',
       },
       body: JSON.stringify(toTowersRequest(program)),
     });

     res.status(answer.status).json(await answer.json());
   });
   ```

   The same shape works in any language: an authenticated route of yours that forwards a JSON body with one extra header.

2. **Map your data to a request**

   `toTowersRequest` is the only part specific to your system. It turns your records into [Contracts, Layers, Lines and Risks](https://towers.vinsa.dev/docs/api/request.md):

   ```js
   function toTowersRequest(program) {
     return {
       program: {
         programRef: program.reference,
         programName: program.name,
         contracts: program.contracts.map((c) => ({
           contractRef: c.reference,
           contractName: c.name,
           currency: c.currency,
           lineOfBusiness: c.lineOfBusiness,
           layers: c.layers.map((l) => ({
             layerRef: l.reference,
             layerName: l.name,
             layerType: l.type, // 'QSR' | 'SPL' | 'FAC' | 'XOL'
             lowerLimit: l.attachment,
             upperLimit: l.limit == null ? null : l.attachment + l.limit,
             isUnlimited: l.limit == null,
             participationShare: l.participationShare,
             retainedShare: l.retainedShare,
             order: l.order,
             lineBasis: 'of whole', // these source shares are percentages of the whole
             lines: l.lines?.map((line) => ({
               reinsurer: line.name,
               writtenShare: line.writtenShare,
               status: line.status, // required on every Line
             })),
             accumulateBasis: l.basis,
           })),
         })),
         risks: program.risks.map((risk) => ({
           riskId: risk.id,
           insuredName: risk.insured,
           contractRefs: risk.contractReferences,
         })),
       },
     };
   }
   ```

   Note that `upperLimit` is the top of the layer, not its size: a layer of 2.5M in excess of 2.5M has an `upperLimit` of 5M.

3. **Draw it on the page**

   ```tsx title="ProgramTowers.tsx"
   import { useEffect, useState } from 'react';
   import { Towers } from '@vinsa/towers';
   import type { TowersResponse } from '@vinsa/towers';
   import '@vinsa/towers/styles.css';

   export function ProgramTowers({ programId }: { programId: string }) {
     const [towers, setTowers] = useState<TowersResponse | null>(null);
     const [failed, setFailed] = useState(false);

     useEffect(() => {
       let current = true;
       setTowers(null);
       setFailed(false);
       fetch(`/api/programs/${programId}/towers`)
         .then((res) => (res.ok ? res.json() : Promise.reject(res)))
         .then((body) => current && setTowers(body))
         .catch(() => current && setFailed(true));
       return () => {
         current = false;
       };
     }, [programId]);

     if (failed) return <p>The towers for this program could not be drawn.</p>;
     if (!towers) return <p>Drawing towers…</p>;
     return <Towers data={towers} />;
   }
   ```

   If your app already uses a data library such as TanStack Query or SWR, fetch with that instead of the effect.

## Handling a rejected request

When your data has a gap, the API answers `400` with the fields at fault. The endpoint above passes that through, so during integration you can log `errors` and see exactly which layer needs attention:

```json
{
  "message": "Invalid request body",
  "errors": [{ "path": "program.contracts[0].layers[3].lines[0].status", "message": "status must be one of: indication, quoted, firm order, signed, declined" }]
}
```

## Match your portal's look

Set the chart's [CSS variables](https://towers.vinsa.dev/docs/react/theming.md) once, next to your own theme, and it picks up your font and colours.
