DEV Community

abdelilah majid
abdelilah majid

Posted on

Stop Showing the Wrong Currency

Let's be honest: nothing kills an international conversion rate faster than showing a European customer a pricing page in US Dollars, or forcing a Japanese user to mentally convert from British Pounds.

If you're building a global SaaS or e-commerce site, you need to show the local currency immediately. But doing IP geolocation on the frontend is notoriously tricky. Heavy local databases like MaxMind slow down your server, and the free APIs out there are heavily rate-limited or inaccurate.

Today, I’m going to show you how to build a dynamic React hook in Next.js that detects a user's location and currency in under 50ms using a single API call.

The Strategy

We’re going to use the Core Web Utilities API. I love this specific tool because it's written in Rust, runs on AMD EPYC servers, and returns an insane amount of data (including the local currency) from a single IP lookup.

The Code

Let's create a custom React Hook called useUserLocation.

This hook will ping our API when the component mounts, grab the user's IP implicitly, and return their local currency and country code.

import { useState, useEffect } from 'react';

export function useUserLocation() {
  const [location, setLocation] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchLocation = async () => {
      try {
        // Leaving the IP blank tells the API to resolve the caller's IP automatically!
        const response = await fetch('https://core-web-utilities-api.p.rapidapi.com/v1/geoip?ip=', {
          headers: {
            'x-rapidapi-key': 'YOUR_RAPIDAPI_KEY', // Get yours from RapidAPI
            'x-rapidapi-host': 'core-web-utilities-api.p.rapidapi.com'
          }
        });

        const data = await response.json();
        setLocation(data);
      } catch (err) {
        console.error("Failed to fetch location", err);
      } finally {
        setLoading(false);
      }
    };

    fetchLocation();
  }, []);

  return { location, loading };
}
Enter fullscreen mode Exit fullscreen mode

Using it in your Pricing Component

Now, let's drop this into a UI component. If the API detects they are in Europe, we show Euros. If they are in the UK, we show GBP. Otherwise, we default to USD.

import React from 'react';
import { useUserLocation } from './hooks/useUserLocation';

const PricingCard = () => {
  const { location, loading } = useUserLocation();

  // Default to USD
  let symbol = '$';
  let price = 29;

  // Dynamically adjust based on the API's currency response
  if (location && location.currency === 'EUR') {
    symbol = '';
    price = 26; // Adjusted for exchange rate
  } else if (location && location.currency === 'GBP') {
    symbol = '£';
    price = 22;
  }

  if (loading) return <div className="p-8 text-center">Loading pricing...</div>;

  return (
    <div className="border-2 border-blue-500 rounded-xl p-8 max-w-sm text-center shadow-lg">
      <h2 className="text-2xl font-bold mb-2">Pro Plan</h2>
      <p className="text-gray-500 mb-6">Everything you need to scale.</p>

      <div className="text-5xl font-extrabold mb-8">
        {symbol}{price} <span className="text-lg text-gray-400 font-normal">/mo</span>
      </div>

      <button className="bg-blue-600 text-white w-full py-3 rounded-lg font-bold hover:bg-blue-700">
        Start Free Trial
      </button>

      {location && (
        <p className="text-xs text-gray-400 mt-4">
          Pricing localized for {location.country}
        </p>
      )}
    </div>
  );
};

export default PricingCard;
Enter fullscreen mode Exit fullscreen mode

Why this matters

By wrapping this logic into a custom hook powered by a fast API, you get a few massive wins:

  1. Zero Maintenance: You don't have to keep an IP database updated on your own server.
  2. Instant Localization: The API returns currency, country, and even timezone, so you can localize your entire app state from one single network request.
  3. Security: The API also returns a proxy and vpn flag. If someone is trying to spoof a cheaper region using a VPN, you can actually detect it and block them!

If you want to try this out, grab a free key from the Core Web Utilities API on RapidAPI and drop it into your codebase. Your conversion metrics will thank you!

Top comments (0)