Integration of Firebase Analytics in Nextjs Application in Minutes.
By: Dipesh K.C.
Tags: Analytics Tool, JavaScript, Nextjs, Firebase, Programming

Integration of Firebase Analytics in Nextjs Application in Minutes.

Hello Developers 👋. Analytics has been a very essential tool for us. It helps us to get a deeper understanding of our customers. But it was not very straightforward to be used with the Nextjs Application when I tried it. So In this article, I will demonstrate how easily Analytics can be integrated with the Nextjs Application.

Firebase Setup (Part 1 — on Firebase Console)

Let’s start by setting the Firebase project by going to the firebase console.

Select Add Project on your console.

Add your Firebase Project Name in step 1.

Enable Google Analytics in Step 2. Then you need to choose or create a Google Analytics account in step 3.

Upon project creation, a new Google Analytics property will be created in your chosen Google Analytics account and linked to your Firebase project. This link will enable data flow between the products.

Now we have our Firebase Project Setup. And we can navigate to our firebase dashboard by clicking on the currently created project on the console.

Connect Firebase to Next Application

We need a Firebase config to connect to our application. To generate it we first go to the Project Setting as shown in the below screenshot.

Select Add Firebase to your web app from the general tab.

After Registering App we now get all the config codes we require to connect firebase to our Next Application.

Start working on our Next Application

You can create a new Next Application with the below command.

npx create-next-app nextjs-firebase-analytics

We add a firebase.js file on root utils folder.

firebase.js

Let me explain the above codes briefly

[Line 1–2]: Instead of importing everything we just import the individual SDK components we intend to use.

// Like this

import firebase from 'firebase/app';

import 'firebase/<PACKAGE>';

In our case, we only need an analytics module.

[Line 4–12]: These are the config codes we got before from the firebase console.

[Line 13–15]: We here create and initialize a Firebase. Note we have included one if condition here.

// check if already initialized

if (!firebase.apps.length) {

//initilize now

}

The need for this if condition is to confirm that the firebase is not already initialized before. Else we get an error as below

❌ ERROR FirebaseError: Firebase: Firebase App named ‘[DEFAULT]’ already exists (app/duplicate-app).

[Line 16–18]: Here we are just taking the reference of firebase.analytics function. The reason behind not calling the function here is that analytics internally use window.navigator functionality. And if we call the function here we get the following error.

❌ReferenceError: navigator is not defined

There is no window object present during the server-side rendering of Nextjs application.

Solution 1

if(typeof window != undefined){

firebase.analytics()

}

Solution 2 [We will Follow this]

We call the analytics function inside hooks. Hooks are always called during client-side rendering. [Implement Later in the article]

[Line 18]: Finally, we then export it for use in different parts of our application.

_app.js

This file is primarily used to initialize pages and it is not unmounted on page navigations. So this is a good place for our use case. Here in this file we first import analytics from our utils file that we just created and call analytics() inside useEffect which always runs on the browser. Here we also check if the environment is production.

Implementing screen_view event

Here we track pages visited by our customers. For this, we use Nextjs router events to listen routeChangeComplete . On triggering this event we first set the current screen using setCurrentScreen function. It sets screen_name parameter to subsequent events. Then we log screen_view event using logEvent function. Alternatively, we could do

analytics().logEvent("screen_view", {

screen_name: url

}); //Possible Parameter to this event are



app_id ?: string

app_installer_id ?: string

app_name : string ;

app_version ?: string ;

screen_name : EventParams [ "screen_name" ]

Trigger any custom event

We can trigger any custom events in any components to collect additional data from the user.

import { analytics } from "../utils/firebase"; useEffect(() => {

analytics("Page1_visited")

analytics("Blog1_read")

})

Viewing Analytics Result

Option1

You can visit your firebase project console. Here on Analytics section we getting different options.

If you click Events we can see different events triggered by the user.

Option2

Visit https://analytics.google.com/ and browse your project. You can view the events as below.

CONCLUSION

If you get lost on any part you can check this Github project.

That’s it for this article. This is the end of our short journey with the implementation of firebase analytics on Nextjs Application. Hope this will help you with your project. Any kind of suggestions would be highly appreciable. Happy Coding 💻.