javascript
43 lines · 7 steps
A cached exchange-rate proxy in Next.js
A Route Handler that proxies an upstream currency API while caching and revalidating responses at the edge.
Explained by
highlit
1import { NextResponse } from 'next/server'
2
3const UPSTREAM = 'https://api.exchangerate.host/latest'
4
5export async function GET(request) {
6 const { searchParams } = new URL(request.url)
7 const base = (searchParams.get('base') || 'USD').toUpperCase()
8 const symbols = searchParams.get('symbols')?.toUpperCase()
9
10 const upstreamUrl = new URL(UPSTREAM)
11 upstreamUrl.searchParams.set('base', base)
12 if (symbols) upstreamUrl.searchParams.set('symbols', symbols)
13
14 const res = await fetch(upstreamUrl, {
15 headers: { accept: 'application/json' },
16 next: {
17 revalidate: 3600,
18 tags: ['rates', `rates:${base}`],
19 },
20 })
21
22 if (!res.ok) {
23 return NextResponse.json(
24 { error: 'Failed to fetch exchange rates' },
25 { status: 502 },
26 )
27 }
28
29 const data = await res.json()
30
31 return NextResponse.json(
32 {
33 base: data.base,
34 date: data.date,
35 rates: data.rates,
36 },
37 {
38 headers: {
39 'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400',
40 },
41 },
42 )
43}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Route Handlers can proxy a third-party API so clients never touch it directly, letting you sanitize inputs and reshape responses.
- 2Next.js extends fetch with a next option so caching and tag-based revalidation happen at the data layer, not just via headers.
- 3Pairing s-maxage with stale-while-revalidate serves cached data instantly while refreshing it in the background.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-cached-exchange-rate-proxy-in-next-js-explained-javascript-4a6c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.