Skip to content

Instantly share code, notes, and snippets.

@frandiox
Created October 23, 2023 10:20
Show Gist options
  • Save frandiox/cf671efb84681519f76cb8bbc5fd8a45 to your computer and use it in GitHub Desktop.
Save frandiox/cf671efb84681519f76cb8bbc5fd8a45 to your computer and use it in GitHub Desktop.
How to get the client IP from the request object in multiple JS runtimes / platforms

When the handler is behind a proxy server

Reference

const ips = request.headers.get('x-forwarded-for'); // comma-separated list of IPs

Node

Reference

import http from 'node:http';

http
  .createServer((request) => {
    const ip = request.socket.remoteAddress;
  })

Express

Reference

import express from 'express'

express().get('*', (request) => {
  const ip = request.ip;
})

Cloudflare Workers

Reference

export default {
  async fetch(request) {
    const ip = request.headers.get('cf-connecting-ip');
  }
}

Deno

With the std lib serve (deprecated)

Reference

import { serve } from 'https://deno.land/std@0.92.0/http/server.ts';

const server = serve({port: 8000});

for await (const request of server) {
  const ip = request.conn.remoteAddr.hostname;
}

With the new experimental http API (after v1.25)

Reference

Deno.serve((request, info) => {
  const ip = info.remoteAddr.hostname;
});

Bun

Reference

export default {
  async fetch(request, server) {
    const ip = server.requestIP(request);
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment