이전 포스트: https://heo-seongil.tistory.com/140?category=970023
이전 포스트에서 언급했듯이 Google Analytics의 기존 버전은 2023년 상반기에 종료되고 새로운 버전으로 업데이트해야된다고 한다.
다시 연결 해보겠다. 이전에 만들었던 속성을 보니 GA4 설정 어시스턴트가 메뉴가 있었다. 여기 "GA4 속성 만들기", "속성 연결하기"가 있었다. 살펴보니 내 속성 중 동일한 이름으로 GA4라고 적혀있는 메뉴가 있어서 선택해서 연결해주었다.
이 상태로 트래픽 데이터가 수집되는지 확인해보았지만 당연히 연결되지 않았다.
npm react-ga4를 참고하여 서버에 설치를 진행했다.
react-ga4: https://www.npmjs.com/package/react-ga4
새로운 npm 패키지를 설치해야한다. 기존에는 react-ga였지만 react-ga4를 설치한다. 여기서 i는 install과 완전히 똑같은 것이다.
$ npm i react-ga4
아래 두개의 사진은 순서대로 react-ga와 react-ga4의 메뉴얼이다.
살펴보니 기존에는 pageview 이벤트를 send("pageview")로 전달하는 것으로 판단된다. 이에 관한 자세한 공식 메뉴얼을 찾아보니 아래와 같이 설명되어 있다. (참고자료 > UA vs GA4, 참고하세요) 기존에는 속성에서 hit type이 종류별로 있었지만 이제는 모든 hit type이 Event로 통합되었다. 기존에는 위의 그림처럼 location을 파라미터로 전달해주었는데 새로운 버전에는 필요 없어 보인다.
기존의 코드를 아래와 같이 수정했다.
// Project > src > index.js
...
// import ReactGA from 'react-ga'; // UA
import ReactGA from 'react-ga4'; // GA4
// ReactGA.initialize("UA-XXXXXXXXX-X"); //old
ReactGA.initialize("G-XXXXXXXXXX"); //new
ReactDOM.render(
...
//// Project > src > components > RouterChangeTracker
import React from 'react'
import { withRouter } from 'react-router-dom';
// import ReactGA from 'react-ga'; // old
import ReactGA from 'react-ga4'; // new
const RouteChangeTracker = ({ history }) => {
history.listen((location, action) => {
// ReactGA.pageview(location.pathname); // old
ReactGA.send("pageview"); //new
});
return <div></div>;
};
export default withRouter(RouteChangeTracker);
new로 수정하고 다시 빌드하면 정상적으로 연결된 것을 확인할 수 있다.
$ npm run build
하지만 아래 사진에서 보듯이 페이지별 트래픽을 확인할 수 없다... 인줄 알았는데 (아래 이어서..)
위의 그림에서 page_view를 누르면 아래 그림에서 우측 하단과 같이 이벤트의 매개변수 키가 나온다.
그래서 매개변수 키를 선택하면 각자 값이 나온다.
이전 버전에서는 아래 처럼 보기 쉽게 잘 되어있었는데 새로운 버전이 아직 정상이 아닌 것 같다.. 태그를 이용해서도 해보았지만
똑같은 결과였다. 한 번 수정해보아야겠다.
원래는 아래 그림에서 페이지 제목 및 화면 이름 별 조회수가 정상적으로 나와야 되는데 페이지 제목은 PnP로 설정해놔서 변경이 되지 않는다. 리액트의 특징 때문에 어쩔 수 없다. 그래서 react-ga4 패키지의 코드를 확인해보았다.
Project > node_modules > react-ga4 > src > ga4.js의 코드를 보면 send 함수가 아래처럼 정의되어 있다.
// Project > node_modules > react-ga4 > src > ga4.js (line 478~480)
send = (fieldObject) => {
this._gaCommand("send", fieldObject);
};
_gaCommand를 호출하고 _gaCommandSend를 호출하고 _gaCommandSendPageview를 호출해서 실행된다.
// Project > node_modules > react-ga4 > src > ga4.js (line 352~363)
_gaCommand = (command, ...args) => {
switch (command) {
case "send":
this._gaCommandSend(...args);
break;
case "set":
this._gaCommandSet(...args);
break;
default:
console.warn(`Command doesn't exist: ${command}`);
}
};
// Project > node_modules > react-ga4 > src > ga4.js (line 319~343)
_gaCommandSend = (...args) => {
const hitType = typeof args[0] === "string" ? args[0] : args[0].hitType;
switch (hitType) {
case "event":
this._gaCommandSendEventParameters(...args);
break;
case "pageview":
this._gaCommandSendPageviewParameters(...args);
break;
case "timing":
this._gaCommandSendTiming(...args.slice(1));
break;
case "screenview":
case "transaction":
case "item":
case "social":
case "exception":
console.warn(`Unsupported send command: ${hitType}`);
break;
default:
console.warn(`Send command doesn't exist: ${hitType}`);
}
};
// Project > node_modules > react-ga4 > src > ga4.js (line 305~317)
_gaCommandSendPageviewParameters = (...args) => {
if (typeof args[0] === "string") {
this._gaCommandSendPageview(...args.slice(1));
} else {
const {
page,
// eslint-disable-next-line no-unused-vars
hitType,
...rest
} = args[0];
this._gaCommandSendPageview(page, rest);
}
};
// Project > node_modules > react-ga4 > src > ga4.js (line 288~303)
_gaCommandSendPageview = (page, fieldsObject) => {
if (fieldsObject && Object.keys(fieldsObject).length) {
const { title, location, ...rest } = this._toGtagOptions(fieldsObject);
console.log(title,location,res);
this._gtag("event", "page_view", {
...(page && { page_path: page }),
...(title && { page_title: title }),
...(location && { page_location: location }),
...rest,
});
} else if (page) {
this._gtag("event", "page_view", { page_path: page });
} else {
this._gtag("event", "page_view");
}
};
쭉 코드를 보면 path, title, location, rest가 있다. 실제 매개변수 중 page_path, page_title, page_loaction으로 나머지 매개변수는 실제 이름과 동일하게 작성해야 한다. 그래서 이전에 만들어둔 componetn인 RouteChangeTraker를 아래와 같이 작성해서 실행보니 정상적으로 페이지 별 사용자 트래픽을 확인할 수 있었다.
Project > src > components > RouteChangeTracker.js
import React from 'react'
import { withRouter } from 'react-router-dom';
import ReactGA4 from 'react-ga4';
import gtag from 'react-ga4/src/gtag';
const RouteChangeTracker = ({ history }) => {
history.listen((location, action) => {
ReactGA4.send({hitType: "pageview", path: location.pathname, location: location.pathname, title: location.pathname}); //new
//ReactGA4.send({hitType: "pageview", path: location.pathname, location: location.pathname, title: location.pathname, page_referrer: "(self)"});
});
return <div></div>;
};
export default withRouter(RouteChangeTracker);
주석으로 표시해둔 것 처럼 작성하면 page_referrer의 데이터를 지정할 수 있다. 다른 위에서 언급한 세개의 매개변수를 제외하면 모두 적용시킬 수 있을 것 같다.
그래도 첫 사용자 소스가 아직 확인 안된다. direct, Referral, Search등 어디에서 유입됐는지에 관한 정보는 중요하기 때문에 이걸 다시 수정해야되는 날이 오면 확인봐야겠다. 시간지나니깐 잘 된다. ㅎㅎ
참고자료
차세대 Google: https://support.google.com/analytics/answer/10089681?hl=ko&ref_topic=9143232
npm-react-ga: https://www.npmjs.com/package/react-ga
npm-react-ga4: https://www.npmjs.com/package/react-ga4
UA vs GA4: https://support.google.com/analytics/answer/9964640?hl=en#zippy=%2Cin-this-article
파인데이터랩: https://finedata.tistory.com/19
'PnP' 카테고리의 다른 글
hufspnp.com 웹 배포 - 2 (google analytics UA) (0) | 2022.03.28 |
---|---|
hufspnp.com 웹 배포 -1 (nginx & react & https & certbot) (0) | 2022.03.26 |