Home Web Front-end JS Tutorial Building an Automatic Currency Switcher in Next.js

Building an Automatic Currency Switcher in Next.js

Jan 03, 2025 am 08:33 AM

Prerequisites
Before you begin, ensure you have abasic understanding of Next.js and React.

1. Creating the Backend API Route

We'll create a Next.js API route that interacts with our Geolocation API.
Create a new file at: src/app/api/geolocation/route.ts

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

import { NextResponse } from "next/server";

import axios from "axios";

 

type IPGeolocation = {

    ip: string;

    version?: string;

    city?: string;

    region?: string;

    region_code?: string;

    country_code?: string;

    country_code_iso3?: string;

    country_fifa_code?: string;

    country_fips_code?: string;

    country_name?: string;

    country_capital?: string;

    country_tld?: string;

    country_emoji?: string;

    continent_code?: string;

    in_eu: boolean;

    land_locked: boolean;

    postal?: string;

    latitude?: number;

    longitude?: number;

    timezone?: string;

    utc_offset?: string;

    country_calling_code?: string;

    currency?: string;

    currency_name?: string;

    languages?: string;

    country_area?: number;

    asn?: string; // Append ?fields=asn to the URL

    isp?: string; // Append ?fields=isp to the URL

}

 

type IPGeolocationError = {

  code: string;

  error: string;

}

 

export async function GET() {

  // Retrieve IP address using the getClientIp function

  // For testing purposes, we'll use a fixed IP address

  // const clientIp = getClientIp(req.headers);

 

  const clientIp = "84.17.50.173";

 

  if (!clientIp) {

    return NextResponse.json(

      { error: "Unable to determine IP address" },

      { status: 400 }

    );

  }

 

  const key = process.env.IPFLARE_API_KEY;

 

  if (!key) {

    return NextResponse.json(

      { error: "IPFlare API key is not set" },

      { status: 500 }

    );

  }

 

  try {

    const response = await axios.get<IPGeolocation | IPGeolocationError>(

      `https://api.ipflare.io/${clientIp}`,

      {

        headers: {

          "X-API-Key": key,

        },

      }

    );

 

    if ("error" in response.data) {

      return NextResponse.json({ error: response.data.error }, { status: 400 });

    }

 

    return NextResponse.json(response.data);

  } catch {

    return NextResponse.json(

      { error: "Internal Server Error" },

      { status: 500 }

    );

  }

}

Copy after login

2. Obtaining Your API Key

We are going to use a free geolocation service called IP Flare. Visit the API Keys Page: Navigate to the API Keys page.

Visit: www.ipflare.io

From the API Keys page we can get our API key and we can use the quick copy to store it as an environment variable in our .env file. We will use this to authenticate our requests.
Building an Automatic Currency Switcher in Next.js

3. Creating the Frontend Component

I have created this all-in-one component that includes the provider and the currency selector. I am using shadcn/ui and some flag SVGs I found online.

You will need to wrap the application in the so that we can access the context.

Now, anywhere in the application where we want to access the currency, we can use the hook const { currency } = useCurrency();.

To integrate this with Stripe, when you create the checkout you just need to send the currency and ensure that you have added multi-currency pricing to your Stripe products.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

"use client";

 

import { useRouter } from "next/navigation";

import {

  createContext,

  type FC,

  type ReactNode,

  useContext,

  useEffect,

  useMemo,

  useState,

} from "react";

import axios from "axios"; // 1) Import axios

import { Flag } from "~/components/flag";

import {

  Select,

  SelectContent,

  SelectGroup,

  SelectItem,

  SelectTrigger,

  SelectValue,

} from "~/components/ui/select";

import { cn } from "~/lib/utils";

import { type Currency } from "~/server/schemas/currency";

 

// -- [1] Create a local type for the data returned by /api/geolocation.

type GeolocationData = {

  country_code?: string;

  continent_code?: string;

  currency?: string;

};

 

type CurrencyContext = {

  currency: Currency;

  setCurrency: (currency: Currency) => void;

};

 

const CurrencyContext = createContext<CurrencyContext | null>(null);

 

export function useCurrency() {

  const context = useContext(CurrencyContext);

  if (!context) {

    throw new Error("useCurrency must be used within a CurrencyProvider.");

  }

  return context;

}

 

