Skip to content

Repository files navigation

@unirate/fastify

npm ci license: MIT

Official Fastify plugin for the UniRate currency-exchange API. Registered with fastify-plugin semantics, it decorates your Fastify instance with a typed unirate client and can optionally mount read-only proxy routes that keep your API key server-side.

UniRate offers free real-time exchange rates for 170+ currencies plus VAT data; historical rates and time-series are Pro-tier endpoints.

Install

npm install @unirate/fastify

fastify is a peer dependency (>=4.0.0, works with v4 and v5). Native fetch is required (Node ≥ 20.12). Zero runtime dependencies.

Quick start

import Fastify from "fastify";
import unirate from "@unirate/fastify";

const app = Fastify();

await app.register(unirate, {
  apiKey: process.env.UNIRATE_API_KEY!,
});

app.get("/price", async () => {
  // `app.unirate` is fully typed thanks to module augmentation.
  const rate = await app.unirate.getRate("USD", "EUR");
  return { usd_to_eur: rate };
});

await app.listen({ port: 3000 });

Because the plugin is wrapped with fastify-plugin semantics, the unirate decorator is registered on the root instance and is available in every encapsulated route context — register it once.

Options

await app.register(unirate, {
  apiKey: process.env.UNIRATE_API_KEY!, // required
  baseUrl: "https://api.unirateapi.com", // optional override
  timeoutMs: 30_000,                      // optional request timeout
  userAgent: "my-app/1.0",               // optional User-Agent
  decorateName: "unirate",               // optional; name of the decorator
  routes: false,                          // optional; mount proxy routes
  routePrefix: "/unirate",               // optional; route prefix
});
Option Type Default Description
apiKey string Required. Your UniRate API key.
baseUrl string https://api.unirateapi.com API base URL.
timeoutMs number 30000 Per-request timeout.
userAgent string @unirate/fastify/<version> User-Agent header.
decorateName string "unirate" Instance decorator name (fastify.<name>).
routes boolean false Mount read-only proxy routes.
routePrefix string "/unirate" Prefix for the mounted routes.

The decorated client

app.unirate is a UniRateClient with the standard UniRate method surface:

await app.unirate.getRate("USD", "EUR");          // number
await app.unirate.getRate("USD");                 // Record<string, number>
await app.unirate.convert("EUR", 100, "USD");     // number
await app.unirate.getSupportedCurrencies();       // string[]
await app.unirate.getVatRates();                  // all VAT rates
await app.unirate.getVatRates("DE");              // one country
// Pro-tier (403 on free plans):
await app.unirate.getHistoricalRate("2024-01-01", 1, "USD", "EUR");
await app.unirate.getTimeSeries("2024-01-01", "2024-01-07");
await app.unirate.getHistoricalLimits();

Currency and country codes are uppercased automatically.

Optional proxy routes

Set routes: true to expose read-only endpoints. Your API key stays on the server — the browser never sees it.

await app.register(unirate, {
  apiKey: process.env.UNIRATE_API_KEY!,
  routes: true,
});
Route Query Returns
GET /unirate/rate from (default USD), to { from, to, rate } or { from, rates }
GET /unirate/convert from (default USD), to (required), amount (default 1) { from, to, amount, result }
GET /unirate/currencies { currencies }
GET /unirate/vat country (optional) all VAT rates, or one country
curl 'http://localhost:3000/unirate/rate?from=USD&to=EUR'
curl 'http://localhost:3000/unirate/convert?from=USD&to=EUR&amount=100'
curl 'http://localhost:3000/unirate/currencies'
curl 'http://localhost:3000/unirate/vat?country=DE'

Error handling

The plugin exports the full typed-error hierarchy from the client, all extending UniRateError:

Error HTTP status
InvalidRequestError 400
AuthenticationError 401
ProRequiredError 403
InvalidCurrencyError 404
RateLimitError 429
ServiceUnavailableError 503

When you call the decorated client yourself, catch these:

import { RateLimitError } from "@unirate/fastify";

try {
  await app.unirate.getRate("USD", "EUR");
} catch (err) {
  if (err instanceof RateLimitError) {
    // back off
  }
}

The mounted proxy routes translate these to the corresponding HTTP status codes automatically (transport failures become 502). The statusForError(err) helper is exported if you want the same mapping in your own error handler.

Rate limits

Free-tier keys are rate-limited; a 429 surfaces as RateLimitError. Historical and time-series endpoints return 403 (ProRequiredError) on free plans.

Related clients

Part of the UniRate family: @unirate/nestjs, @unirate/next, @unirate/react, unirate-api (framework-agnostic Node client), and more.

License

MIT — see LICENSE.

About

Official Fastify plugin for the UniRate currency-exchange API — typed client decorator + optional server-side proxy routes. Zero runtime deps.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages