getGeolocationForIpAddress

Functionin geolocation@fastly/js-compute 4.0.0View source
getGeolocationForIpAddress(address: string): Geolocation | null

Retrieve geolocation information about the given IP address.

Note: Can only be used when processing requests, not during build-time initialization.

Parameters

address: string

The IPv4 or IPv6 address to query.

Returns

Geolocation | null

A Geolocation object, or null if no geolocation data is available for the address.

Throws

  • {Error} If address is not a valid IPv4 or IPv6 address.
1
2
3
4
5
6
7
8
9
10
11
12
13
import { getGeolocationForIpAddress } from "fastly:geolocation";
async function app(event) {
const ip =
new URL(event.request.url).searchParams.get("ip") ||
event.client.address;
const geo = getGeolocationForIpAddress(ip);
return new Response(JSON.stringify(geo), {
headers: { "Content-Type": "application/json" },
});
}
addEventListener("fetch", (event) => event.respondWith(app(event)));