Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

fix(analytics): address review feedback on GA4 migration

Matt Robertsf6632e90697c
diff --git a/app/cmd/server.go b/app/cmd/server.go
index 4ccaa6b8a..657fe6b70 100644
--- a/app/cmd/server.go
+++ b/app/cmd/server.go
@@ -46,7 +46,7 @@ func RunServer() int {
})
}
- if strings.HasPrefix(env.Config.GoogleAnalytics, "UA-") {
+ if strings.HasPrefix(strings.ToUpper(env.Config.GoogleAnalytics), "UA-") {
log.Warn(ctx, "GOOGLE_ANALYTICS is set to a Universal Analytics ID, which Google no longer supports. Replace it with a Google Analytics 4 Measurement ID (G-XXXXXXXXXX).")
}
diff --git a/app/middlewares/security.go b/app/middlewares/security.go
index c85caeae7..2a660c2c3 100644
--- a/app/middlewares/security.go
+++ b/app/middlewares/security.go
@@ -22,7 +22,11 @@ func Secure() web.MiddlewareFunc {
}
cdnHost = " " + cdnHost
}
- csp := fmt.Sprintf(web.CspPolicyTemplate, c.ContextID(), cdnHost)
+ analyticsScript, analyticsConnect := "", ""
+ if env.Config.GoogleAnalytics != "" {
+ analyticsScript, analyticsConnect = web.CspGoogleAnalyticsScript, web.CspGoogleAnalyticsConnect
+ }
+ csp := fmt.Sprintf(web.CspPolicyTemplate, c.ContextID(), cdnHost, analyticsScript, analyticsConnect)
c.Response.Header().Set("Content-Security-Policy", strings.TrimSpace(csp))
c.Response.Header().Set("X-XSS-Protection", "1; mode=block")
diff --git a/app/middlewares/security_test.go b/app/middlewares/security_test.go
index abd857fde..3a8f6da85 100644
--- a/app/middlewares/security_test.go
+++ b/app/middlewares/security_test.go
@@ -24,7 +24,7 @@ func TestSecureWithoutCDN(t *testing.T) {
return c.NoContent(http.StatusOK)
})
- expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'nonce-" + ctxID + "' https://www.googletagmanager.com; img-src 'self' https: data:; font-src 'self' data:; object-src 'none'; media-src 'none'; connect-src 'self' https://www.googletagmanager.com https://*.google-analytics.com https://*.analytics.google.com; frame-src 'self'"
+ expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'nonce-" + ctxID + "'; img-src 'self' https: data:; font-src 'self' data:; object-src 'none'; media-src 'none'; connect-src 'self'; frame-src 'self'"
Expect(status).Equals(http.StatusOK)
Expect(response.Header().Get("Content-Security-Policy")).Equals(expectedPolicy)
@@ -47,7 +47,7 @@ func TestSecureWithCDN(t *testing.T) {
return c.NoContent(http.StatusOK)
})
- expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline' *.test.fider.io; script-src 'self' 'nonce-" + ctxID + "' https://www.googletagmanager.com *.test.fider.io; img-src 'self' https: data: *.test.fider.io; font-src 'self' data: *.test.fider.io; object-src 'none'; media-src 'none'; connect-src 'self' https://www.googletagmanager.com https://*.google-analytics.com https://*.analytics.google.com *.test.fider.io; frame-src 'self'"
+ expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline' *.test.fider.io; script-src 'self' 'nonce-" + ctxID + "' *.test.fider.io; img-src 'self' https: data: *.test.fider.io; font-src 'self' data: *.test.fider.io; object-src 'none'; media-src 'none'; connect-src 'self' *.test.fider.io; frame-src 'self'"
Expect(status).Equals(http.StatusOK)
Expect(response.Header().Get("Content-Security-Policy")).Equals(expectedPolicy)
@@ -70,7 +70,7 @@ func TestSecureWithCDN_SingleHost(t *testing.T) {
return c.NoContent(http.StatusOK)
})
- expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline' test.fider.io; script-src 'self' 'nonce-" + ctxID + "' https://www.googletagmanager.com test.fider.io; img-src 'self' https: data: test.fider.io; font-src 'self' data: test.fider.io; object-src 'none'; media-src 'none'; connect-src 'self' https://www.googletagmanager.com https://*.google-analytics.com https://*.analytics.google.com test.fider.io; frame-src 'self'"
+ expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline' test.fider.io; script-src 'self' 'nonce-" + ctxID + "' test.fider.io; img-src 'self' https: data: test.fider.io; font-src 'self' data: test.fider.io; object-src 'none'; media-src 'none'; connect-src 'self' test.fider.io; frame-src 'self'"
Expect(status).Equals(http.StatusOK)
Expect(response.Header().Get("Content-Security-Policy")).Equals(expectedPolicy)
@@ -79,6 +79,26 @@ func TestSecureWithCDN_SingleHost(t *testing.T) {
Expect(response.Header().Get("Referrer-Policy")).Equals("no-referrer-when-downgrade")
}
+func TestSecureWithGoogleAnalytics(t *testing.T) {
+ RegisterT(t)
+
+ env.Config.GoogleAnalytics = "G-TEST123"
+
+ server := mock.NewServer()
+ server.Use(middlewares.Secure())
+
+ var ctxID string
+ status, response := server.Execute(func(c *web.Context) error {
+ ctxID = c.ContextID()
+ return c.NoContent(http.StatusOK)
+ })
+
+ expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'nonce-" + ctxID + "' https://www.googletagmanager.com; img-src 'self' https: data:; font-src 'self' data:; object-src 'none'; media-src 'none'; connect-src 'self' https://www.googletagmanager.com https://*.google-analytics.com https://*.google.com https://*.g.doubleclick.net https://pagead2.googlesyndication.com; frame-src 'self'"
+
+ Expect(status).Equals(http.StatusOK)
+ Expect(response.Header().Get("Content-Security-Policy")).Equals(expectedPolicy)
+}
+
func executeCSRF(method, url string, headers map[string]string) int {
server := mock.NewServer().WithURL(url)
server.Use(func(next web.HandlerFunc) web.HandlerFunc {
diff --git a/app/pkg/env/env.go b/app/pkg/env/env.go
index 39b113ed4..2c968a983 100644
--- a/app/pkg/env/env.go
+++ b/app/pkg/env/env.go
@@ -167,6 +167,8 @@ func Reload() {
panic(errors.Wrap(err, "failed to parse environment variables"))
}
+ Config.GoogleAnalytics = strings.TrimSpace(Config.GoogleAnalytics)
+
if IsSingleHostMode() {
if Config.HostDomain != "" {
panic("HOST_DOMAIN environment variable has been replaced by BASE_URL. Set it to your site base url, e.g: https://feedback.mysite.com")
diff --git a/app/pkg/web/engine.go b/app/pkg/web/engine.go
index 7c5190a0c..622949fef 100644
--- a/app/pkg/web/engine.go
+++ b/app/pkg/web/engine.go
@@ -28,15 +28,20 @@ var (
cspBase = "base-uri 'self'"
cspDefault = "default-src 'self'"
cspStyle = "style-src 'self' 'unsafe-inline'%[2]s"
- cspScript = "script-src 'self' 'nonce-%[1]s' https://www.googletagmanager.com%[2]s"
+ cspScript = "script-src 'self' 'nonce-%[1]s'%[3]s%[2]s"
cspFont = "font-src 'self' data:%[2]s"
cspImage = "img-src 'self' https: data:%[2]s"
cspObject = "object-src 'none'"
cspFrame = "frame-src 'self'"
cspMedia = "media-src 'none'"
- cspConnect = "connect-src 'self' https://www.googletagmanager.com https://*.google-analytics.com https://*.analytics.google.com%[2]s"
+ cspConnect = "connect-src 'self'%[4]s%[2]s"
+
+ // Google Analytics hosts are only allowed when GOOGLE_ANALYTICS is set (https://developers.google.com/tag-platform/security/guides/csp)
+ CspGoogleAnalyticsScript = " https://www.googletagmanager.com"
+ CspGoogleAnalyticsConnect = " https://www.googletagmanager.com https://*.google-analytics.com https://*.google.com https://*.g.doubleclick.net https://pagead2.googlesyndication.com"
//CspPolicyTemplate is the template used to generate the policy
+ //Args: 1 = nonce, 2 = CDN host, 3 = analytics script hosts, 4 = analytics connect hosts
CspPolicyTemplate = fmt.Sprintf("%s; %s; %s; %s; %s; %s; %s; %s; %s; %s", cspBase, cspDefault, cspStyle, cspScript, cspImage, cspFont, cspObject, cspMedia, cspConnect, cspFrame)
)
diff --git a/app/pkg/web/renderer.go b/app/pkg/web/renderer.go
index a5a6e5c58..f90a4f6d2 100644
--- a/app/pkg/web/renderer.go
+++ b/app/pkg/web/renderer.go
@@ -200,7 +200,6 @@ func (r *Renderer) Render(w io.Writer, statusCode int, props Props, ctx *Context
public["page"] = props.Page
public["contextID"] = ctx.ContextID()
- public["sessionID"] = ctx.SessionID()
public["tenant"] = tenant
public["props"] = props.Data
public["settings"] = &Map{
diff --git a/app/pkg/web/testdata/basic.html b/app/pkg/web/testdata/basic.html
index f55626681..347338845 100755
--- a/app/pkg/web/testdata/basic.html
+++ b/app/pkg/web/testdata/basic.html
@@ -45,7 +45,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","page":"","props":{},"sessionID":"","settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true,"version":"dev"},"tenant":null,"title":"Fider"}
+ {"contextID":"CONTEXT_ID","page":"","props":{},"settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true,"version":"dev"},"tenant":null,"title":"Fider"}
</script>
diff --git a/app/pkg/web/testdata/canonical.html b/app/pkg/web/testdata/canonical.html
index ea314bed7..f933551b2 100755
--- a/app/pkg/web/testdata/canonical.html
+++ b/app/pkg/web/testdata/canonical.html
@@ -47,7 +47,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","page":"","props":{},"sessionID":"","settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true,"version":"dev"},"tenant":null,"title":"Fider"}
+ {"contextID":"CONTEXT_ID","page":"","props":{},"settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true,"version":"dev"},"tenant":null,"title":"Fider"}
</script>
diff --git a/app/pkg/web/testdata/chunk.html b/app/pkg/web/testdata/chunk.html
index 11bfee86d..eddd0046d 100644
--- a/app/pkg/web/testdata/chunk.html
+++ b/app/pkg/web/testdata/chunk.html
@@ -45,7 +45,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","page":"Test.page","props":{},"sessionID":"","settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true,"version":"dev"},"tenant":null,"title":"Fider"}
+ {"contextID":"CONTEXT_ID","page":"Test.page","props":{},"settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true,"version":"dev"},"tenant":null,"title":"Fider"}
</script>
diff --git a/app/pkg/web/testdata/home.html b/app/pkg/web/testdata/home.html
index b103648be..880678692 100755
--- a/app/pkg/web/testdata/home.html
+++ b/app/pkg/web/testdata/home.html
@@ -45,7 +45,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","description":"My Page Description","page":"","props":{"countPerStatus":{},"posts":[],"tags":[]},"sessionID":"","settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true,"version":"dev"},"tenant":null,"title":"My Page Title · Fider"}
+ {"contextID":"CONTEXT_ID","description":"My Page Description","page":"","props":{"countPerStatus":{},"posts":[],"tags":[]},"settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true,"version":"dev"},"tenant":null,"title":"My Page Title · Fider"}
</script>
diff --git a/app/pkg/web/testdata/home_ssr.html b/app/pkg/web/testdata/home_ssr.html
index a39ae8b69..5a1688d35 100755
--- a/app/pkg/web/testdata/home_ssr.html
+++ b/app/pkg/web/testdata/home_ssr.html
@@ -45,7 +45,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","description":"My Page Description","page":"Test.page","props":{"countPerStatus":{},"posts":[],"tags":[]},"sessionID":"","settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true,"version":"dev"},"tenant":{"id":0,"name":"","subdomain":"","invitation":"","welcomeMessage":"","welcomeHeader":"","descriptionTemplate":"","cname":"","status":0,"locale":"en","isPrivate":false,"logoBlobKey":"","allowedSchemes":"","isEmailAuthAllowed":false,"isFeedEnabled":false,"preventIndexing":false,"isModerationEnabled":false,"isPro":false},"title":"My Page Title · "}
+ {"contextID":"CONTEXT_ID","description":"My Page Description","page":"Test.page","props":{"countPerStatus":{},"posts":[],"tags":[]},"settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true,"version":"dev"},"tenant":{"id":0,"name":"","subdomain":"","invitation":"","welcomeMessage":"","welcomeHeader":"","descriptionTemplate":"","cname":"","status":0,"locale":"en","isPrivate":false,"logoBlobKey":"","allowedSchemes":"","isEmailAuthAllowed":false,"isFeedEnabled":false,"preventIndexing":false,"isModerationEnabled":false,"isPro":false},"title":"My Page Title · "}
</script>
diff --git a/app/pkg/web/testdata/oauth.html b/app/pkg/web/testdata/oauth.html
index 7a91aff91..4c5b374a5 100755
--- a/app/pkg/web/testdata/oauth.html
+++ b/app/pkg/web/testdata/oauth.html
@@ -45,7 +45,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","page":"","props":{},"sessionID":"","settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[{"provider":"google","displayName":"Google","clientID":"1234","url":"https://demo.test.fider.io:3000/oauth/google","callbackURL":"https://demo.test.fider.io:3000/oauth/google/callback","logoBlobKey":"google.png","isCustomProvider":false,"isEnabled":true}],"postWithTags":true,"version":"dev"},"tenant":null,"title":"Fider"}
+ {"contextID":"CONTEXT_ID","page":"","props":{},"settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[{"provider":"google","displayName":"Google","clientID":"1234","url":"https://demo.test.fider.io:3000/oauth/google","callbackURL":"https://demo.test.fider.io:3000/oauth/google/callback","logoBlobKey":"google.png","isCustomProvider":false,"isEnabled":true}],"postWithTags":true,"version":"dev"},"tenant":null,"title":"Fider"}
</script>
diff --git a/app/pkg/web/testdata/tenant.html b/app/pkg/web/testdata/tenant.html
index a8aa1b515..9f0b82c41 100755
--- a/app/pkg/web/testdata/tenant.html
+++ b/app/pkg/web/testdata/tenant.html
@@ -45,7 +45,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","page":"","props":{},"sessionID":"","settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true,"version":"dev"},"tenant":{"id":0,"name":"Game of Thrones","subdomain":"","invitation":"","welcomeMessage":"","welcomeHeader":"","descriptionTemplate":"","cname":"","status":0,"locale":"","isPrivate":false,"logoBlobKey":"","allowedSchemes":"","isEmailAuthAllowed":false,"isFeedEnabled":false,"preventIndexing":false,"isModerationEnabled":false,"isPro":false},"title":"Game of Thrones"}
+ {"contextID":"CONTEXT_ID","page":"","props":{},"settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true,"version":"dev"},"tenant":{"id":0,"name":"Game of Thrones","subdomain":"","invitation":"","welcomeMessage":"","welcomeHeader":"","descriptionTemplate":"","cname":"","status":0,"locale":"","isPrivate":false,"logoBlobKey":"","allowedSchemes":"","isEmailAuthAllowed":false,"isFeedEnabled":false,"preventIndexing":false,"isModerationEnabled":false,"isPro":false},"title":"Game of Thrones"}
</script>
diff --git a/app/pkg/web/testdata/user.html b/app/pkg/web/testdata/user.html
index 6b49456c3..c1b946896 100755
--- a/app/pkg/web/testdata/user.html
+++ b/app/pkg/web/testdata/user.html
@@ -45,7 +45,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","description":"My Page Description","page":"","props":{},"sessionID":"","settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true,"version":"dev"},"tenant":null,"title":"My Page Title · Fider","user":{"avatarBlobKey":"","avatarType":"gravatar","avatarURL":"https://demo.test.fider.io:3000/static/avatars/gravatar/5/Jon%20Snow","email":"[email protected]","id":5,"isAdministrator":true,"isCollaborator":true,"isTrusted":false,"name":"Jon Snow","role":"administrator","status":"active"}}
+ {"contextID":"CONTEXT_ID","description":"My Page Description","page":"","props":{},"settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true,"version":"dev"},"tenant":null,"title":"My Page Title · Fider","user":{"avatarBlobKey":"","avatarType":"gravatar","avatarURL":"https://demo.test.fider.io:3000/static/avatars/gravatar/5/Jon%20Snow","email":"[email protected]","id":5,"isAdministrator":true,"isCollaborator":true,"isTrusted":false,"name":"Jon Snow","role":"administrator","status":"active"}}
</script>
diff --git a/public/services/analytics.spec.ts b/public/services/analytics.spec.ts
new file mode 100644
index 000000000..b790632c3
--- /dev/null
+++ b/public/services/analytics.spec.ts
@@ -0,0 +1,43 @@
+import { analytics, toEventName } from "./analytics"
+
+test("toEventName joins category and action with an underscore", () => {
+ expect(toEventName("post", "vote")).toBe("post_vote")
+ expect(toEventName("comment", "approve-and-verify")).toBe("comment_approve_and_verify")
+})
+
+test("toEventName replaces characters GA4 does not allow", () => {
+ expect(toEventName("post", "approve and verify")).toBe("post_approve_and_verify")
+ expect(toEventName("tag", "import.csv")).toBe("tag_import_csv")
+})
+
+test("toEventName truncates to 40 characters", () => {
+ const name = toEventName("category", "a-very-long-action-name-that-keeps-on-going")
+ expect(name).toHaveLength(40)
+ expect(name).toMatch(/^[A-Za-z0-9_]+$/)
+})
+
+describe("analytics", () => {
+ afterEach(() => {
+ delete window.gtag
+ })
+
+ test("does nothing when gtag is not loaded", () => {
+ expect(() => analytics.event("post", "vote")).not.toThrow()
+ expect(() => analytics.error(new Error("boom"))).not.toThrow()
+ })
+
+ test("sends events to gtag", () => {
+ window.gtag = jest.fn()
+ analytics.event("post", "toggle-vote")
+ expect(window.gtag).toHaveBeenCalledWith("event", "post_toggle_vote", { event_category: "post" })
+ })
+
+ test("sends errors as exception events with the error message", () => {
+ window.gtag = jest.fn()
+ analytics.error(new TypeError("Cannot read properties of undefined"))
+ expect(window.gtag).toHaveBeenCalledWith("event", "exception", {
+ description: "TypeError: Cannot read properties of undefined",
+ fatal: false,
+ })
+ })
+})
diff --git a/public/services/analytics.ts b/public/services/analytics.ts
index b64dfc46c..848980c34 100644
--- a/public/services/analytics.ts
+++ b/public/services/analytics.ts
@@ -1,16 +1,20 @@
+// GA4 event names may only contain letters, numbers and underscores, and are limited to 40 characters
+export const toEventName = (eventCategory: string, eventAction: string): string =>
+ `${eventCategory}_${eventAction}`.replace(/[^A-Za-z0-9_]/g, "_").substring(0, 40)
+
export const analytics = {
event: (eventCategory: string, eventAction: string): void => {
if (window.gtag) {
- // GA4 event names may only contain letters, numbers and underscores
- window.gtag("event", `${eventCategory}_${eventAction}`.replace(/-/g, "_"), {
+ window.gtag("event", toEventName(eventCategory, eventAction), {
event_category: eventCategory,
})
}
},
error: (err?: Error): void => {
if (window.gtag) {
+ // GA4 truncates parameter values to 100 characters, so a stack trace would be cut off after its first line
window.gtag("event", "exception", {
- description: err ? err.stack : "<not available>",
+ description: err ? `${err.name}: ${err.message}` : "<not available>",
fatal: false,
})
}