Exchange Rates App: Get real-time exchange rates with Next.js
Welcome to the Exchange Rates App tutorial! In this guide, one can acquire knowledge about how to create a web application that fetches real-time exchange rates from Exchange Rate API using Next.js, Tailwind CSS, and the Exchange Rate API.
Now let’s start and check in the world of direct stimulation of the exchange rates!
Requirement
Before we go so far, let’s prepare some software we need.
Software
- Yarn (https://yarnpkg.com)
- Visual Studio Code (https://code.visualstudio.com/download)
1. Setup Project
Run the following command in your terminal/cmd
$ yarn create next-app next-exchange-rates- Would you like to use TypeScript? No
- Would you like to use ESLint? Yes
- Would you like to use Tailwind CSS? Yes
- Would you like to use `src/` directory? Yes
- Would you like to use App Router? (recommended)? No
- Would you like to customize the default import alias (@/*)? Yes
2. Install Dependencies
You now have a new directory called next-exchange-rates Let’s cd into it:
$ cd next-exchange-ratesNext, install dependencies
$ yarn add axiosExplanation :
- axios : We’ll use Axios to make HTTP requests to the Exchange Rates API.
3. Get Your Exchange Rate API Key
Sign up at exchangerate-api.com and grab your API key. This key allows you to access their exchange rates data. Let’s create .env file, and copy-paste this code below and define variable based on API key.
EXCHANGE_RATE_API_KEY=your_api_key_here4. Write the API Route to Fetch Exchange Rates
Next.js makes it easy to create API routes. We’ll create a new file called exchange-rates.js in the src/pages/api directory:
import axios from 'axios';
export default async function handler(req, res) {
const apiKey = process.env.EXCHANGE_RATE_API_KEY; // Store your API key in environment variables
const url = `https://v6.exchangerate-api.com/v6/${apiKey}/latest/USD`;
try {
const response = await axios.get(url);
if (response?.data?.result === 'success') {
res.status(200).json(response?.data);
} else {
res.status(500).json({ error: 'Failed to fetch exchange rates' });
}
} catch (error) {
res.status(500).json({ error: error.message });
}
}5. Fetch Exchange Rates from the Frontend
Now, let’s fetch exchange rates from our frontend. Here’s an example in src/pages/index.js:
import { useEffect, useState } from "react";
import axios from "axios";
export default function Home() {
const [exchangeRates, setExchangeRates] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchExchangeRates() {
try {
const response = await axios.get("/api/exchange-rates");
setExchangeRates(response.data.conversion_rates);
} catch (error) {
setError(error.message);
} finally {
setLoading(false);
}
}
fetchExchangeRates();
}, []);
if (loading)
return (
<div className="flex justify-center items-center min-h-screen">
<div>Loading...</div>
</div>
);
if (error)
return (
<div className="flex justify-center items-center min-h-screen">
<div>Error: {error}</div>
</div>
);
return (
<div className="min-h-screen bg-gray-100 flex flex-col items-center py-10">
<h1 className="text-3xl font-bold mb-8">Real-Time Exchange Rates</h1>
<div className="bg-white shadow-md rounded-lg p-8 w-full max-w-4xl">
<div className="h-[600px] overflow-y-scroll">
<table className="min-w-full bg-white">
<thead>
<tr>
<th className="py-3 px-4 border-b text-left">Currency Code</th>
<th className="py-3 px-4 border-b text-left">Exchange Rate</th>
</tr>
</thead>
<tbody>
{exchangeRates &&
Object.entries(exchangeRates).map(([currency, rate]) => (
<tr key={currency}>
<td className="py-3 px-4 border-b">{currency}</td>
<td className="py-3 px-4 border-b">{Number(rate)?.toFixed(2)}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
);
}Don’t forget clear some css variable at src/styles/globals.css. And your globals.css will look like this
@tailwind base;
@tailwind components;
@tailwind utilities;Result
Run the following command
$ yarn devThen your result will looks like this
You can see the source code here :
Get Ryan Adhitama Putra’s stories in your inbox
Join Medium for free to get updates from this writer.
https://github.com/ryanadhitama/next-exchange-rates
Thank You!
Stackademic 🎓
Thank you for reading until the end. Before you go:
- Please consider clapping and following the writer! 👏
- Follow us X | LinkedIn | YouTube | Discord
- Visit our other platforms: In Plain English | CoFeed | Differ
- More content at Stackademic.com










