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