Skip to content
This repository was archived by the owner on Dec 26, 2022. It is now read-only.

Commit 4afff0f

Browse files
committed
Save user uid
1 parent d3c19f5 commit 4afff0f

File tree

3 files changed

+26
-7
lines changed

3 files changed

+26
-7
lines changed

.env.example

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,5 @@ GA_UACODE=UA-XXXXXXXXX-X
44
# But dotenv-webpack plugin will replace it by string and parse by Terser will fail.
55
# NODE_DEBUG=request # debug requests in analytics
66
# DEBUG_PROD=true
7+
# FORCE_ENABLE_ANALYTICS=true
8+

src/services/gaService/GaService.ts

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,27 @@
1-
import ua from 'universal-analytics';
1+
import ua, { Visitor } from 'universal-analytics';
2+
import { v4 as uuid } from 'uuid';
23

3-
const isProd = process.env.NODE_ENV === 'production';
4+
const isEnabled =
5+
process.env.NODE_ENV === 'production' ||
6+
process.env.FORCE_ENABLE_ANALYTICS === 'true';
47

58
const gaCode = process.env.GA_UACODE;
6-
let analytics: any | null = null;
79

8-
if (isProd && gaCode) {
9-
analytics = ua(gaCode);
10+
let analytics: Visitor | null = null;
11+
12+
if (isEnabled && gaCode) {
13+
let uid = window.localStorage.getItem('uid');
14+
15+
if (!uid) {
16+
uid = uuid();
17+
window.localStorage.setItem('uid', uid);
18+
}
19+
20+
analytics = ua(gaCode, uid);
1021
}
1122

1223
const executeOnCondition = (fn: () => void) => {
13-
if (isProd && analytics) {
24+
if (isEnabled && analytics) {
1425
fn();
1526
}
1627
};

src/types/Types.d.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
declare module 'universal-analytics' {
2-
const ua: (code: string) => any;
2+
export interface Visitor {
3+
pageview(path: string): Visitor;
4+
event(category: string, action: string): Visitor;
5+
send(): void;
6+
}
7+
8+
const ua: (code: string, uid?: string) => Visitor;
39

410
export default ua;
511
}

0 commit comments

Comments
 (0)