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 express = require('express'); const app = express();
Enforcing HTTPS with Express middleware
middleware
https
security
Intermediate
6 steps
ruby
module Rack class MaintenanceMode RETRY_AFTER = 3600
A Rack maintenance-mode middleware in Rails
middleware
rack
http-status
Intermediate
8 steps
javascript
const express = require('express'); const router = express.Router(); router.get('/articles/:slug', async (req, res, next) => {
Conditional GET caching in Express
http-caching
conditional-get
routing
Intermediate
8 steps
javascript
function parseHexColor(hex) { const cleaned = hex.trim().replace(/^#/, ''); const expand = (short) =>
Parsing hex colors into RGBA channels
parsing
bitwise
regex
Intermediate
7 steps
javascript
import { useReducer, useCallback } from 'react'; function historyReducer(state, action) { const { past, present, future } = state;
Undo/redo form state with a React reducer
undo-redo
reducer
immutability
Intermediate
10 steps
java
@Component public class HeaderMergeFilter { private static final String PER_REQUEST_HEADERS = HeaderMergeFilter.class.getName() + ".headers";
Merging default and per-request headers in Spring
webclient
filters
http-headers
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.