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
const logger = require('./logger'); class AppError extends Error { constructor(message, statusCode = 500, details = null) {
Centralized error handling in Express
error-handling
middleware
custom-errors
Intermediate
8 steps
javascript
const formatters = new Map(); function getFormatter(locale, currency) { const key = `${locale}:${currency}`;
Caching Intl.NumberFormat for currency formatting
memoization
internationalization
caching
Intermediate
8 steps
javascript
class DOMBatcher { constructor() { this.reads = []; this.writes = [];
Batching DOM reads and writes to avoid layout thrash
batching
requestanimationframe
layout-thrashing
Intermediate
8 steps
go
package web import ( "embed"
Serving embedded static assets in Go
embed
static-assets
http-handler
Intermediate
8 steps
javascript
function createCountdownTimer(durationSeconds, { onTick, onComplete } = {}) { let remaining = durationSeconds; let intervalId = null;
Building a countdown timer with closures
closures
factory-function
timers
Intermediate
9 steps
javascript
export function buildPaginationUrl(baseUrl, { page, perPage, filters = {}, sort } = {}) { const url = new URL(baseUrl); const params = url.searchParams;
Building and parsing pagination URLs
url-parsing
query-string
pagination
Intermediate
8 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.