NextJS 从 api 路由调用 gtag(“event”)

发布于 2025-01-10 05:42:55 字数 468 浏览 2 评论 0原文

我想在打开 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深海夜未眠 2025-01-17 05:42:55

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文