I'm trying to forward traffic to a specific slug based on the user's country code after an IP address lookup.
It works perfectly locally but it's not working when I deploy to Netlify.
export default defineNuxtRouteMiddleware(async (to, from) => {
const targetPathDe = '/de-de'
const targetPathEn = '/de-en'
// Prevent middleware from redirecting if already on the target path
if (to.path === targetPathDe || to.path === targetPathEn) {
return
}
const ipApiUrl = 'http://ip-api.com/json/?fields=countryCode'
try {
// Use native fetch to get IP data
const response = await fetch(ipApiUrl)
const ipData = await response.json()
// Check the country code from IP data
if (ipData.countryCode === 'DE') {
return navigateTo(targetPathDe)
} else {
return navigateTo(targetPathEn)
}
} catch (error) {
console.error('Error fetching IP data:', error)
return navigateTo(targetPathEn)
}
})
Locally, I'm running npm run dev
and Netlify is npm run build
.
OP considered using the geolocation edge function for now.
It is easier to implement and probably more precise too!