- Notifications
You must be signed in to change notification settings - Fork9
Utilities for server side processing of Google Analytics in Deno CLI and Deploy
License
denoland/ga
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Utilities for server side processing of Google Analytics in Deno CLI and Deploy.
When you server side render pages, it can be more efficient to not add GoogleAnalytics to the client side app, and instead send the messages directly viayour edge worker. This library provides a framework for doing this.
The library is designed to generate a measure message for each request andresponse handled by a Deno CLI or Deno Deploy server. These messages are thenqueued up and asynchronously batched to Google Analytics.
If you are using the Deno HTTP APIs directly,std/http
, or various other HTTPframeworks,createReporter()
will return a function which can be used todispatch messages to Google Analytics.
You need to create the reporter function, and then call the reporter withinformation about the current request and response.
import{createReporter}from"https://deno.land/x/g_a/mod.ts";constreporter=createReporter();
If you are using thelow-level Deno APIfor HTTP servers, usage of the reporter would look something like this:
import{createReporter}from"https://deno.land/x/g_a/mod.ts";constga=createReporter();forawait(constconnofDeno.listen({port:0})){(async()=>{consthttpConn=Deno.serveHttp(conn);forawait(constrequestEventofhttpConn){leterr;conststart=performance.now();try{// processing of the request...constresponse=newResponse(/* response details */);awaitrequestEvent.respondWith(response);}catch(e){err=e;}finally{awaitga(requestEvent.request,conn,response,start,err);}}})();}
If you are using thestd
library HTTP APIthen it would look something like this:
import{createReporter}from"https://deno.land/x/g_a/mod.ts";import{serve}from"https://deno.land/std/http/server.ts";importtype{ConnInfo}from"https://deno.land/std/http/server.ts";constga=createReporter();functionhandler(req:Request,conn:ConnInfo){leterr;letres:Response;conststart=performance.now();try{// processing of the request...res=newResponse(/* response details */);}catch(e){err=e;}finally{ga(req,conn,res!,start,err);}returnres!;}serve(handler);
If you are usingoak, thencreateReportMiddleware()
can be used to create a middleware which will do thejob:
import{createReportMiddleware}from"https://deno.land/x/g_a/mod.ts";import{Application}from"https://deno.land/x/oak/mod.ts";constga=createReportMiddleware();constapp=newApplication();app.use(ga);// register additional middleware...app.listen({port:0});
About
Utilities for server side processing of Google Analytics in Deno CLI and Deploy