Build log
Three bugs deep: a 6-hour debugging story about a feature I almost just hardcoded
Kazikit needed geo-based pricing. A visitor in Nigeria should see NGN. Someone in Ghana sees GHS. Someone in Kenya sees KES. The currency also feeds into Paystack, so getting the country right affects what actually gets charged, not just what number shows on the screen.
I gave myself an afternoon. It took six hours.
Around hour four, staring at a log that still showed the wrong currency, I thought about hardcoding Kenya and shipping it. Ninety percent of my users are Kenyan. Nobody checks a pricing page from Lagos every day. I didn't do it. I want credit for that.
Instead I found three bugs, stacked on top of each other, each one disguised as the last one. Here's what six hours of that actually looks like.
The setup
Vercel's edge network injects a header called x-vercel-ip-country on every request. Read it, map the country to a currency using a lookup table I'd already built for every African country I support, store the result in a cookie. A middleware seemed like the right place, since it already handled auth checks for protected routes.
const headerCountry =
request.headers.get("x-vercel-ip-country") ||
request.headers.get("cf-ipcountry") ||
null;
const geoDetected = headerCountry !== null;
const country = headerCountry ?? "US";
const currency = COUNTRY_CURRENCY_MAP[country] ?? DEFAULT_CURRENCY;I deployed it. I tested it from Kenya. I got shown USD.
Bug #1: the header was fine the whole time
I assumed the header wasn't arriving. Maybe Vercel's geolocation wasn't populating. Maybe something upstream ate it. I logged the raw values:
console.log("[geo debug]", {
vercelCountry: request.headers.get("x-vercel-ip-country"),
cfCountry: request.headers.get("cf-ipcountry"),
});vercelCountry: "KE". Correct, on every request, the whole time. I'd spent an hour interrogating a witness who never lied to me once.
So where did KE go after that?
My middleware also refreshed the Supabase session. To keep that cookie current, Supabase's SSR client calls a setAll function I write myself:
setAll: (cookiesList) => {
cookiesList.forEach(({ name, value, ...options }) => {
request.cookies.set({ name, value, ...options });
});
response = NextResponse.next({
request: { headers: request.headers },
});
cookiesList.forEach(({ name, value, ...options }) => {
response.cookies.set({ name, value, ...options });
});
},That response = NextResponse.next(...) line builds a new response object. Any cookie I'd already set on the old response, including my currency cookie, vanishes with it. I'd set the currency cookie earlier in the function. Supabase's refresh replaced the whole object a few lines later and took my cookie down with it.
The fix: set the currency and geo cookies after Supabase finishes its callback, on whichever response object survives to the return statement.
Bug #2: fixed everywhere except the page that mattered
I redeployed. Dashboard pages showed the right currency. Billing pages showed the right currency. The pricing page, the one page this entire feature existed for, still showed USD.
This is where the hardcoding idea started making its case. Ninety percent Kenyan traffic. Fifteen minutes to ship const currency = "KES". I sat with that idea for a while and then rejected it, mostly out of spite for the bug.
I almost re-opened the cookie-ordering code, assuming I'd missed something in the same fix. I hadn't. The cause here was a config file, not a callback.
My middleware's matcher only listed protected routes:
export const config = {
matcher: [
"/dashboard/:path*",
"/resumes/:path*",
"/billing/:path*",
],
}/pricing doesn't require login. Anyone can see prices without an account. So /pricing never appeared in the matcher, and the middleware never ran on that page at all. My cookie fix was correct. It just lived inside a function that this one page never called.
The matcher had been doing two jobs: deciding who gets geo detection, and deciding who needs to be logged in. Those are different lists of routes. I split them apart. The matcher now covers nearly every page, and an explicit check inside the function handles the login requirement:
const PROTECTED_PATHS = ["/dashboard", "/billing", "/resumes"];
function isProtectedPath(pathname: string) {
return PROTECTED_PATHS.some(p => pathname === p || pathname.startsWith(`${p}/`));
}
if (!user && isProtectedPath(pathname)) {
return NextResponse.redirect(new URL("/login", request.url));
}I was also mid-upgrade to Next.js 16, which renamed middleware.ts to proxy.ts and the exported function from middleware to proxy. For ten minutes I genuinely thought my whole file was being ignored, and started fixing a naming convention that was already correct. Another bug that wasn't a bug.
Bug #3: right cookie, wrong price, useless error message
I redeployed and checked the logs. preferred_currency: 'KES'. geo_detected: '1'. Both correct, on the pricing page this time.
The page still showed the wrong number.
By hour five I'd stopped assuming a new symptom meant the old bug had come back. Good, because it hadn't. The cookie was fine. The step that converts USD prices into local currency, calling an exchange rate API, was failing on every request:
[exchange-rates] Failed to fetch: Error: Exchange rate fetch failed
That message told me nothing. I'd written the catch block myself:
if (!res.ok) throw new Error("Exchange rate fetch failed");No status code. No response body. Just a string that described the symptom and hid the cause. I rewrote it:
if (!res.ok) {
const body = await res.text().catch(() => "");
throw new Error(`Exchange rate fetch failed: ${res.status} ${res.statusText} — ${body}`);
}I redeployed. The real error showed up in seconds: a 404. My request URL had an extra path segment:
https://openexchangerates.org/api/v1/latest.json?app_id=... wrong
https://openexchangerates.org/api/latest.json?app_id=... right
I'd added /v1/ assuming the API followed the versioned-path convention half the internet uses. It doesn't. Six characters stood between me and a working feature, and my own error handler had hidden them from me for an hour.
Why this took six hours
Each of these three bugs takes five minutes to fix once you've found it. The six hours came from how convincingly each one looked like the last.
A broken detection layer looks exactly like "always shows the default." So does a working detection layer whose cookie gets deleted downstream. I couldn't tell the difference until I logged the raw header value directly.
A correctly-fixed bug and a new bug can produce the identical symptom. My cookie fix worked. The next page I tested still showed the wrong currency. Nothing about that told me the cause had changed.
The exchange rate failure hid because I wrote the code that hid it. Nobody did that to me. I did that to myself, months earlier, when I chose a short error string over a useful one.
And the hardcoding idea kept coming back because it was, honestly, a reasonable idea. Ninety percent of my traffic wouldn't have noticed. But Paystack charges in whatever currency the code decides, and a hardcoded Kenya would have charged a Nigerian customer in KES the first time one showed up. Nobody would catch that in testing. Someone would catch it on their card statement.
Key takeaways
A repeated symptom doesn't mean a repeated cause. All three bugs produced "wrong currency." Check what actually changed between attempts, not just whether the screen looks the same.
Verify at the boundary before you touch the logic. Logging the raw header value took thirty seconds and ruled out an entire category of bug. I should have done that first, not after an hour of assumptions.
Config that serves two purposes will eventually fail one of them. My matcher decided both who gets geo detection and who needs to log in. The day I needed a route with one but not the other, it broke.
A generic error message is a debt you pay later, with interest. throw new Error("failed") cost nothing to write and an hour to walk back. Include the status code and response body the first time.
Reassigned variables inside callbacks are an easy way to lose state silently. If you're building a response across multiple callback stages, know exactly which reference survives to the return statement. Set what you care about last.
The urge to hardcode is a signal worth listening to, not a shortcut worth taking. It's usually your own brain asking whether the debugging session is worth it. Sometimes the honest answer is yes, and this was one of those times.
The feature works now. Correct currency, correctly rounded, on first paint, for every country I support, feeding the right amount into Paystack. Three fixes got me there. Only one of them was anywhere near where I started looking.