帶有 Nextjs 的強類型 GA4 第二部分 - 危險區
在本系列的第一部分中,在 Next v11 發布之前,我們介紹了使用 Nextjs 配置 GA4。
從那時起,Nextjs 推出了一個 next/script 組件,它為危險地轉義內部 html 提供了一種替代方法——在使用 vanilla 腳本標籤時,這是以前必要的邪惡。
獎勵:它的性能也更好
因此,不再需要危險地生活在 HTML 的世界中——除了語義,我們將移動我們在 _document.tsx
中配置的腳本標籤 在第一篇文章中到 _app.tsx
.
重要提示:腳本必須在 Next.js 頁面中的 Head (next/head) 標記上方實例化,並且絕不能與 next/document
中的 head 一起使用
這個語法上性感的實現可以按如下方式執行:
const Noop: FC = ({ children }) => <>{children}</>;
export default function NextApp({
Component,
pageProps
}: AppContext & AppInitialProps) {
const LayoutNoop = (Component as any).LayoutNoop || Noop;
const apolloClient = useApollo(pageProps);
useEffect(() => {
document.body.classList?.remove('loading');
}, []);
const router = useRouter();
useEffect(() => {
const handleRouteChange = (url: URL) => {
gtag.pageview(url);
};
router.events.on('routeChangeComplete', handleRouteChange);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events]);
return (
<>
<Script
async
strategy='lazyOnload'
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
/>
<Script strategy='afterInteractive'>
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`}
</Script>
<Head nextSeoProps={NextSEO} />
<ApolloProvider client={apolloClient}>
<AuthProvider>
<GoogleFacebookProvider>
<LayoutNoop pageProps={pageProps}>
<Component {...pageProps} />
</LayoutNoop>
</GoogleFacebookProvider>
</AuthProvider>
</ApolloProvider>
</>
);
}
對於那些對利用新的 <Script />
時可用的各種方法感到好奇的人 組件,您可以在這裡閱讀更多內容
在急切啟動開發或將這些更改部署到預覽/生產之前,請務必從 _document.tsx
的 Head 中刪除以下 XSS 蜜罐
// ...
<Head>
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());gtag('config',
'${GA_TRACKING_ID}', {
page: window.location.pathname
});
`
}}
/>
</Head>
// ...
實時指標報告?是的。
對於那些有興趣將實時指標發送到您的谷歌分析資產的人來說,您很幸運。在 _app.tsx
中的默認導出下方 ,包括以下功能,您將在不知不覺中在您的 GA4 儀表板中獲得實時指標
export function reportGAVitals({
id,
name,
label,
value
}: NextWebVitalsMetric) {
if (typeof window !== 'undefined')
window.gtag('event', name, {
event_category: label === 'web-vital' ? 'Web Vitals' : 'Next.js custom metric',
value: Math.round(name === 'CLS' ? value * 1000 : value), // values must be integers
event_label: id, // id unique to current page load
non_interaction: true // avoids affecting bounce rate.
} as Gtag.EventParams);
}
回想一下 Gtag.EventParams
從 @types/gtag.js
輸入 包在全球範圍內可供消費,需要 0 個導入——在根 index.d.ts
中配置 文件如下:
索引.d.ts
/// <reference types="gtag.js" />
declare module 'gtag.js';
我的 TypeScript 朋友們就到此為止,但期待更多強類型 Nextjs 文章的到來!對您希望看到 Next + TypeScript 涵蓋的主題的反饋將不勝感激——從 graphql-codegen 到 apollo config 到 api 路由,再到在無頭上下文中完美地鍵入回退設置為 true 的動態路由等等等等.
乾杯