# Next.js

> Fetch towers in a server component and draw them, with the key kept on the server.

With the App Router, the API call and the chart can live in the same page: the fetch runs on the server, and only the result reaches the browser.

1. **Add your key to the environment**

   ```sh title=".env.local"
   TOWERS_API_URL=https://towers-api.vinsa.dev
   TOWERS_API_KEY=twr_...
   ```

   Do not prefix these with `NEXT_PUBLIC_`. That prefix would ship the key to the browser.

2. **Install the package and import its styles**

   ```sh
   npm install @vinsa/towers
   ```

   ```tsx title="app/layout.tsx" ins={1}
   import '@vinsa/towers/styles.css';
   import './globals.css';

   export default function RootLayout({ children }: { children: React.ReactNode }) {
     return (
       <html lang="en">
         <body>{children}</body>
       </html>
     );
   }
   ```

3. **Write the server-side call**

   ```ts title="lib/towers.ts"
   import 'server-only';
   import type { TowersResponse } from '@vinsa/towers';

   export async function buildTowers(program: unknown): Promise<TowersResponse> {
     const res = 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(program),
       cache: 'no-store',
     });

     if (!res.ok) {
       const problem = await res.json().catch(() => null);
       throw new Error(problem?.message ?? `Towers API answered ${res.status}`);
     }
     return res.json();
   }
   ```

   The `server-only` import makes the build fail if this file is ever pulled into browser code.

4. **Draw the result in a page**

   ```tsx title="app/programs/[id]/page.tsx"
   import { Towers } from '@vinsa/towers';
   import { buildTowers } from '@/lib/towers';
   import { loadProgram } from '@/lib/programs'; // your own data

   export default async function ProgramPage({ params }: { params: Promise<{ id: string }> }) {
     const { id } = await params;
     const program = await loadProgram(id);
     const towers = await buildTowers(program);

     return (
       <main>
         <h1>{program.program?.programName}</h1>
         <Towers data={towers} />
       </main>
     );
   }
   ```

   `<Towers />` is a client component, and the response is plain JSON, so it can be passed across directly.

## Reacting to clicks

Function props such as `onSelect` cannot be passed from a server component. Wrap the chart in a small client component of your own:

```tsx title="app/programs/[id]/program-towers.tsx"
'use client';

import { useState } from 'react';
import { Towers } from '@vinsa/towers';
import type { TowersResponse } from '@vinsa/towers';

export function ProgramTowers({ towers }: { towers: TowersResponse }) {
  const [selected, setSelected] = useState<string | null>(null);

  return (
    <>
      <Towers data={towers} onSelect={(key) => setSelected(key)} />
      {selected && <p>Selected layer: {selected}</p>}
    </>
  );
}
```

## Caching

The API always gives the same answer for the same request. If a program changes rarely, replace `cache: 'no-store'` with `next: { revalidate: 300 }`, or cache on your side keyed by the program's version.
