How to make express's request.ip work in Bun
Tried Bun with an express app but stumbled upon a bug where req.ip is undefined? Fear not, here is the solution.
bun
express
The solution
Just adjust your express app code like below:
import { createServer } from 'http';
const app = express();
// your express setups: app.use(), app.get(), etc...
// then use cereateServer from http module
const server = createServer(app);
// then consolidate request socket address
server.on('request', (req, _res) => {
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
req.socket.remoteAddress; // make express req.ip work in bun
});
// make the server listen to requests as usual
server.listen(
process.env.PORT,
process.env.NODE_ENV !== production ? 'localhost' : '0.0.0.0',
() => {
console.log('Listening !!!!')
}
);
This twitter post may help you get it.