@unirate/sveltekit

July 8, 2026 · View on GitHub

SvelteKit integration for the UniRate currency exchange API.

Server-side getRate/convert helpers for load functions, a createCurrencyHandle() geo-detection hook, an API route proxy that keeps your key server-side, and <Currency> + <Rate> Svelte 5 components. Zero runtime dependencies.

Install

npm install @unirate/sveltekit

Quick start

1. Set your API key

# .env
UNIRATE_API_KEY=your-api-key-here

Get a free key at unirateapi.com.

2. Load data in a server load function

// src/routes/+page.server.ts
import { getRate, convert, listCurrencies } from '@unirate/sveltekit/server';

export async function load() {
  const [rate, price, currencies] = await Promise.all([
    getRate('USD', 'EUR'),
    convert('USD', 'EUR', 99.99),
    listCurrencies(),
  ]);
  return { rate, price, currencies };
}

3. Display with components

<!-- src/routes/+page.svelte -->
<script>
  import Currency from '@unirate/sveltekit/Currency.svelte';
  import Rate from '@unirate/sveltekit/Rate.svelte';

  let { data } = $props();
</script>

<p>1 USD = <Rate from="USD" to="EUR" rate={data.rate} /> EUR</p>
<p>Price: <Currency amount={data.price} currency="EUR" /></p>

API

Server helpers (@unirate/sveltekit/server)

import { createUniRate, getRate, convert, listCurrencies } from '@unirate/sveltekit/server';

createUniRate(options?)

Factory that returns an object with all API methods bound to a single client instance.

const unirate = createUniRate({
  apiKey: 'your-key',   // defaults to UNIRATE_API_KEY env var
  baseUrl: '...',       // defaults to https://api.unirateapi.com
  timeoutMs: 10_000,    // defaults to 30_000
});

const rate = await unirate.getRate('USD', 'EUR');

Top-level convenience functions

These use a default createUniRate() instance (reads UNIRATE_API_KEY from env):

FunctionReturns
getRate(from, to?)number (single pair) or Record<string, number> (all pairs)
convert(from, to, amount)number
listCurrencies()string[]
getHistoricalRate(date, from, to?, amount?)number or Record<string, number>
getVatRates(country?)VAT data
getTimeSeries(startDate, endDate, base?, currencies?, amount?)Record<string, Record<string, number>>
getHistoricalLimits()HistoricalLimitsResponse

Historical and time-series endpoints require a Pro subscription.

Currency detection hook (@unirate/sveltekit/hooks)

// src/hooks.server.ts
import { createCurrencyHandle } from '@unirate/sveltekit/hooks';

const currencyHandle = createCurrencyHandle({
  defaultCurrency: 'USD',    // fallback when no signal detected
  cookieName: 'unirate_currency',
  cookieMaxAge: 365 * 24 * 60 * 60,
});

export const handle = currencyHandle;
// or compose with sequence():
// export const handle = sequence(currencyHandle, otherHandle);

The hook detects currency from:

  1. Existing cookie (highest priority)
  2. Accept-Language header region subtag (e.g., en-GB → GBP)
  3. Accept-Language language fallback (e.g., ja → JPY)
  4. defaultCurrency option (default: USD)

It sets event.locals.currency and persists the detected currency in a cookie. Add the type to your app.d.ts:

// src/app.d.ts
declare global {
  namespace App {
    interface Locals {
      currency: string;
    }
  }
}

API route proxy (@unirate/sveltekit/api)

Keep your API key server-side by proxying client requests through a SvelteKit endpoint:

// src/routes/api/unirate/+server.ts
import { createUniRateRequestHandler } from '@unirate/sveltekit/api';

export const GET = createUniRateRequestHandler({
  allowedPaths: ['/api/rates', '/api/convert', '/api/currencies'],
});

Client-side usage:

const res = await fetch('/api/unirate?path=/api/rates&from=USD&to=EUR');
const { rate } = await res.json();

Components

<Currency>

Formats a numeric amount as a localized currency string.

<script>
  import Currency from '@unirate/sveltekit/Currency.svelte';
</script>

<Currency amount={99.99} currency="EUR" />
<!-- renders: €99.99 -->

<Currency amount={1234.5} currency="JPY" decimals={0} locale="ja-JP" />
<!-- renders: ¥1,235 -->
PropTypeDefaultDescription
amountnumberrequiredThe numeric value to format
currencystringrequiredISO 4217 currency code
decimalsnumber2Fraction digits
localestringbrowser defaultBCP 47 locale tag

<Rate>

Formats an exchange rate number.

<script>
  import Rate from '@unirate/sveltekit/Rate.svelte';
</script>

<Rate from="USD" to="EUR" rate={0.9245} />
<!-- renders: 0.9245 -->
PropTypeDefaultDescription
fromstringrequiredSource currency code
tostringrequiredTarget currency code
ratenumberrequiredThe exchange rate value
decimalsnumber4Fraction digits
localestringbrowser defaultBCP 47 locale tag

Error handling

All errors extend UniRateError:

import {
  UniRateError,
  AuthenticationError,   // 401
  ProRequiredError,      // 403
  InvalidCurrencyError,  // 404
  InvalidRequestError,   // 400
  RateLimitError,        // 429
} from '@unirate/sveltekit';

UniRate ecosystem

UniRate ships official integrations for 40+ ecosystems, all maintained under the UniRate-API org.

Core clients (9 languages) Python · Node.js / TypeScript · Go · Rust · Java · Ruby · PHP · .NET · Swift

JavaScript / TypeScript React · Next.js · Remix · SvelteKit · Vue · Angular · Nuxt · NestJS · tRPC

Static-site generators Astro · Eleventy · Hugo · Jekyll

CMS & e-commerce Wagtail · WordPress · WooCommerce · Drupal · Strapi · Medusa · Symfony · Laravel · Directus

Data, AI & backend LangChain (Python) · LangChain.js · FastAPI · Flask · Django REST Framework · Apache Airflow · dbt

Platform & tools MCP server · CLI · Cloudflare Workers · Home Assistant · n8n · Google Sheets · VS Code · Obsidian

Money library bridges money gem (Ruby) · NodaMoney (.NET)

Get a free API key at unirateapi.com.

License

MIT