Skip to content

Commit 6e66659

Browse files
committed
feat(cloudflare): add geolocation support
1 parent 52a7194 commit 6e66659

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

packages/open-next/src/core/routingHandler.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ import type { InternalEvent, InternalResult, Origin } from "types/open-next";
99
import { debug } from "../adapters/logger";
1010
import { cacheInterceptor } from "./routing/cacheInterceptor";
1111
import {
12-
getNextConfigHeaders,
1312
fixDataPage,
13+
getNextConfigHeaders,
1414
handleFallbackFalse,
1515
handleRedirects,
1616
handleRewrites,

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-open-next-city",
11+
country: "x-open-next-country",
12+
region: "x-open-next-region",
13+
latitude: "x-open-next-latitude",
14+
longitude: "x-open-next-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)