# Add currency exchange rates and conversion to Next.js App Router

Fetch rates and conversions from server components or Route Handlers. Keep credentials server-side; fetch revalidation is set to one hour as requested for this per-response API.

## Get a free API key

Sign up at https://currencyexchangerate-api.com/auth/login, then create a key under API keys in the console. The free plan includes 3,000 requests per month with no credit card. Store the secret as CXR_API_KEY in server-side environment configuration; never expose it in browser code.

File: `.env`

```shell
CXR_API_KEY=cxr_your_secret_key
```

## Create a reusable client and cache rates

Use the standard HTTP client. Cache every /latest response until nextUpdateAt: rates change at most once by then, and reusing the response saves quota. The helper also exposes /convert.

File: `lib/rates.ts`

```typescript
import 'server-only';

const API_BASE_URL = 'https://api.currencyexchangerate-api.com/api/v1';
const headers = { Authorization: 'Bearer ' + process.env.CXR_API_KEY };

export async function latest(base = 'USD', symbols = 'EUR,GBP') {
  const query = new URLSearchParams({ base, symbols });
  const response = await fetch(API_BASE_URL + '/latest?' + query, {
    headers,
    next: { revalidate: 3600 },
  });
  if (!response.ok) {
    throw new Error('Rates API status ' + response.status);
  }
  return response.json();
}

export async function convert(from: string, to: string, amount: number) {
  const query = new URLSearchParams({ from, to, amount: String(amount) });
  const response = await fetch(API_BASE_URL + '/convert?' + query, { headers });
  if (!response.ok) {
    throw new Error('Rates API status ' + response.status);
  }
  return response.json();
}
```

## Use it in Next.js App Router

Call the helper from a server route, controller, view, command, or script. Format converted values for the user’s locale.

File: `app/api/convert/route.ts`

```typescript
import { NextResponse } from 'next/server';

import { convert } from '@/lib/rates';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const from = searchParams.get('from') ?? 'EUR';
  const to = searchParams.get('to') ?? 'GBP';
  const amount = Number(searchParams.get('amount') ?? '100');
  if (!Number.isFinite(amount)) {
    return NextResponse.json({ error: 'Invalid amount' }, { status: 422 });
  }
  return NextResponse.json(await convert(from, to, amount));
}
```

## Handle API errors

A 401 means the key is invalid. A 429 can mean a rate limit or quota limit; read Retry-After in seconds before retrying. Other errors use application/problem+json.

File: `errors.js`

```javascript
// In get(), replace the generic throw with:
//   if (!response.ok) throw await apiError(response);
async function apiError(response) {
  const problem = await response.json().catch(() => ({}));
  if (response.status === 401) {
    return new Error('Check CXR_API_KEY');
  }
  if (response.status === 429) {
    const retryAfter = response.headers.get('Retry-After');
    return new Error('Retry after ' + retryAfter + ' seconds');
  }
  return new Error(problem.detail || 'Rates API status ' + response.status);
}
```

## Format the amount for display

Use locale-aware currency formatting instead of adding a symbol manually.

File: `format.js`

```javascript
const formatter = new Intl.NumberFormat('en-GB', {
  style: 'currency',
  currency: 'EUR',
});
const formatted = formatter.format(85.249105);
```

## Related links

- [API documentation](https://currencyexchangerate-api.com/docs.md)
- [All integration guides](https://currencyexchangerate-api.com/guides.md)
- [Get a free API key](https://currencyexchangerate-api.com/auth/login)
