Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
151
rated 0 times [  155] [ 4]  / answers: 1 / hits: 93605  / 4 Years ago, wed, february 26, 2020, 12:00:00

I'm using styled-components with next.js so my styles need to be server-side rendered, hence how can I add google analytics to my website?



I checked next.js google analytics example but as I said my _document file is different because of using styled-components.



// _document.js

import React from 'react'
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'

class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage

try {
ctx.renderPage = () => originalRenderPage({
enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
})

const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
}
} finally {
sheet.seal()
}
}
}

export default MyDocument


More From » reactjs

 Answers
3

Next.js since v11 recommends using their <Script> tag, and the right place to add it is the App component.


pages/_app.jsx


import React from 'react';
import Script from 'next/script';

const App = ({ Component, pageProps }) => {
return (
<>
<Script
src="https://www.googletagmanager.com/gtag/js?id=G-xxxxxxxxxx"
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){window.dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'G-xxxxxxxxxx');
`}
</Script>

<Component {...pageProps} />
</>
);
};

export default App;

You can see this solution working in nestjs-starter where I'm also setting the tag from an env var.


For v10 and lower use regular <script> tags according to Google's guide.


Keep in mind that Google Analytics does automatic page tracking, but this will not work for every use case. For example, hash and search parameter changes are not tracked. This can lead to a lot of confusion. For example, when using HashRouter or anchor links the navigation will not be tracked. To have full control over page view tracking you can disable automatic tracking. See for a detailed explanation: The Ultimate Guide to Google Analytics (UA & GA4) on React (Or Anything Else


Manual page tracking: https://stackoverflow.com/a/63249329/2771889


[#51173] Monday, February 17, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
willieelisham

Total Points: 201
Total Questions: 108
Total Answers: 106

Location: Zambia
Member since Sat, Oct 31, 2020
4 Years ago
willieelisham questions
Wed, Apr 14, 21, 00:00, 3 Years ago
Wed, Mar 31, 21, 00:00, 3 Years ago
Sun, Oct 11, 20, 00:00, 4 Years ago
Sat, May 9, 20, 00:00, 4 Years ago
;