honojs / website

Repository for hono.dev
https://hono.dev
68 stars 213 forks source link

Add section on obtaining client IP address #313

Closed NicoPlyley closed 2 months ago

NicoPlyley commented 2 months ago

This has been a big question on Discord. Currently this is the only way I found to solve this issue.

I understand if you do not want it added since it may not be the ideal way since the ip address is added to the env which is meant for environment variables.

yusukebe commented 2 months ago

Hi @NicoPlyley !

I think your way is good! Plus, we can add the type by using a Bindings generics like the following:

import type { SocketAddress } from 'bun'
import { Hono } from 'hono'

type Bindings = {
  ip: SocketAddress
}

const app = new Hono<{ Bindings: Bindings }>()

app.get('/', (c) => {
  return c.json({
    yourIp: c.env.ip
  })
})

Bun.serve({
  fetch(req, server) {
    return app.fetch(req, { ip: server.requestIP(req) })
  }
})

Bindings seems to be only for Cloudflare, but we are now using it in Node.js adapter.

NicoPlyley commented 2 months ago

Great! I made some updates with the Bindings example and output of c.env.ip

yusukebe commented 2 months ago

@NicoPlyley

Thanks Nico! Let's go with this.