denoland / deploy_feedback

For reporting issues with Deno Deploy
https://deno.com/deploy
74 stars 5 forks source link

How to get client ip on Nuxt3 middleware? #572

Open jasonleong opened 10 months ago

jasonleong commented 10 months ago

file: /server/middleware/getip.ts

export default defineEventHandler(async (event) => {

console.log(getRequestIP(event, { xForwardedFor: true }));//result is "undefined"
console.log(event.node.req.connection.remoteAddress); //result is "undefined"
console.log(event.node.req.socket.remoteAddress); //result is "undefined" too
//here how to get the client ip ? 

});

thank you!

ry commented 10 months ago

Here's an example of how to get the client IP

Deno.serve((req: Request, conn) => {
    let ip = conn.remoteAddr.hostname;
    return new Response("Hello World " + ip)
});
revgum commented 8 months ago

If you're using Hono server and want to inject the client IP into the env for downstream handling, here's a method that works;

const server = new Hono(options);

Deno.serve({
  port,
  handler: (req: Request, conn: Deno.ServeHandlerInfo) => server.fetch(req, { remoteAddr: conn.remoteAddr }),
});

// A Hono route handler in your code

type Bindings = {
  remoteAddr: Deno.NetAddr;
};

app.get("/my-route", async (c: Context<{ Bindings: Bindings }>) => {
  console.log(c.env.remoteAddr); // { transport: string, hostname: string, port: number }
  ...
});