Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 7138

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T01:01:08+00:00 2024-11-28T01:01:08+00:00

Using Hotjar and Google Analytics with Next.js to track behavior

  • 60k

As a developer, my go-to analytics tools are Hotjar and Google Analytics for both small, personal projects, and more complex applications that attract users. When I get a choice, Next.js is my favorite React framework – it offers server-side rendering (SSR), a growing and responsive community, and integrates easily with my favorite CSS framework, TailwindCSS.

In this tutorial, you'll learn how to easily integrate Hotjar with Google Analytics into your Next.js app. At the time of writing, the current Next.js version is 11. This tutorial assumes that you have already created Google Analytics and Hotjar accounts, and just need to add the codes into your application.

Installing Dependencies

Only one dependency is required for Hotjar – this makes it super simple to add in Hotjar support:

yarn add react-hotjar

Initializing Hotjar

Before you begin, you'll need your tracking code. When you set up your Hotjar site, you'll be presented with a script tag that contains a bunch of Javascript inside of it – find the line that contains h._hjSettings, and get the values for hjid and hjsfv. You'll need both of these.

Navigate to your _app.js document. We'll be adding in a useEffect hook that is initialized when the component mounts, and initializes the Hotjar client.

  1. Import the react-hotjar module, as well as the useEffect hook.
import { hotjar } from 'react-hotjar' import { useEffect } from 'react' 
Enter fullscreen mode Exit fullscreen mode

  1. Once those are imported, you need to add a useEffect hook within your component with an empty dependency array:
useEffect(() => {   hotjar.initialize(HJID, HJSV) }, []) 
Enter fullscreen mode Exit fullscreen mode

When you're finished, your component should look something like this:

import { hotjar } from 'react-hotjar' import { useEffect } from 'react'  function MyApp ({ Component, pageProps }) {   useEffect(() => {     hotjar.initialize(0123456, 1)   }, [])    return <Component {...pageProps} /> }  export default MyApp 
Enter fullscreen mode Exit fullscreen mode

That's it for Hotjar! Next, we'll move onto Google Analytics – keep this component ready as we'll need to add another useEffect hook to track GA actions.

Initializing Google Analytics

Before you begin, you'll need your tracking ID for the property you are installing Google Analytics for. If you can't find this tracking ID, Google provides a useful article with step-by-step instructions.

To install Google Analytics, you'll need to find the Head component of your Next.js app. Depending on how you structured your project, you may find this in the index.js file or a separate layout component. This script needs to be present on every page that you want to collect analytics for, so I suggest creating a separate layout component that wraps around your pages.

  1. Add the gtag scripts into your head tag – notice the dangerouslySetInnerHTML attribute. This is required for you to embed this tag but should be used carefully. For more information on this attribute, see this article by LogRocket.

Replace “TRACKING-ID” with the tracking ID that you got earlier.

<script   async   src='https://www.googletagmanager.com/gtag/js?id=TRACKING-ID' ></script> <script   dangerouslySetInnerHTML={{     __html: `    window.dataLayer = window.dataLayer || [];    function gtag(){dataLayer.push(arguments);}    gtag('js', new Date());    gtag('config', 'TRACKING-ID');`   }} ></script> 
Enter fullscreen mode Exit fullscreen mode

  1. If you don't have one already, create a lib directory in the project root and add a file called gtag.js. Add the following functions into your file, and replace “TRACKING-ID” with the previous tracking ID.
export const pageview = url => {   window.gtag('config', 'TRACKING-ID', {     page_path: url   }) }  export const event = ({ action, category, label, value }) => {   window.gtag('event', action, {     event_category: category,     event_label: label,     value: value   }) } 
Enter fullscreen mode Exit fullscreen mode

  1. Navigate back to _app.js. We will need to add another useEffect hook that is called each time an event occurs. Import the dependencies and the functions that we created in the previous step:
import * as gtag from 'lib/gtag'  import { useEffect } from 'react' import { useRouter } from 'next/router' 
Enter fullscreen mode Exit fullscreen mode

  1. Once those have been imported, you need to initialize the router and add in the useEffect hook that will follow route changes.
const router = useRouter()  useEffect(() => {   const handleRouteChange = url => {     gtag.pageview(url)   }   router.events.on('routeChangeComplete', handleRouteChange)   return () => {     router.events.off('routeChangeComplete', handleRouteChange)   } }, [router.events]) 
Enter fullscreen mode Exit fullscreen mode

When you're finished with both Hotjar and Google Analytics, your component should look like this:

import * as gtag from 'lib/gtag'  import { hotjar } from 'react-hotjar' import { useEffect } from 'react' import { useRouter } from 'next/router'  function MyApp ({ Component, pageProps }) {   const router = useRouter()    useEffect(() => {     const handleRouteChange = url => {       gtag.pageview(url)     }     router.events.on('routeChangeComplete', handleRouteChange)     return () => {       router.events.off('routeChangeComplete', handleRouteChange)     }   }, [router.events])    useEffect(() => {     hotjar.initialize(0123456, 1)   }, [])    return <Component {...pageProps} /> }  export default MyApp 
Enter fullscreen mode Exit fullscreen mode

Wrapping Up

That's it! You should now have Hotjar and Google Analytics collecting data for your site now.

You can find more of my content here.

javascriptnextjsreactwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.