Set up data collection with tracking and the Prepr Next.js package

Prepr is a CMS that includes built-in A/B testing and personalization features. These capabilities require visitor data to measure your test results and to build segments for personalization. This chapter of the Next.js complete guide shows you how to enable tracking to collect this data in your Next.js front end and how to simplify this data collection with the Prepr Next.js package.

Enable Prepr tracking and collect view events

The steps below continue from the previous section, Make your Next.js project dynamic. If you don't yet have a Next.js project connected to Prepr, follow the previous steps listed in the Complete guide overview to create one. Otherwise, let's get started.

Add the tracking code

Adding the Prepr tracking code to your front end allows you to capture visitor (Customer) data and lets you track how they engage with your content.

Follow the steps below to add the tracking code:

  1. Go to the src/app folder and add the highlighted code below to the layout.tsx file.
./src/app/layout.tsx
import type {Metadata} from "next";
import NavBar from "@/components/NavBar";
import './globals.css'
import {Ubuntu} from "next/font/google";
import Script from 'next/script'
 
const ubuntu = Ubuntu({weight: ['400', '700'], subsets: ['latin']})
 
export const metadata: Metadata = {
    title: "Prepr advanced starter",
    description: "Showing the power of personalization and A/B testing",
};
 
export default function RootLayout({children}: Readonly<{children: React.ReactNode;}>) {
    return (
        <html lang="en">
            <head>
                <Script
                id={'prepr_script'}
                dangerouslySetInnerHTML={{
                    __html: `YOUR-PREPR-CODE-SNIPPET`,
                }}></Script>
            </head>
	        <body className={ubuntu.className}>
		        <NavBar/>
		        {children}
	        </body>
        </html>
    );
}
  1. In your Prepr environment, go to the Settings → Event tracking page.

  2. Copy the Prepr tracking code and paste it into the placeholder YOUR-PREPR-CODE-SNIPPET above.

event tracking page

  1. Remove the HTML tags <!-- Prepr Tracking Code -->, <script> and </script> tags from the embedded code. This is because you're using the Next.js Script function to execute the tracking code directly.

  2. Refresh your website page in the browser. If there are no errors in the terminal console, the tracking code has been added successfully.

Troubleshooting
Syntax error: Unexpected token '<'
Cause: HTML tags are included in the code snippet that you copied.
Solution: Remove all the HTML tags, <!-- Prepr Tracking Code -->, <script> and </script> from the embedded code in the layout.tsx file.

Track page view events

For the subsequent A/B testing and personalization sections in this guide, we want to track page view events. To do this, add a content item meta property to the page.tsx file like in the highlighted code below. The tracking code automatically recognizes this property and records the view event in Prepr. Check out the data collection events docs for more details.

./src/app/[[...slug]]/page.tsx
import HeaderSection from "@/components/HeaderSection";
import ImageAndTextSection from "@/components/ImageAndTextSection";
import {getClient} from "@/ApolloClient";
import {GetPageBySlugDocument, GetPageBySlugQuery} from "@/gql/graphql";
import {notFound} from "next/navigation";
 
async function getData(slug: string) {
    const {data} = await getClient().query<GetPageBySlugQuery>({
        query: GetPageBySlugDocument,
        variables: {
            slug: slug,
        },
        fetchPolicy: 'no-cache',
    })
 
    if (!data) {
        return notFound()
    }
 
    return data
}
 
export default async function Page({params}: { params: { slug: string | string[] } }) {
    let {slug} = params
 
    if (!slug) {
        slug = '/'
    }
 
    if (slug instanceof Array) {
        slug = slug.join('/')
    }
 
    const data = await getData(slug)
    const elements = data.Page?.stack.map((element, index) => {
        if (element.__typename === 'SectionImageAndText') {
            return <ImageAndTextSection key={index} data={element}/>
        } else if (element.__typename === 'SectionHeader') {
            return <HeaderSection key={index} data={element}/>
        }
    })
 
    return (
        <div>
            <meta property='prepr:id' content={data.Page?._id}/>
            {elements}
        </div>
    );
}

For more details on how to track other types of events, check out the data collection docs.

Test data collection

You can easily check if the data collection is successful with the following steps.

  1. Go to your website in the browser and refresh the page.

  2. In your Prepr environment, go to the the Segments page.

  3. If the page view is recorded successfully you'll see a recent customer in the All customers list.

  4. Click to open this customer and you should see the View event on the Homepage similar to the image below.

page view event

Install the Prepr Next.js package

We've provided the Prepr NextJS package (opens in a new tab) to simplify working with event data for A/B testing and personalization.

In the steps above, you enabled tracking in your website with the Prepr tracking code. The Prepr tracking code generates the __prepr_uid cookie for each website visitor. This visitor gets stored in Prepr as a Customer with this unique ID, if they don't already exist.

This means you can use this __prepr_uid cookie value to set the API request header, Prepr-Customer-Id, when you retrieve the page content for A/B testing and personalization. The Prepr NextJS package prepares the Prepr-Customer-Id API request header for you, using the __prepr_uid cookie value.

Based on this value, Prepr retrieves the right content as follows:

  • A/B testing: Prepr decides which variant, A or B, to return in the content.
  • Personalization: Prepr checks the segment that this customer belongs to and retrieves the matching personalized variant.

To install the Prepr NextJS package, follow the steps below.

  1. In your Next.js project, install the package with the following terminal command:
npm install @preprio/prepr-nextjs

Once done, you need to call a function in the package to prepare the API request headers before the page gets rendered in your website.

  1. To do this, go to your project and create a new file middleware.ts in the src folder. Then add the following code to call the PreprMiddleware function.
./src/middleware.ts
import { NextRequest } from 'next/server'
import { PreprMiddleware } from '@preprio/prepr-nextjs'
 
export function middleware(request: NextRequest) {
    return PreprMiddleware(request)
}

Congratulations! You've successfully enabled Prepr tracking in your Next.js front end, started collecting page view events, and installed the Prepr Next.js package for A/B testing and personalization. Now, you're ready to add A/B testing and personalization to your website.

Was this article helpful?

We’d love to learn from your feedback