In cloudscribe.Web.Common, we have 2 useful things that make it easier to track page views and events in google analytics.
- Second we have a GoogleAnalyticsGA4Helper that makes it easy to add analytics events from server side code that will then be detected by the taghelper and rendered into the page.
Using the GoogleAnalyticsTagHelper
Assuming you have already installed the cloudscribe.Web.Common NuGet package, you also need to make sure you have declared the taghelper in your _ViewImports.cshtml like this:
@addTagHelper *, cloudscribe.Web.Common
Then you can add the taghelper into your Layout.cshtml file so that it will be on every page in your site. It should go in the head section just before the closing head tag. You must pass in your google analytics profile id and you can optionally also pass in a user id in cases where you have an authenticated user and a user id is available. In cloudscribe Core we pass in both values like this:
<google-analytics profile-id="@Tenant.GoogleAnalyticsProfileId" user-id="@User.GetUserId()"></google-analytics>
If you are not using cloudscribe Core you can hard code the profile id and leave out the user id unless you have another way to get it.
Note that the google-analytics taghelper (in UA mode) had some settings that used to work in tandem with the cookie-consent taghelper.
Note: The new GA4 uses first party cookies now instead of third party cookies. The tag helper in GA4 mode does not interact with the cookie-consent taghelper.
Using the GoogleAnalyticsGA4Helper
The GoogleAnalyticsGA4Helper is wired up for dependency injection so you can simply add it to the constructor signature of a controller or service class and it will be injected.
Consider this code example for tracking "Login Submit" events where _analyticsGA4Helper is the GoogleAnalyticsGA4Helper injected into our service.
var source = "OnSite" var e = new GoogleAnalyticsGA4Event(); e.Name = "login-failed"; e.Parameters.Add(new KeyValuePair<string, string>("method", source)); e.Parameters.Add(new KeyValuePair<string, string>("reason", "Login not allowed")); _analyticsGA4Helper.AddEvent(e);
Ecommerce Transaction Tracking
Currently, ecommerce tracking is not implemented in the new GoogleAnalyticsGA4Helper, or in the Tag Helper.
In cloudscribe Core we have a AccountAnalytics service that tracks events such as Login Submit, Login Fail, Login Success, Register Submit, Register Fail, Register Success etc. Internally it uses both the GoogleAnalyticsHelper and the GoogleAnalyticsGA4Helper (depending on if the Tag Helper is in UA or Gtag mode). You can easily create your own services to encapsulate various kinds of events that you want to track.
In summary, the GoogleAnalyticsTagHelper is all you need for basic standard page view tracking. For easy tracking of events that happen on the server you can use the GoogleAnalyticsGA4Helper.