Custom Tracking part2
Author Cloudapp
E.G.

Next.js 14 - Custom Client-Side Tracking - Part 2 (new data attributes)

August 22, 2024
Table of Contents

In this follow-up story, I will show you how to add new attributes to your tracking data set. We will add the UserAgent, Pathname, Mobile, Platform, Region, and City. All data will be saved to a Neon.tech Postgres DB via Prisma ORM, as in the story before.

Here is the GitHub repo with the entire code. Below, you will find the link to the example page.

Example page hosted on Vercel -> https://nextjs14-kafka-tracking.vercel.app/

Prisma Schema for new attributes

We added a new table, “custom tracking,” to our schema.prisma so that this table will be created within our Postgres DB Service neon.tech. We need to run the below command to synchronize our schema with the DB

New schema.prisma File

We added new attributes like city, region, pathname, useragent, platform, and mobile.

Modifying existing Tracking Hook

We will adapt the tracking hook we created in the last story.

Modified usePageTracking Hook

The main logic sits in the usePageTracking Hook. The complete code is visible below.

To extend the script to track the userAgent, pathname, mobile, platform and city, we'll update the usePageTracking hook accordingly.

Explanation of the Additions:

  • The userAgent is retrieved from the navigator.userAgent object. This string contains information about the browser, operating system, and device.

  • The pathname is obtained from window.location.pathname, which gives you the path of the URL relative to the domain.

  • The platform is retrieved using navigator.platform. This provides the operating system or environment the user is on, such as Win32 for Windows, MacIntel for macOS, etc.

  • The isMobileDevice function checks if the user's device is likely to be a mobile device based on the userAgent string. It checks for common mobile device identifiers like android, iPhone, iPad, etc. Returns true if a mobile device is detected and false otherwise.

  • The getUserLocation function now returns an object containing country, city and

    region by using the ipapi.co API. This data is retrieved using the API response and includes fallback values of Unknown if the data isn't available.

You can extend the Hook even more, if you would like to track additional attributes.

New Route for writing data to Neon.tech table “customtracking”

Since we created a new table, “custom tracking,” we will create a new API Route as well so that we can clearly separate the logic.

That’s it. Now we have quite complete tracking of our users on the page. Please don’t forget to respect GDPR rules and activate tracking only if you are allowed to.

Cloudapp-dev, and before you leave us

Thank you for reading until the end. Before you go:

Please consider clapping and following the writer! 👏 on our Medium Account

Or follow us on twitter -> Cloudapp.dev

Related articles