mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-09-21 01:53:26 +00:00
Enhance tracking with geolocation headers and continent info in analytics proxy (#3667)
Co-authored-by: Nicolas Dorseuil <nicolas@gitbook.io>
This commit is contained in:
@@ -26,8 +26,10 @@ export default class extends WorkerEntrypoint {
|
||||
async fetch(request) {
|
||||
return runWithCloudflareRequestContext(request, this.env, this.ctx, async () => {
|
||||
const startTime = Date.now();
|
||||
const middlewareRequest = new Request(request.url, request);
|
||||
middlewareRequest.headers.set('x-open-next-continent', request.cf?.continent || '');
|
||||
// - `Request`s are handled by the Next server
|
||||
const reqOrResp = await middlewareHandler(request, this.env, this.ctx);
|
||||
const reqOrResp = await middlewareHandler(middlewareRequest, this.env, this.ctx);
|
||||
if (reqOrResp instanceof Response) {
|
||||
const duration = Date.now() - startTime;
|
||||
const logMessage = formatLog(
|
||||
|
||||
@@ -28,6 +28,17 @@ export function shouldTrackEvents(headers?: Awaited<ReturnType<typeof nextHeader
|
||||
export async function serveProxyAnalyticsEvent(req: Request) {
|
||||
const requestURL = new URL(req.url);
|
||||
|
||||
// Fill geolocation data from request headers either from OpenNext or Vercel
|
||||
const country =
|
||||
req.headers.get('x-open-next-country') || req.headers.get('x-vercel-ip-country');
|
||||
const latitude =
|
||||
req.headers.get('x-open-next-latitude') || req.headers.get('x-vercel-ip-latitude');
|
||||
const longitude =
|
||||
req.headers.get('x-open-next-longitude') || req.headers.get('x-vercel-ip-longitude');
|
||||
// OpenNext doesn't provide continent info, we add it manually in our custom worker
|
||||
const continent =
|
||||
req.headers.get('x-open-next-continent') || req.headers.get('x-vercel-ip-continent');
|
||||
|
||||
const org = requestURL.searchParams.get('o');
|
||||
const site = requestURL.searchParams.get('s');
|
||||
if (!org || !site) {
|
||||
@@ -43,6 +54,10 @@ export async function serveProxyAnalyticsEvent(req: Request) {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(country ? { 'x-location-country': country } : {}),
|
||||
...(latitude ? { 'x-location-latitude': latitude } : {}),
|
||||
...(longitude ? { 'x-location-longitude': longitude } : {}),
|
||||
...(continent ? { 'x-location-continent': continent } : {}),
|
||||
},
|
||||
body: req.body,
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user