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.
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)
- 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
base(optional): Base currency code (default: USD)symbols(optional): Comma-separated list of target currencies- Get an API key
- Make HTTP requests to fetch rates
- Cache responses to reduce API calls
- Handle errors gracefully
- Secure your credentials
Step 1: Get Your API Key
First, sign up for a free account at finexly.com and obtain your API key:
Keep this key safe—it's your credential for accessing the API.
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
Example Request
curl "https://api.finexly.com/latest?base=USD&symbols=EUR,GBP,JPY&accesskey=YOURAPI_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 APIKEY = 'YOURAPI_KEY';
const APIBASEURL = 'https://api.finexly.com/latest';// service.js
async function getExchangeRate(baseCurrency, targetCurrency) {
try {
const url = ${APIBASEURL}?base=${baseCurrency}&symbols=${targetCurrency}&accesskey=${APIKEY};
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:
Currency Converter
Currency Converter
Enter an amount to see the conversion
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}&accesskey=${process.env.REACTAPPFINEXLYAPI_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 (
Currency Converter
setAmount(e.target.value)}
placeholder="Enter amount"
/>
{loading &&
Loading...
}
{error && Error: {error}
}
{rate && {converted} {to}
}
);
}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 APIKEY = process.env.FINEXLYAPI_KEY;
const APIBASEURL = '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 = ${APIBASEURL}?base=${from}&symbols=${to}&accesskey=${APIKEY};
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 APIKEY = process.env.FINEXLYAPI_KEY;
// Or create a backend endpoint
// Frontend calls your server, server calls Finexly
2. Implement Caching
Reduce API calls by caching rates:
const cache = new Map();
const CACHE_TTL = 5 60 1000; // 5 minutesasync 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 APIKEY = process.env.FINEXLYAPI_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:
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.
Ready to build? Sign up for Finexly today and get immediate access to real-time exchange rates.
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 →