Hi if anyone have any input on this, will greatly appreicated.
I am using the maxmind database but it seems like it not setting the region based on the ip address.
This is my code in the middleware.
async function getCountryCode(
request: NextRequest,
regionMap: Map<string, Region | number>
) {
try {
let countryCode
let ipAddress: string | null = request.headers.get("x-forwarded-for") || null;
if (ipAddress) {
// The x-forwarded-for can contain multiple IP addresses; use the first one.
ipAddress = ipAddress.split(",")[0].trim()
}
console.log(ipAddress)
// Fetch country code using the extracted IP address
const maxmindDBCountryCode = await fetch(${BACKEND_URL}/store/ip-lookup, {
headers: {
"x-real-ip": ipAddress ?? "",
},
})
const data = await maxmindDBCountryCode.json()
const urlCountryCode = request.nextUrl.pathname.split("/")[1]?.toLowerCase()
// Prioritize country code from IP lookup if available and valid
if (data.country_code && regionMap.has(data.country_code.toLowerCase())) {
countryCode = data.country_code.toLowerCase()
}
// If a country code is specified in the URL and valid, use it
if (urlCountryCode && regionMap.has(urlCountryCode)) {
countryCode = urlCountryCode
}
// If no valid country code from above, use the default region
if (!countryCode && regionMap.has(DEFAULT_REGION)) {
countryCode = DEFAULT_REGION
}
// If still no country code, use the first available region in the map
if (!countryCode && regionMap.keys().next().value) {
countryCode = regionMap.keys().next().value
}
return countryCode
} catch (error) {
if (process.env.NODE_ENV === "development") {
console.error(
"Middleware.ts: Error getting the country code. Did you set up regions in your Medusa Admin and define a NEXT_PUBLIC_MEDUSA_BACKEND_URL environment variable?"
)
}
}
}