New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adding GA script tag? #160
Comments
checkout |
@robinvdvleuten I'd suggest creating a GoogleTagManager component and including it in the Head or right after it depending on your implementation choice. |
as people mentioned you can use the |
Any tips on getting react-ga working with next.js? |
@gtramontina it should work. Otherwise I'm one of the |
No need for
|
I would recommend a better solution to track client side page view: autotrack. See MoOx/phenomic#384 for more information. |
@impronunciable it would be great to have an example as after some googling I'm still confused 😃 Could this be reopened?
The page tracking should work both when the page is server-rendered and then when navigating to another page. It would be would be great to see how the whole thing should integrate in a typical Next app with a Head, a page layout HOC, etc. Would also be great to know if you think there's a better/simpler/less cumbersome/more state-of-the-art combination than Next.js + Google Analytics Autotrack... |
I can investigate this
…On Tue, Jan 17, 2017, 7:59 AM Sébastien Dubois ***@***.***> wrote:
@impronunciable <https://github.com/impronunciable> it would be great to
have an example as after some googling I'm still confused 😃 Could this
be reopened?
- @MoOx <https://github.com/MoOx> seems to imply that react-ga isn't
necessary, should use Google AutoTrack
<https://github.com/googleanalytics/autotrack> instead
- but Autotrack instructs to create a script tag with code which
accesses the window object, so that doesn't work server-side
- and anyway if using a react component such as react-ga, where should
it be put? In a render? componentWillMount? getInitialProps? It's not
super clear as it kind of supposes that you use react-router and load the
code a single time for all pages.
The page tracking should work both when the page is server-rendered and
then when navigating to another page. It would be would be great to see how
the whole thing should integrate in a typical Next app with a Head, a page
layout HOC, etc.
Would also be great to know if you think there's a better/simpler/less
cumbersome/more state-of-the-art combination than Next.js + Google
Analytics Autotrack...
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#160 (comment)>, or mute
the thread
<https://github.com/notifications/unsubscribe-auth/AAKHp9-2bfLXj2hMGlNlkqUSRqEL7R2Cks5rTJ8kgaJpZM4KkXxa>
.
|
Pretty sure autotrack is more than enough, only injected on the client side - no need to think about the server-side. |
See MoOx/react-toulouse@c42045d for an example. It's not using next, but I guess it should be easy to adapt. |
Yeah we don't want to track server renders, Since it Will obfuscate things like location. |
No you don't since it will be handled by the client: keep in mind that a page is request by the client and will be rendered in the client browser :) |
OK I didn't realise the code shouln't run server-side. So I used autotrack as recommended by @MoOx, I think this should work: sedubois/relate@50dc3f3 Just haven't confirmed yet if it counts page views correctly, this is new to me 😬 😄 |
You can use "real time" view to debug GA easily. |
@MoOx yes well that's what bothers me, I don't see anything in the realtime panel when I visit https://relate.now.sh in parallel in another tab (0 active users) |
I'm still not getting this... I don't get any data with the code I wrote. All the examples I see seem to require a An example would still be very appreciated 🙂 |
Ah, got it working by switching to react-ga 😄 |
How did you get it to work? I've been trying to call a pageview function on componentDidMount. The production app GA Check fails. |
@luandro don't remember the details, but you can look at the commit I linked above if it helps |
I did and tried it. I did the same as you, calling configureAnalytics on top, and pageview on In your code it doesn't seem you actually connected page hoc anywhere, did you? |
@luandro Simply add |
Maybe there is a more 'next.js' way to do this but WRT running scripts on the page I found that if I created a // modules/Script.js
export default ({children}) => (
<script dangerouslySetInnerHTML={{__html: `(${children.toString()})();` }}></script>
); Then I could do this which worked for me: import Document, { Head, Main, NextScript } from 'next/document'
import Script from '../modules/Script';
export default class MyDocument extends Document {
render () {
return (
<html>
<body>
<Main />
<Script>
{
() => {
console.log('foo');
}
}
</Script>
<NextScript />
</body>
</html>
)
}
} The caveat is that you must enclose everything in a function. |
Is it possible to track individual pageviews without explicitly calling the ga('send', 'pageview') on every page. If we absolutely have to do it, where do we invoke it from having certainty that ga has been loaded? Is it possible to tie into route change events in some way to log pageviews? |
@karthikiyengar I am using
|
@vinaypuppal is it common practice to initGA for every page component? |
@rongierlach I'm using a export default class extends Component {
componentDidMount() {
ReactGA.initialize('UA-1234567-1')
ReactGA.pageview(document.location.pathname)
}
render() {
return (
<div>
{this.props.children}
</div>
)
} This is the cleanest way I've done it yet as if the page is server rendered, it needs to initialize. I'm sure there is a hook that could bypass the initialize if it's client rendered. |
@notrab couldn't you potentially be missing the shallow renders? They your app will just transition and your layout component may not remount. This is what I have to catch those. componentDidMount() {
ReactGA.initialize('xx-xxxxxxx-x')
let trackMe = true
if (trackMe) {
ReactGA.pageview(document.location.pathname)
trackMe = false
}
Router.onRouteChangeStart = () => {
NProgress.start()
this.store.dispatch(transitionPage(true))
trackMe = true
}
Router.onRouteChangeComplete = () => {
NProgress.done()
this.store.dispatch(transitionPage(false))
if (trackMe) { ReactGA.pageview(document.location.pathname) }
}
Router.onRouteChangeError = () => {
NProgress.done()
this.store.dispatch(transitionPage(false))
}
this.store.dispatch(calculateResponsiveState(window))
} |
* Add new Travis CI docs * Implement feedback Co-Authored-By: Timothy <hello@timothy.is> * Improve Travis guide * Fix weird spacing in Code blocks * Better list order * Further Travis guide improvements * Give the first paragraph a context to Travis * Better titles
An issue which arises if you're using NextJS 9 is that this with disable Automatic Prerendering. Wondering if there is a better place to put the Update: I found the with-google-analytics example (https://github.com/zeit/next.js/tree/canary/examples/with-google-analytics) and borrowed the bit about: |
@GodOfGrandeur This sounds promissing, will try in prod. Didn't get the version mentioned above working or seemed like so https://medium.com/@austintoddj/using-google-analytics-with-next-js-423ea2d16a98 Adding your code in _app.js seems to trigger everywhere like needed and I also like it's not triggered on server (would not have though it's an issue). |
No need for any third party, If you are using gtag use the following code I created:-
|
Another option is to use useEffect(() => {
if (process.env.NODE_ENV === 'production') {
window.dataLayer = window.dataLayer || []
function gtag() {
dataLayer.push(arguments)
}
gtag('js', new Date())
gtag('config', '{GOOGLE ANALYTICS CODE}', {
page_location: window.location.href,
page_path: window.location.pathname,
page_title: window.document.title,
})
}
}) And in the <Head>
<script async src="https://www.googletagmanager.com/gtag/js?id={GOOGLE ANALYTICS CODE}"></script>
</Head> |
@reinink Just want to mention that you might want to pass an empty array as the second prop to useEffect(() => {...}, []) |
Expanding on @reinink s solution, here's a working HOC I use to wrap my layout components/templates. import React, { useEffect } from 'react'
import Head from 'next/head'
const GoogleAnalyticsHOC = ({ children }) => {
useEffect(() => {
if (process.env.NODE_ENV === 'production') {
window.dataLayer = window.dataLayer || []
// eslint-disable-next-line
function gtag() {
window.dataLayer.push(arguments)
}
gtag('js', new Date())
gtag('config', process.env.GOOGLE_ANALYTICS_ID, {
page_location: window.location.href,
page_path: window.location.pathname,
page_title: window.document.title
})
}
}, [])
return (
<>
<Head>
<script async src={`https://www.googletagmanager.com/gtag/js?id=${process.env.GOOGLE_ANALYTICS_ID}`} />
</Head>
{children}
</>
)
}
export default GoogleAnalyticsHOC It's not extensively tested but it works and passes myself as a realtime visitor running locally. :) |
I found this guide - is this a recommended approach (uses react-ga)? |
I'd say recommended way is to use this official example: https://github.com/zeit/next.js/tree/canary/examples/with-google-analytics It's already posted here. Sometimes I wish github issues to be more like stackoverflow, having some answer accepted and highlighted, right after the question (when there's too many messages and emojis is not enough. One option is to restrict commenting this post, so people will create a new issue instead. And while creating they'll find a similar issue was already created (thanks to "similar issues" feature), and it has an answer (but still, the answer with emojis is lost somewhere in the middle of long history, so it's not very convenient to find answers on github). |
Github is prototyping this over on this repo's Discussions tab. |
@janbaykara wow, really? We all think the same way :) I hope they will find a way to somehow translate an issue to a discussion though, or it will be the same thing (if functionality will be merged to issues, and all existing discussions will become issues). But thanks for the response! |
@3lonious I've personally ditched Google Analytics, as it does not do a good job with SPA in general. (really bad experience, especially with SSR+CSR and double events hard to track down) Regarding Next.js, check out https://github.com/UnlyEd/next-right-now/blob/v2-mst-aptd-gcms-lcz-sty/src/components/pageLayouts/Head.tsx (using Dont hesitate to take a look at NRN https://unlyed.github.io/next-right-now, it's meant to be a good example on "how to do X" with Next.js and should save you quite some headaches. |
im not sure i get it, i dont see any script tags in that file? |
This is also a solution that works. I haven't tested it extensively so please do that yourself. In <script async src='https://www.googletagmanager.com/gtag/js?id=YOUR_GA_TRACKING_ID'></script>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments)}
gtag('js', new Date());
gtag('config', 'YOUR_GA_TRACKING_ID');
`
}}>
</script> It reports traffic to my GA account at least. |
@3lonious Script tags and style tags work the same way. |
ok thanks guys. im gonna try and get back to you |
ok i think i got it to work |
thanks Anton. ok i have a new one for you haha i have a chat app i use for customer service but that script tag dosnt work either? any ideas? |
How About TBT? If you add google analytics it will slower your speed score |
That’s because of their recommendation of placing the script before the content. If you place it under the content, the score won’t go down. I personally don’t see real benefits of placing the script first. If the page load was somehow broken, and HTML didn’t fully load somehow and it was aborted, then I might not count it as a hit, so whatever. |
I m working with nextjs. I m trying to use react google place auto complete API. And wants to insert those script tag of API? Where should I insert those script tag?? |
_app.js import ReactGA from "react-ga";
componentDidMount() {
ReactGA.initialize("XX-XXXXXXXXX-X", { debug: false });
ReactGA.set({ page: this.props.router.pathname });
ReactGA.pageview(this.props.router.pathname);
this.unlisten = this.props.router.events.on("routeChangeComplete", (router) => {
ReactGA.set({ page: router });
ReactGA.pageview(router);
});
} |
This comment has been minimized.
This comment has been minimized.
With React hooks : _app.js import { useEffect } from 'react'
import { useRouter } from 'next/router'
import ReactGA from 'react-ga'
import Layout from '../components/Layout'
function MyApp ({ Component, pageProps }) {
const router = useRouter()
useEffect(() => {
const handleRouteChange = (url, { shallow }) => {
ReactGA.set({ page: url })
ReactGA.pageview(url)
}
ReactGA.initialize('XX-XXXXXXXXX-X', { debug: false })
ReactGA.set({ page: router.pathname })
ReactGA.pageview(router.pathname)
router.events.on('routeChangeComplete', handleRouteChange)
return () => {
router.events.off('routeChangeComplete', handleRouteChange)
}
}, [])
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
}
export default MyApp |
This issue has been automatically locked due to no recent activity. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you. |
Hi there!
I am currently converting my website to a next.js project and can't figure out on how to add the Google Analytics script tag to the page. Any thoughts?
Cheers,
Robin
The text was updated successfully, but these errors were encountered: