Unable to get the user's source IP address

addEventListener("fetch", event => {
  const json = JSON.stringify(event.request)

  return event.respondWith(
    new Response(json, {
      headers: {
        "content-type": "application/json;charset=UTF-8"
      }
    })
  )
})
{"request":{"cf":{"clientTcpRtt":36,"longitude":"114.15210","latitude":"22.21080","tlsCipher":"AEAD-AES128-GCM-SHA256","continent":"AS","asn":42378,"clientAcceptEncoding":"gzip, deflate, br","country":"HK","tlsClientAuth":{"certIssuerDNLegacy":"","certIssuerSKI":"","certSubjectDNRFC2253":"","certSubjectDNLegacy":"","certFingerprintSHA256":"","certNotBefore":"","certSKI":"","certSerial":"","certIssuerDN":"","certVerified":"NONE","certNotAfter":"","certSubjectDN":"","certPresented":"0","certRevoked":"0","certIssuerSerial":"","certIssuerDNRFC2253":"","certFingerprintSHA1":""},"tlsExportedAuthenticator":{"clientFinished":"0d34943256db65d6dd9129ed1921ce2ab6ee4d9223a93a13e3","clientHandshake":"8012522130ca05142de676d96295852100efdedbb13b899998f10f6","serverHandshake":"3fdfc997e47f81a798b8d574273fb59b4e78e8f28814b0f1bf0a5b","serverFinished":"52e1005330053ce23a47a783ad0ad2a97de747435e0c2eaf8"},"tlsVersion":"TLSv1.3","colo":"SIN","timezone":"Asia/Hong_Kong","region":"Central and Western District","requestPriority":"weight=256;exclusive=1","edgeRequestKeepAliveStatus":1,"regionCode":"HCW","city":"Central","httpProtocol":"HTTP/2"},"fetcher":{},"redirect":"manual","headers":{},"url":"https://zzz.workers.dev/","method":"GET","bodyUsed":false,"body":null},"type":"fetch"}

No IP information in the event.request field.

That’s because it’s in the headers.

2 Likes

addEventListener("fetch", event => {
  let requestHeaders = JSON.stringify(Object.fromEntries(event.request.headers), null, 2)
  console.log(`Request headers: ${requestHeaders}`)
  
  const json = JSON.stringify(event.request.headers)

  return event.respondWith(
    new Response(json, {
      headers: {
        "content-type": "application/json;charset=UTF-8"
      }
    })
  )
})

It doesn’t show in the playground. Those headers are set only in production environments.

You can manually add it though, to check if the code works, there is the ability right there to add headers.

1 Like


This is the browser console in the production environment and you can see that the headers field is empty.

Read the documentation again, the header has to be iterated correctly, it’s not a normal object.

3 Likes

It worked, thanks a lot!

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.