Skip to content

Commit 38a33f7

Browse files
committed
feat(cloudflare): add geolocation support
1 parent ff659f0 commit 38a33f7

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

packages/open-next/src/overrides/wrappers/cloudflare.ts

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,20 @@ import type {
66

77
import type { MiddlewareOutputEvent } from "../../core/routingHandler";
88

9+
const cfPropNameToHeaderName = {
10+
city: "x-vercel-ip-city",
11+
country: "x-vercel-ip-country",
12+
region: "x-vercel-ip-country-region",
13+
latitude: "x-vercel-ip-latitude",
14+
longitude: "x-vercel-ip-longitude",
15+
};
16+
917
const handler: WrapperHandler<
1018
InternalEvent,
1119
InternalResult | ({ type: "middleware" } & MiddlewareOutputEvent)
1220
> =
1321
async (handler, converter) =>
14-
async (event: Request, env: Record<string, string>): Promise<Response> => {
22+
async (request: Request, env: Record<string, string>): Promise<Response> => {
1523
globalThis.process = process;
1624

1725
// Set the environment variables
@@ -22,7 +30,20 @@ const handler: WrapperHandler<
2230
}
2331
}
2432

25-
const internalEvent = await converter.convertFrom(event);
33+
const internalEvent = await converter.convertFrom(request);
34+
35+
// Retrieve geo information from the cloudflare request
36+
// See https://developers.cloudflare.com/workers/runtime-apis/request
37+
// Note: This code could be moved to a cloudflare specific converter when one is created.
38+
const cfProperties = (request as any).cf as Record<string, string | null>;
39+
for (const [propName, headerName] of Object.entries(
40+
cfPropNameToHeaderName,
41+
)) {
42+
const propValue = cfProperties[propName];
43+
if (propValue !== null) {
44+
internalEvent.headers[headerName] = propValue;
45+
}
46+
}
2647

2748
const response = await handler(internalEvent);
2849

0 commit comments

Comments
 (0)