diff --git a/apps/web/pages/api/countrycode.ts b/apps/web/pages/api/countrycode.ts new file mode 100644 index 0000000000..db40ce2ce7 --- /dev/null +++ b/apps/web/pages/api/countrycode.ts @@ -0,0 +1,20 @@ +import type { NextRequest } from "next/server"; + +export const config = { + runtime: "experimental-edge", +}; + +export default async function handler(req: NextRequest) { + const countryCode = req.headers.get("x-vercel-ip-country") ?? ""; + return new Response( + JSON.stringify({ + countryCode, + }), + { + status: 200, + headers: { + "content-type": "application/json", + }, + } + ); +} diff --git a/packages/ui/form/PhoneInput.tsx b/packages/ui/form/PhoneInput.tsx index 27e247e040..125750caee 100644 --- a/packages/ui/form/PhoneInput.tsx +++ b/packages/ui/form/PhoneInput.tsx @@ -1,3 +1,5 @@ +import { isSupportedCountry } from "libphonenumber-js"; +import { useEffect, useState } from "react"; import type { Props } from "react-phone-number-input/react-hook-form"; import BasePhoneInput from "react-phone-number-input/react-hook-form"; import "react-phone-number-input/style.css"; @@ -19,10 +21,12 @@ function PhoneInput({ onChange, ...rest }: PhoneInputProps) { + const defaultCountry = useDefaultCountry(); return ( ({ ); } +const useDefaultCountry = () => { + const [defaultCountry, setDefaultCountry] = useState("US"); + useEffect(() => { + fetch("/api/countrycode") + .then((res) => res.json()) + .then((res) => { + if (isSupportedCountry(res.countryCode)) setDefaultCountry(res.countryCode); + }) + .catch((err) => { + console.log(err); + }); + }, []); + + return defaultCountry; +}; + export default PhoneInput;