Skip to content

Commit

Permalink
Fix ip address fetching to use vercel forwarded ip address
Browse files Browse the repository at this point in the history
  • Loading branch information
muliswilliam committed Sep 20, 2023
1 parent decf1be commit e919355
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions src/pages/api/ip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,17 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
})
}

console.log('x-vercel-forwarded-for' ,req.headers['x-vercel-forwarded-for'])
console.log('x-vercel-ip-country' ,req.headers['x-vercel-ip-country'])
console.log('x-vercel-ip-country-region' ,req.headers['x-vercel-ip-country-region'])
console.log('x-vercel-ip-city' ,req.headers['x-vercel-ip-city'])
console.log('x-vercel-ip-longitude' ,req.headers['x-vercel-ip-longitude'])
console.log('x-vercel-ip-latitude' ,req.headers['x-vercel-ip-latitude'])
console.log('x-vercel-ip-timezone' ,req.headers['x-vercel-ip-timezone'])
// TODO: Use these values instead of making a request to ip-api.com
// console.log('x-vercel-forwarded-for' ,req.headers['x-vercel-forwarded-for'])
// console.log('x-vercel-ip-country' ,req.headers['x-vercel-ip-country'])
// console.log('x-vercel-ip-country-region' ,req.headers['x-vercel-ip-country-region'])
// console.log('x-vercel-ip-city' ,req.headers['x-vercel-ip-city'])
// console.log('x-vercel-ip-longitude' ,req.headers['x-vercel-ip-longitude'])
// console.log('x-vercel-ip-latitude' ,req.headers['x-vercel-ip-latitude'])
// console.log('x-vercel-ip-timezone' ,req.headers['x-vercel-ip-timezone'])

const response = await fetch('http://ip-api.com/json/')
const ipAddress = req.headers['x-vercel-forwarded-for'] as string
const response = await fetch(`http://ip-api.com/json/${ipAddress}`)
const data = await response.json()
const { status, query, ...rest } = data

Expand All @@ -27,4 +29,4 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
const ipInfo = { ...rest, ipAddress: query } as IpAddressInfo

res.status(200).json({ ...ipInfo })
}
}

0 comments on commit e919355

Please sign in to comment.