Trying to get users ip in an api route using middleware.js
Unanswered
Kuchi posted this in #help-forum
![Avatar](https://cdn.discordapp.com/embed/avatars/2.png)
KuchiOP
Here's my api route
is that sufficient for grabbing user ip within an api route that gets called inside my middleware.js file?
export default withIronSessionApiRoute(async (req, res) => {
let ip = req.ip ?? req.headers["x-real-ip"];
const forwardedFor = req.headers["x-forwarded-for"];
if (!ip && forwardedFor) {
ip = forwardedFor.split(",")[0] ?? "Unknown";
} else if (req.socket.remoteAddress && req.socket.remoteAddress !== "::1") {
// // If x-forwarded-for header is not available, use the remoteAddress
ip = req.socket.remoteAddress.includes(":")
? req.socket.remoteAddress.split(":").slice(-1)[0]
: req.socket.remoteAddress;
}
if (!ip || ip === null) {
// If IP address couldn't be determined, handle it accordingly
res.status(500).json({ error: "Failed to determine IP address" });
return;
}
is that sufficient for grabbing user ip within an api route that gets called inside my middleware.js file?