HonoH
Hono10mo ago
Mitul Kheni

Unable to get the client's IP

I am using bun and creating a request middleware to log the requests, but I am having a hard time getting the client's IP address.
server.ts file code:
import { config } from './config/config';
import app from './index';
import { webSocketHandler } from './web-socket';

const port = config.port;

const server = Bun.serve({
    port,
    fetch: async (req, server) => {
        if (server.upgrade(req)) {
            return;
        }
        return await app.fetch(req, config);
    },
    websocket: webSocketHandler,
});

export default server;


request.middleware.ts:
import { type MiddlewareHandler } from 'hono';
import { RequestLog } from '../database/entities/request-log.entity';
import type { IRequestLog } from '../database/interface/request-log.interface';
import { getConnInfo } from 'hono/bun';

export const requestLogger: MiddlewareHandler = async (c, next) => {
    const start = Date.now();
    await next();
    const end = Date.now();

    const logEntry = new RequestLog<Partial<IRequestLog>>({
        clientIp: getConnInfo(c).remote.address || 'unknown',
        ...
    });

    await logEntry
        .save()
        .catch((err) => console.trace('Failed to log request:', err));
};


Error I am getting:
<-- GET /api/home
4 |   const server = getBunServer(c);
5 |   if (!server) {
6 |     throw new TypeError("env has to include the 2nd argument of fetch.");
7 |   }
8 |   if (typeof server.requestIP !== "function") {
9 |     throw new TypeError("server.requestIP is not a function.");
              ^
TypeError: server.requestIP is not a function.
      at getConnInfo (/Users/iweenggs/NodeJS/wego/node_modules/hono/dist/adapter/bun/conninfo.js:9:11)
      at <anonymous> (/Users/iweenggs/NodeJS/wego/src/middlewares/request-logger.middleware.ts:19:19)


I have tried to get the ip from c.req.header('X-Forwarded-For'); But that also did not work.
Was this page helpful?