NextJS 从 api 路由调用 gtag(“event”)
我想在打开 api 路由时在 Google Analytics 上记录一个事件。
目前我的 gtag 实现如下:
export const logEvent = ({ action, category, label, value }: LogEventProps) => {
(window as any).gtag("event", action, {
event_category: category,
event_label: label,
value: value,
});
};
问题是它依赖于一个要触发日志的窗口,这是未定义的,这是可以理解的,每当我从 api
路由调用此方法时。
我找不到有关如何从服务器端记录事件的任何有价值的信息。
解决方法可能是将 api 重定向到记录事件的空白页面,但我不喜欢这个想法,并且想知道是否有更好的方法。
I'd like to log an event on Google Analytics when an api route is opened.
My gtag implementation is as follows at the moment:
export const logEvent = ({ action, category, label, value }: LogEventProps) => {
(window as any).gtag("event", action, {
event_category: category,
event_label: label,
value: value,
});
};
Problem is that it relies on a window for logs to be fired, which is undefined, understandably so, whenever I'm calling this method from an api
route.
I couldn't find any valuable information on how to log an event from the server side.
A work-around might be to have the api redirect to a blank page that logs the event, but I don't love the idea and wonder if there's a better approach.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
window关键字(Variable)仅在客户端可用。您不能在服务器端使用窗口变量。 Windows 变量取决于浏览器的信息。同时,gtag将他的信息保存在window变量中
The window keyword(Variable) is only available on the client side. you can't use window variables on the server side. Windows variables depend on the browser's information. meanwhile, gtag saved his information in window variable