diff --git a/apps/frontend/src/composables/country.js b/apps/frontend/src/composables/country.js deleted file mode 100644 index 19a0aca27..000000000 --- a/apps/frontend/src/composables/country.js +++ /dev/null @@ -1,6 +0,0 @@ -export const useUserCountry = () => - useState("userCountry", () => { - const headers = useRequestHeaders(["cf-ipcountry"]); - - return headers["cf-ipcountry"] ?? "US"; - }); diff --git a/apps/frontend/src/composables/country.ts b/apps/frontend/src/composables/country.ts new file mode 100644 index 000000000..0d3dd6a81 --- /dev/null +++ b/apps/frontend/src/composables/country.ts @@ -0,0 +1,36 @@ +import { useState, useRequestHeaders } from "#imports"; + +export const useUserCountry = () => { + const country = useState("userCountry", () => "US"); + const fromServer = useState("userCountryFromServer", () => false); + + if (import.meta.server) { + const headers = useRequestHeaders(["cf-ipcountry", "accept-language"]); + const cf = headers["cf-ipcountry"]; + if (cf) { + country.value = cf.toUpperCase(); + fromServer.value = true; + } else { + const al = headers["accept-language"] || ""; + const tag = al.split(",")[0]; + const val = tag.split("-")[1]?.toLowerCase(); + if (val) { + country.value = val; + fromServer.value = true; + } + } + } + + if (import.meta.client) { + onMounted(() => { + if (fromServer.value) return; + const lang = navigator.language || navigator.userLanguage || ""; + const region = lang.split("-")[1]; + if (region) { + country.value = region.toUpperCase(); + } + }); + } + + return country; +};