Nextjs14-Custom-Tracking-Script
Author Cloudapp
E.G.

Next.js 14 -Building Custom Client-Side Tracking End-to-End

August 20, 2024
Table of Contents

In this story, I will show you how you can build a custom hook for page tracking and integrate it into your existing Next.js 14 project with ease. The tracked data will be saved into a Neon.tech Postgres DB via the ORM Prisma and a custom API Route.

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/

NPM Package for Fingerprinting

If you read the first story, you have already installed the needed NPM packages.

Changing Prisma Schema

Adding new Data Fields to our schema.prisma File

Syncing Schema Changes

after Schema changes, so that the change was synchronised with the underlying DB.

Creating a new Tracking Hook

Now we are ready for the creation of our new hook, where we use the new npm package “fingerprintjs”, which we use to define a UserID.

New Component for Hook Integration

Now, we create a new Component that uses the new hook, which we then import into our layout.tsx

Importing new Component into Layout

Now we import the component src/app/[locale]/layout.tsx

and below {children} we use the component.

Layout.tsx — Complete Code

Saving Tracking Data to Postgres DB via Custom Route

We use the new route in our previously created hook

Tracking Route — Complete Code

The Route gets the data and stores it in the corresponding “tracking” table. Since we are using Prisma, it’s quite simple.

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