튜토리얼/React로 통화 변환기 만들기

React로 통화 변환기 만들기

React로 통화 변환기 만들기. 코드, 캐시, 최신성 메타데이터를 포함한 실용 가이드입니다.

ERexchangerate.dev·Sep 20, 2026·7분 분량

자격 증명을 노출하지 않고 서버에서 구현하며 출처와 관측 시각을 보존합니다.

핵심 요점
API 키는 서버에만 보관합니다.
통화 코드와 금액을 검증합니다.
성공한 응답을 캐시합니다.
출처와 관측 시각을 표시합니다.

단계 1

서버에서 실행하고 입력값을 검증하며 응답 메타데이터를 보존하세요.

코드 예제copy
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
  const { searchParams } = request.nextUrl;
  const from = searchParams.get("from")?.toUpperCase();
  const to = searchParams.get("to")?.toUpperCase();
  const amount = Number(searchParams.get("amount"));
  if (!from || !to || !Number.isFinite(amount) || amount < 0) {
    return NextResponse.json({ error: "invalid_input" }, { status: 400 });
  }

  const response = await fetch(
    `https://api.exchangerate.dev/v1/convert/${from}/${to}/${amount}`,
    {
      headers: { Authorization: `Bearer ${process.env.EXCHANGERATE_API_KEY}` },
      signal: AbortSignal.timeout(5000),
      next: { revalidate: 60 },
    },
  );
  return NextResponse.json(await response.json(), { status: response.status });
}

단계 2

코드 예제copy
"use client";

import { FormEvent, useState } from "react";

type ConversionResult = {
  converted: string;
  source: string;
  data_updated_at: string;
};

export function CurrencyConverter() {
  const [amount, setAmount] = useState("100");
  const [result, setResult] = useState<ConversionResult | null>(null);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  async function submit(event: FormEvent) {
    event.preventDefault();
    setLoading(true); setError("");
    try {
      const params = new URLSearchParams({ from: "USD", to: "EUR", amount });
      const response = await fetch(`/api/convert?${params}`);
      const body = await response.json();
      if (!response.ok) throw new Error(body.error ?? "conversion_failed");
      setResult(body);
    } catch (caught) {
      setError(caught instanceof Error ? caught.message : "conversion_failed");
    } finally { setLoading(false); }
  }

  return <form onSubmit={submit}>
    <input value={amount} onChange={(event) => setAmount(event.target.value)} inputMode="decimal" />
    <button disabled={loading}>{loading ? "Converting…" : "Convert"}</button>
    {error && <p role="alert">{error}</p>}
    {result && <output>{result.converted} EUR · {result.source} · {result.data_updated_at}</output>}
  </form>;
}

단계 3

  • API 키는 서버에만 보관합니다.
  • 통화 코드와 금액을 검증합니다.
  • 성공한 응답을 캐시합니다.
  • 출처와 관측 시각을 표시합니다.
가이드
이 환율은 참고용이며 결제 가격이 아닙니다.
ER
exchangerate.dev
통화 데이터를 사용하는 개발자를 위한 실용 가이드입니다.

계속 읽기

가이드개발자를 위한 통화 변환 API읽기 가이드API errors and response fields읽기