How to use Google Analytics in Deno Deploy
Google Analytics is a popular and simple way to get basic analytics on your site. While dropping GAâs JavaScript snippet on the client-side is easy, it doesnât work when visitors use ad blockers. (For example, over 70% of our audience uses ad blockers.) Using server-side GA not only avoids ad blockers, but also is more reliable and accurate.
Deno Deploy
Deno Deploy is our edge computing service that runs modern JavaScript and TypeScript around the world. Services on Deno Deploy are highly available with minimal latency, which can be used for a variety of use cases, from static sites and e-commerce stores to oauth micro services. (This blog that you are reading right now is hosted on Deno Deploy!)
No matter what your use case is with Deno Deploy, now you can easily add Google Analytics to better understand how users are engaging with your website or service.
Example
We wrote a GA integration as a module, which can be imported directly into your Deno CLI or Deploy Project. Note that the module currently supports the classic Universal Analytics, though we are investigating moving to GA4.
import { createReporter } from "https://deno.land/x/g_a/mod.ts";
import { serve } from "https://deno.land/std/http/server.ts";
const ga = createReporter({ id: "UA-123" });
serve((req, connInfo) => {
let err;
let res;
const start = performance.now();
try {
res = new Response("hello world");
} catch (e) {
err = e;
} finally {
ga(req, connInfo, res, start, err);
}
return res;
});
Or try this example in a Deno Deploy playground: server-side-ga.
If youâre using Denoâs HTTP middleware server oak, then you can also add GA as middleware:
import { createReportMiddleware } from "https://deno.land/x/g_a/mod.ts";
import { Application } from "https://deno.land/x/oak/mod.ts";
const ga = createReportMiddleware({ id: "UA-123" });
const app = new Application();
app.use(ga);
app.use((ctx) => {
ctx.response.body = "Hello World!";
});
app.listen();
You can also set your UA property as an environmental variable, GA_TRACKING_ID
in the Deploy settings:
And the above integration will work right out of the box:
Whatâs next
Google Analytics is a powerful and free analytics tool. Weâre currently investigating moving to GA4, as well as adding support for sending events. If youâre using this GA module, weâd love to get your feedback.