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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Route Handlers can proxy a third-party API so clients never touch it directly, letting you sanitize inputs and reshape responses.
  2. 2Next.js extends fetch with a next option so caching and tag-based revalidation happen at the data layer, not just via headers.
  3. 3Pairing s-maxage with stale-while-revalidate serves cached data instantly while refreshing it in the background.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A cached exchange-rate proxy in Next.js — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code