Files
sweet/www/routes/_middleware.ts
T
Bartek Iwańczuk 214975d90d chore: inline ga4 module and remove raw GitHub import (#3733)
## Summary
- Inlined the `$ga4` module (from
`https://raw.githubusercontent.com/denoland/ga4/main/mod.ts`) into
`www/utils/ga4.ts`
- Replaced old `deno.land/std` URL imports with `@std/http`
(`getCookies`, `STATUS_TEXT`)
- Inlined the trivial `snakeCase` helper (was from `deno.land/x/case`)
- Removed `$ga4` import map entry from `deno.json`

The ga4 package was never published to jsr or npm, so inlining was the
cleanest way to eliminate the last raw URL-based dependency.
2026-03-28 12:05:13 +00:00

117 lines
2.9 KiB
TypeScript

import type { Context } from "fresh";
import type { Event } from "../utils/ga4.ts";
import { GA4Report, isDocument, isServerError } from "../utils/ga4.ts";
const GA4_MEASUREMENT_ID = Deno.env.get("GA4_MEASUREMENT_ID");
let showedMissingEnvWarning = false;
function ga4<T>(
request: Request,
conn: Context<T>,
response: Response,
_start: number,
error?: unknown,
) {
if (GA4_MEASUREMENT_ID === undefined) {
if (!showedMissingEnvWarning) {
showedMissingEnvWarning = true;
// deno-lint-ignore no-console
console.warn(
"GA4_MEASUREMENT_ID environment variable not set. Google Analytics reporting disabled.",
);
}
return;
}
Promise.resolve().then(async () => {
// We're tracking page views and file downloads. These are the only two
// HTTP methods that _might_ be used.
if (!/^(GET|POST)$/.test(request.method)) {
return;
}
// If the visitor is using a web browser, only create events when we serve
// a top level documents or download; skip assets like css, images, fonts.
if (!isDocument(request, response) && error == null) {
return;
}
let event: Event | null = null;
const contentType = response.headers.get("content-type");
if (/text\/html/.test(contentType!)) {
event = { name: "page_view", params: {} }; // Probably an old browser.
}
if (event == null && error == null) {
return;
}
// If an exception was thrown, build a separate event to report it.
let exceptionEvent;
if (error != null) {
exceptionEvent = {
name: "exception",
params: {
description: String(error),
fatal: isServerError(response),
},
};
} else {
exceptionEvent = undefined;
}
// Create basic report.
const measurementId = GA4_MEASUREMENT_ID;
// @ts-ignore GA4Report doesn't even use the localAddress parameter
const report = new GA4Report({
measurementId,
request,
response,
// Doesn't use localAddr
// deno-lint-ignore no-explicit-any
conn: conn.info as any,
});
// Override the default (page_view) event.
report.event = event;
// Add the exception event, if any.
if (exceptionEvent != null) {
report.events.push(exceptionEvent);
}
await report.send();
}).catch((err) => {
// deno-lint-ignore no-console
console.error(err);
});
}
export async function handler<T>(
ctx: Context<T>,
): Promise<Response> {
let err;
let res: Response;
const start = performance.now();
try {
const resp = await ctx.next();
const headers = new Headers(resp.headers);
res = new Response(resp.body, { status: resp.status, headers });
return res;
} catch (e) {
res = new Response("Internal Server Error", {
status: 500,
});
err = e;
throw e;
} finally {
ga4(
ctx.req,
ctx,
res!,
start,
err,
);
}
}