最近專案剛好需要客製 dataLayer
而使用到的 next.js app router 框架需安裝套件完成事件追蹤
首先需要安裝 @next/third-parties
npm install @next/third-parties@latest next@latest
這邊使用到的版本為 "@next/third-parties": "^14.2.6",
接著照著官方文件引入 app/layout.tsx
// 引入 GoogleTagManager
import { GoogleTagManager } from '@next/third-parties/google'
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      // gtm-id 填上 gtm 給的 id
      <GoogleTagManager gtmId="GTM-XYZ" />
      <body>{children}</body>
    </html>
  )
}
接著使用它的方式官方文件建議這樣做
'use client' // 只能在 client 端使用
// 引入 sendGTMEvent
import { sendGTMEvent } from '@next/third-parties/google'
 
export function EventButton() {
  return (
    <div>
      <button
        // 事件推送方式
        onClick={() => sendGTMEvent('event', 'buttonClicked', { value: 'xyz' })}
      >
        Send Event
      </button>
    </div>
  )
}
我們的需求是訂單成立並且結完帳成功後才會推送事件
所以我將它寫成元件並在 'use server' 的 page 中引入
dataLayer 的資料如下
dataLayer.push({
  event: "purchase", // purchase 是事件名稱
  ecommerce: {
    transaction_id: "66C94FFF9F445", // If repeated, GA4 will not be written again.
    value: 300, // Tax included and shipping fee excluded
    shipping: 40,
    currency: "TWD",
    coupon: "", // Optional fields may be omitted or set to empty string.
    items: [
    {
      item_id: "66",
      item_name: "商品名稱",
      price: 300,
      quantity: 3
      item_families: "xxx",
    }]
  }
});
照理來說,我們需要將它改成下面方式做推送
sendGTMEvent('event', 'purchase', { ecommerce: {
    transaction_id: "66C94FFF9F445",
    value: 300,
    shipping: 40,
    currency: "TWD",
    coupon: "", 
    items: [
    {
      item_id: "66",
      item_name: "商品名稱",
      price: 300,
      quantity: 3
      item_families: "xxx",
    }]
  } 
})}
但是 ts 卻報錯
參考 ai、stackoverflow 或是 github 上的文件都沒能解決我的問題
後來剛好看到這篇文章
反向而行
將三個參數包成一個物件
sendGTMEvent({
      event: 'purchase', // 事件名稱改這樣寫
      ecommerce: {
        transaction_id: orderID, 
        value: detailData?.totals?.grand_total, 
        shipping: detailData?.totals?.shipping_rate,
        currency: 'TWD',
        coupon: detailData?.totals?.coupon_code ?? '', 
        items: GADatas, // 整理過後的 items
      },
    })

結果就成功ㄌ (WT ಠ_ಠ
這是最近遇到ㄉ問題
如果官方之後有做更新,會再將它們做調整