How to Integrate a Currency API with JavaScript - Step-by-Step Tutorial
Integrating a currency exchange rate API into your JavaScript application is easier than you might think. Whether you're building a web app, mobile application with React Native, or a Node.js backend, this guide will walk you through everything you need to know. For a Python implementation, see our Python tutorial. Want to build a complete converter app? Follow our step-by-step currency converter tutorial. For mobile-specific patterns (React Native, Flutter, Swift), see our mobile apps guide.
Prerequisites
Before starting, you'll need:
- Basic JavaScript knowledge (understanding of async/await is helpful)
- A text editor or IDE
- An API key from a currency API provider (like Finexly)
- A browser with developer tools (or Node.js for backend integration)
- A basic understanding of exchange rates (see our exchange rates explained guide if you're new to the concept)
Step 1: Get Your API Key
First, sign up for a free account at finexly.com and obtain your API key:
- Visit finexly.com and click "Sign Up"
- Create your account with your email
- Verify your email address
- Go to your Dashboard
- Navigate to "API Keys" and copy your key
Keep this key safe—it's your credential for accessing the API. For more details on available endpoints and parameters, consult the API documentation.
Step 2: Understanding the Finexly API
The Finexly API provides real-time exchange rates through a simple REST endpoint:
https://api.finexly.com/latestRequired Parameters
base(optional): Base currency code (default: USD)symbols(optional): Comma-separated list of target currencies
Example Request
curl "https://api.finexly.com/latest?base=USD&symbols=EUR,GBP,JPY&access_key=YOUR_API_KEY"Example Response
{
"success": true,
"timestamp": 1680000000,
"base": "USD",
"date": "2026-03-28",
"rates": {
"EUR": 0.9245,
"GBP": 0.7932,
"JPY": 148.50,
"CAD": 1.3650,
"AUD": 1.5230
}
}Step 3: Basic JavaScript Integration
Let's start with a simple vanilla JavaScript example:
// config.js
const API_KEY = 'YOUR_API_KEY';
const API_BASE_URL = 'https://api.finexly.com/latest';
// service.js
async function getExchangeRate(baseCurrency, targetCurrency) {
try {
const url = `${API_BASE_URL}?base=${baseCurrency}&symbols=${targetCurrency}&access_key=${API_KEY}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const data = await response.json();
if (!data.success) {
throw new Error(data.error?.info || 'Unknown API error');
}
return data.rates[targetCurrency];
} catch (error) {
console.error('Failed to fetch exchange rate:', error);
throw error;
}
}
// Usage
getExchangeRate('USD', 'EUR')
.then(rate => {
console.log(`1 USD = ${rate} EUR`);
})
.catch(error => {
console.error('Error:', error);
});Step 4: Build a Currency Converter
Let's create a practical currency converter application. You can also test live currency conversions with our interactive converter:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Currency Converter</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
max-width: 600px;
margin: 0 auto;
padding: 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
}
.converter {
background: white;
border-radius: 12px;
padding: 30px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
color: #333;
margin-bottom: 30px;
}
.input-group {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
margin-bottom: 20px;
}
.input-field {
display: flex;
flex-direction: column;
}
label {
font-size: 14px;
color: #666;
margin-bottom: 8px;
font-weight: 600;
}
select, input {
padding: 12px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 16px;
transition: border-color 0.3s;
}
select:focus, input:focus {
outline: none;
border-color: #667eea;
}
.result {
background: #f5f5f5;
padding: 20px;
border-radius: 8px;
margin-top: 20px;
text-align: center;
}
.result-value {
font-size: 32px;
font-weight: bold;
color: #667eea;
margin: 10px 0;
}
.loading {
color: #999;
font-size: 14px;
}
.error {
color: #d32f2f;
font-size: 14px;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="converter">
<h1>Currency Converter</h1>
<div class="input-group">
<div class="input-field">
<label for="amount">Amount</label>
<input
type="number"
id="amount"
value="1"
placeholder="Enter amount"
min="0"
step="0.01"
>
</div>
<div class="input-field">
<label for="from-currency">From</label>
<select id="from-currency">
<option value="USD">USD - US Dollar</option>
<option value="EUR">EUR - Euro</option>
<option value="GBP">GBP - British Pound</option>
<option value="JPY">JPY - Japanese Yen</option>
<option value="CAD">CAD - Canadian Dollar</option>
<option value="AUD">AUD - Australian Dollar</option>
<option value="CHF">CHF - Swiss Franc</option>
<option value="CNY">CNY - Chinese Yuan</option>
<option value="SEK">SEK - Swedish Krona</option>
<option value="NZD">NZD - New Zealand Dollar</option>
</select>
</div>
</div>
<div class="input-group">
<div class="input-field">
<label for="to-currency">To</label>
<select id="to-currency">
<option value="EUR">EUR - Euro</option>
<option value="USD">USD - US Dollar</option>
<option value="GBP">GBP - British Pound</option>
<option value="JPY">JPY - Japanese Yen</option>
<option value="CAD">CAD - Canadian Dollar</option>
<option value="AUD">AUD - Australian Dollar</option>
<option value="CHF">CHF - Swiss Franc</option>
<option value="CNY">CNY - Chinese Yuan</option>
<option value="SEK">SEK - Swedish Krona</option>
<option value="NZD">NZD - New Zealand Dollar</option>
</select>
</div>
</div>
<div class="result" id="result">
<p class="loading">Enter an amount to see the conversion</p>
</div>
</div>
<script>
const API_KEY = 'YOUR_API_KEY';
const API_BASE_URL = 'https://api.finexly.com/latest';
const amountInput = document.getElementById('amount');
const fromCurrency = document.getElementById('from-currency');
const toCurrency = document.getElementById('to-currency');
const resultDiv = document.getElementById('result');
async function convertCurrency() {
const amount = parseFloat(amountInput.value);
const from = fromCurrency.value;
const to = toCurrency.value;
if (!amount || amount < 0) {
resultDiv.innerHTML = '<p class="loading">Enter a valid amount</p>';
return;
}
resultDiv.innerHTML = '<p class="loading">Converting...</p>';
try {
const url = `${API_BASE_URL}?base=${from}&symbols=${to}&access_key=${API_KEY}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const data = await response.json();
if (!data.success) {
throw new Error(data.error?.info || 'Unknown error');
}
const rate = data.rates[to];
const converted = (amount * rate).toFixed(2);
resultDiv.innerHTML = `
<div>
<p>${amount} ${from}</p>
<p class="result-value">${converted}</p>
<p>${to}</p>
<p style="color: #999; font-size: 12px; margin-top: 10px;">
1 ${from} = ${rate.toFixed(4)} ${to}
</p>
</div>
`;
} catch (error) {
resultDiv.innerHTML = `
<p class="error">Error: ${error.message}</p>
`;
}
}
// Add event listeners
amountInput.addEventListener('input', convertCurrency);
fromCurrency.addEventListener('change', convertCurrency);
toCurrency.addEventListener('change', convertCurrency);
// Initial conversion
convertCurrency();
</script>
</body>
</html>Step 5: React Integration
If you're using React, here's how to integrate Finexly:
// useExchangeRate.js
import { useState, useEffect } from 'react';
const useExchangeRate = (baseCurrency, targetCurrency) => {
const [rate, setRate] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchRate = async () => {
try {
setLoading(true);
const url = `https://api.finexly.com/latest?base=${baseCurrency}&symbols=${targetCurrency}&access_key=${process.env.REACT_APP_FINEXLY_API_KEY}`;
const response = await fetch(url);
const data = await response.json();
if (!data.success) {
throw new Error(data.error?.info || 'Failed to fetch rate');
}
setRate(data.rates[targetCurrency]);
setError(null);
} catch (err) {
setError(err.message);
setRate(null);
} finally {
setLoading(false);
}
};
fetchRate();
}, [baseCurrency, targetCurrency]);
return { rate, loading, error };
};
export default useExchangeRate;// CurrencyConverter.jsx
import React, { useState } from 'react';
import useExchangeRate from './useExchangeRate';
function CurrencyConverter() {
const [amount, setAmount] = useState(1);
const [from, setFrom] = useState('USD');
const [to, setTo] = useState('EUR');
const { rate, loading, error } = useExchangeRate(from, to);
const converted = rate ? (amount * rate).toFixed(2) : 0;
return (
<div className="converter">
<h1>Currency Converter</h1>
<input
type="number"
value={amount}
onChange={(e) => setAmount(e.target.value)}
placeholder="Enter amount"
/>
<select value={from} onChange={(e) => setFrom(e.target.value)}>
<option value="USD">USD</option>
<option value="EUR">EUR</option>
<option value="GBP">GBP</option>
</select>
<select value={to} onChange={(e) => setTo(e.target.value)}>
<option value="EUR">EUR</option>
<option value="USD">USD</option>
<option value="GBP">GBP</option>
</select>
{loading && <p>Loading...</p>}
{error && <p className="error">Error: {error}</p>}
{rate && <p className="result">{converted} {to}</p>}
</div>
);
}
export default CurrencyConverter;Step 6: Node.js / Express Backend Integration
For server-side integration with Express:
// routes/api/convert.js
const express = require('express');
const router = express.Router();
const API_KEY = process.env.FINEXLY_API_KEY;
const API_BASE_URL = 'https://api.finexly.com/latest';
router.get('/convert', async (req, res) => {
const { amount, from, to } = req.query;
if (!amount || !from || !to) {
return res.status(400).json({
error: 'Missing required parameters: amount, from, to'
});
}
try {
const url = `${API_BASE_URL}?base=${from}&symbols=${to}&access_key=${API_KEY}`;
const response = await fetch(url);
const data = await response.json();
if (!data.success) {
return res.status(400).json({
error: data.error?.info || 'API error'
});
}
const rate = data.rates[to];
const converted = parseFloat(amount) * rate;
res.json({
amount: parseFloat(amount),
from,
to,
rate,
converted: converted.toFixed(2),
timestamp: data.timestamp
});
} catch (error) {
res.status(500).json({
error: 'Failed to fetch conversion rate'
});
}
});
module.exports = router;Best Practices
1. Secure Your API Key
Never expose your API key in client-side code:
// ❌ DON'T DO THIS
const API_KEY = 'abc123'; // Visible in browser!
// ✅ DO THIS INSTEAD
// Use environment variables
const API_KEY = process.env.FINEXLY_API_KEY;
// Or create a backend endpoint
// Frontend calls your server, server calls Finexly2. Implement Caching
Reduce API calls by caching rates:
const cache = new Map();
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
async function getCachedRate(from, to) {
const key = `${from}-${to}`;
const cached = cache.get(key);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return cached.rate;
}
const rate = await fetchRate(from, to);
cache.set(key, { rate, timestamp: Date.now() });
return rate;
}3. Handle Errors Gracefully
Always expect things to fail:
async function safeConvert(amount, from, to) {
try {
const rate = await getExchangeRate(from, to);
return amount * rate;
} catch (error) {
console.error('Conversion failed:', error);
// Use cached/stale data or notify user
return null;
}
}4. Rate Limiting Awareness
Monitor your API usage:
async function checkRateLimit() {
const response = await fetch('https://api.finexly.com/latest?base=USD');
const remaining = response.headers.get('X-Rate-Limit-Remaining');
const reset = response.headers.get('X-Rate-Limit-Reset');
console.log(`Remaining requests: ${remaining}`);
console.log(`Reset at: ${new Date(reset * 1000)}`);
}Troubleshooting Common Issues
"Invalid API Key" Error
// Check your key is correct
const API_KEY = process.env.FINEXLY_API_KEY;
console.log('API Key set:', !!API_KEY);CORS Issues
If you're making requests from the browser directly, ensure CORS is enabled. For production, use a backend proxy:
// Instead of fetching directly to Finexly
fetch('https://api.finexly.com/latest?access_key=...')
// Fetch through your own server
fetch('/api/exchange-rate')Rate Limit Exceeded
Implement exponential backoff:
async function fetchWithRetry(url, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await fetch(url);
} catch (error) {
if (i === maxRetries - 1) throw error;
await new Promise(resolve =>
setTimeout(resolve, Math.pow(2, i) * 1000)
);
}
}
}Conclusion
Integrating a currency exchange rate API into your JavaScript application is straightforward with Finexly. Whether you're building a simple currency converter or a complex fintech application, the steps are the same:
- Get an API key
- Make HTTP requests to fetch rates
- Cache responses to reduce API calls
- Handle errors gracefully
- Secure your credentials
Start with the simple vanilla JavaScript example and scale up to React or Node.js as your application grows. Finexly's reliable, real-time exchange rates make it perfect for any JavaScript project handling international transactions. For more details, see the API documentation and check our pricing plans for production-scale applications.
Ready to build? Sign up for Finexly today and get immediate access to real-time exchange rates.
Explore More
Vlado Grigirov
Senior Currency Markets Analyst & Financial Strategist
Vlado Grigirov is a senior currency markets analyst and financial strategist with over 14 years of experience in foreign exchange markets, cross-border finance, and currency risk management. He has wo...
View full profile →