export const CurrencyProvider: FC<{ children: ReactNode }> = ({ children }) => {

  const router = useRouter();

 

  // -- [2] Local state for geolocation data

  const [location, setLocation] = useState<GeolocationData | null>(null);

  const [isLoading, setIsLoading] = useState<boolean>(true);

 

  // -- [3] Fetch location once when the component mounts

  useEffect(() => {

    const fetchLocation = async () => {

      setIsLoading(true);

      try {

        const response = await axios.get("/api/geolocation");

        setLocation(response.data);

      } catch (error) {

        console.error(error);

      } finally {

        setIsLoading(false);

      }

    };

 

    void fetchLocation();

  }, []);

 

  // -- [4] Extract currency from location if present (fallback to "usd")

  const geoCurrency = location?.currency;

 

  const getInitialCurrency = (): Currency => {

    if (typeof window !== "undefined") {

      const cookie = document.cookie

        .split("; ")

        .find((row) => row.startsWith("currency="));

      if (cookie) {

        const value = cookie.split("=")[1];

        if (value === "usd" || value === "eur" || value === "gbp") {

          return value;

        }

      }

    }

    return "usd";

  };

 

  const [currency, setCurrencyState] = useState<Currency>(getInitialCurrency);

 

  useEffect(() => {

    if (!isLoading && geoCurrency !== undefined) {

      const validatedCurrency = validateCurrency(geoCurrency, location);

      if (validatedCurrency) {

        setCurrency(validatedCurrency);

      }

    }

    // eslint-disable-next-line react-hooks/exhaustive-deps

  }, [isLoading, location, geoCurrency]);

 

  // -- [5] Update currency & store cookie; no more tRPC invalidation

  const setCurrency = (newCurrency: Currency) => {

    setCurrencyState(newCurrency);

    if (typeof window !== "undefined") {

      document.cookie = `currency=${newCurrency}; path=/; max-age=${

        60 * 60 * 24 * 365

      }`; // Expires in 1 year

    }

    // Removed tRPC invalidate since we are no longer using tRPC

    router.refresh();

  };

 

  const contextValue = useMemo<CurrencyContext>(

    () => ({

      currency,

      setCurrency,

    }),

    [currency],

  );

 

  return (

    <CurrencyContext.Provider value={contextValue}>

      {children}

    </CurrencyContext.Provider>

  );

};

 

export const CurrencySelect = ({ className }: { className?: string }) => {

  const { currency, setCurrency } = useCurrency();

  return (

    <Select value={currency} onValueChange={setCurrency}>

      <SelectTrigger className={cn("w-[250px]", className)}>

        <SelectValue placeholder="Select a currency" />

      </SelectTrigger>

      <SelectContent>

        <SelectGroup className="text-sm">

          <SelectItem value="usd">

            <div className="flex items-center gap-3">

              <Flag code="US" className="h-4 w-4 rounded" /> <span>$ USD</span>

            </div>

          </SelectItem>

          <SelectItem value="eur">

            <div className="flex items-center gap-3">

              <Flag code="EU" className="h-4 w-4 rounded" /> <span>€ EUR</span>

            </div>

          </SelectItem>

          <SelectItem value="gbp">

            <div className="flex items-center gap-3">

              <Flag code="GB" className="h-4 w-4 rounded" /> <span>£ GBP</span>

            </div>

          </SelectItem>

        </SelectGroup>

      </SelectContent>

    </Select>

  );

};

 

// -- [6] Use our new GeolocationData type in place of RouterOutputs

const validateCurrency = (

  currency: string,

  location?: GeolocationData | null,

): Currency | null => {

  if (currency === "usd" || currency === "eur" || currency === "gbp") {

    return currency;

  }

 

  if (!location) {

    return null;

  }

 

  if (location.country_code === "GB") {

    return "gbp";

  }

 

  // Check if they are in the EU

  if (location.continent_code === "EU") {

    return "eur";

  }

 

  // North America

  if (location.continent_code === "NA") {

    return "usd";

  }

 

  return null;

};

Copy after login

The above is the detailed content of Building an Automatic Currency Switcher in Next.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles