get-ip-address.ts 663 B

12345678910111213141516171819
  1. import { NextApiRequest, NextApiResponse } from 'next'
  2. const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  3. let ipAddress = req.headers['x-real-ip'] as string
  4. const forwardedFor = req.headers['x-forwarded-for'] as string
  5. // With CF infront, the user IP will be in this header instead of the x-forwared-for
  6. const cfConnectingIp = req.headers['cf-connecting-ip'] as string
  7. if (cfConnectingIp) {
  8. ipAddress = cfConnectingIp.split(',').at(0) ?? 'Unknown'
  9. } else if (!ipAddress && forwardedFor) {
  10. ipAddress = forwardedFor.split(',').at(0) ?? 'Unknown'
  11. }
  12. return res.status(200).json({ ipAddress })
  13. }
  14. export default handler