Add personalization to your Next.js website

Prepr CMS enables editors to create adaptive content directly in their content items to personalize elements of web pages. This makes setting up personalization really simple and effective in increasing engagement and conversions. This chapter of the Next.js complete guide shows you how to add personalization to your Next.js website.

At the end of this section, you'll see a personalized home page for visitors interested in electric cars.

Personalized home page

The steps below make use of the Adaptive content in the Homepage content item from the Acme Lease demo data.

Home page content item

Home page content item with Adaptive content for the Hero and Feature sections.

This chapter continues from the previous section, Set up data collection. If you haven't yet enabled Prepr tracking in your Next.js project, follow the steps in this section first. Otherwise, let's get started.

You can also watch the video for step-by-step instructions detailed in the guide below.

Set up personalization for the home page

You can show different personalized versions of the content to different groups (Segments) of visitors. To show the right variant to the right visitor:

  • Every visitor is given an ID that resolves to a segment they belong to.
  • In your front end, you need to send this ID along with the query to retrieve the right variant.
  • This is done by setting the value for the API request header, Prepr-Customer-Id, when you make the API request to retrieve the content.

By installing the Prepr Next.js package in the previous section, you've already prepared your API request headers.

Add customers to segments

For this setup we'll make use of the Electric Car Lovers segment in the Acme lease demo data. Make sure that the segment in your Prepr environment includes the condition, Customers who did view specific items, Electric Lease Landing Page.

segment builder

If you need more details, checkout the Segments docs.

You previously enabled Prepr tracking in your website. This means a customer gets added to the Electric Car Lovers segment whenever they view the Electric Lease Landing Page content item.

You can test this with the following steps:

  1. Go to http://localhost:3000/electric-lease to open the electric lease landing page in your website.

    Electric Car landing page

  2. In your Prepr environment, go to the Segments page and click the Electric Car Lovers segment. You should see matching customers in this segment like in the image below.

    Electric Car segment customers

To make sure that customers in the Electric Car Lovers segment see the matching adaptive content when they visit the home page, you need to set the API request header, Prepr-Customer-Id, when you retrieve the page content. Based on this value, Prepr will check the segment that this customer belongs to and will retrieve the matching personalized variant.

Because you installed the Prepr Next.js package previously, your API request headers are already prepared.

Set the API request headers

Since the API request headers are already prepared, you can simply set the API request headers for your page. To set the API request headers, update your page.tsx with the highlighted code below:

./src/app/[[...slug]]/page.tsx
// Import the section components to display them 
import HeroSection from "@/components/sections/hero-section";
import FeatureSection from "@/components/sections/feature-section";
import {getClient} from "@/apollo-client";
import {GetPageBySlugDocument, GetPageBySlugQuery} from "@/gql/graphql";
import {notFound} from "next/navigation";
import { getPreprHeaders } from '@preprio/prepr-nextjs'
 
export const revalidate = 0
export const dynamic = 'force-dynamic'
 
async function getData(slug: string) {
  const {data} = await getClient().query<GetPageBySlugQuery>({
    query: GetPageBySlugDocument,
    variables: {
        slug: slug,
    },
    context: {
      // Call the getPreprHeaders function to get the appropriate headers
      headers: await getPreprHeaders()
    },
    fetchPolicy: 'no-cache',
  })
 
    if (!data.Page) {
        return notFound()
    }
 
    return data
}
 
export default async function Page({ params}: {params: Promise<{ slug: string | string[]}>}) 
{
    let { slug} = await params
 
    // Set the slug to the home page value if there's no slug 
    if (!slug) {
        slug = '/'
    }
 
    // Add a forward slash to the slug to navigate to the correct page.
    if (slug instanceof Array) {
        slug = slug.join('/')
    }
 
    const data = await getData(slug)
    const elements = data.Page?.content.map((element, index) => {
      if (element.__typename === 'Feature') {
          return <FeatureSection key={index} item={element}/>
      } else if (element.__typename === 'Hero') {
          return <HeroSection key={index} item={element}/>
      }
    })
    
    return (
        <div>
          <meta property='prepr:id' content={data.Page?._id}/>
          {elements}
        </div>
    );
}

Test your adaptive content

Now that people who visit the Electric lease landing page are being grouped into the Electric Car Lovers segment, you can test the adaptive content. To test the adaptive content for the Electric Car Lovers segment follow the steps below.

  1. Go to the Electric Car landing page in your website. For example: http://localhost:3000/electric-lease.
  2. Wait a few seconds and go back to the home page. You can now see the personalized home page like in the image below.

Personalized home page

To see the non-personalized page, you can reset the cookies and refresh the page as follows:

  1. Right-click the page to Inspect the page, click the Application tab. Under the cookies, click your localhost. You'll notice the __prepr_uid cookie in the list.

  2. Right-click the localhost entry to Clear the cookies and refresh the page. You should now see the non-personalized content in the home page.

clear cookies

Add HTML attributes to track impressions and conversion events

Your personalization is running successfully, however there are no metrics being recorded yet. You can see this with the Awaiting data message at the top of the Adaptive content block in the Homepage content item.

Home page content item

To get Prepr to start showing some metrics data, you need to add HTML attributes to elements in your adaptive content. When you add these attributes, the tracking code you added in the previous section automatically tracks impressions and your chosen conversion events.

  1. To start collecting impressions and clicks, add the HTML attributes data-prepr-variant-key and data-prepr-variant-event to the Hero section as shown in the highlighted code below. The impression is recorded when the Hero element scrolls into view. The click is recorded when the Button element is clicked.

    ./src/components/hero-section.tsx
    import Link from 'next/link'
    import { FragmentType, getFragmentData } from '@/gql'
    import { HERO_SECTION_FRAGMENT } from '@/queries/get-page-by-slug'
    import Image from 'next/image'
    import Button from '@/components/button'
     
    export default function HeroSection(props: { item: FragmentType<typeof HERO_SECTION_FRAGMENT> }) 
    {
        const item = getFragmentData(HERO_SECTION_FRAGMENT, props.item)
        const image = item.image
        
        return ( 
            /* Set the HTML attribute with the matching data-prepr-variant-key to collect impressions for the whole section */
            <section className="bg-primary-50" data-prepr-variant-key={item._context?.variant_key}>
                <div className="mx-auto max-w-8xl p-spacing flex flex-col items-center md:flex-row gap-8 py-10 lg:py-20">
                    <div className="basis-6/12">
                        <h1 className="text-mb-5xl lg:text-7xl text-secondary-700 font-medium break-words text-balance">{item.heading}</h1>
                        <p className="text-mb-lg text-secondary-500 lg:text-lg mt-4 lg:mt-6 text-balance">{item.sub_heading}</p>
                        <div className="flex gap-4 mt-8 xl:mt-10">
                        <div>
                            {/* Set the HTML attribute to collect click events on the link */}
                            <Link href='#' data-prepr-variant-event><Button>Find your car</Button></Link>
                        </div>
                        </div>
                    </div>
                    <div className="basis-6/12 relative flex justify-end items-center">
                        <div className="z-10 flex items-center aspect-[20/17] w-9/12 overflow-hidden justify-center absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2">
                            <Image src={image?.url || ''} alt="Hero Image" width={720} height={360} className='object-cover rounded-2xl'/>
                        </div>
                        <div
                            className="w-9/12 aspect-[20/17] bg-primary-100 rounded-3xl right-0 top-0 z-0">
                        </div>
                    </div>
                </div>
            </section>
        )
    }

If you want to track a conversion other than a click event, e.g. a quote request, then set your data-prepr-variant-event to the custom event. For example: data-prepr-variant-event="QuoteRequest". Check out the Personalization doc for more details.

  1. To start recording metrics, go to the home page in your website, click the Find your car button.

  2. Now when you view the adaptive content in your Homepage content item, you can click the Metrics link and see the number of impressions and clicks like in the image below.

Adaptive content metrics

Congratulations! You have successfully set up personalization with metrics in your Next.js website. Now, you can install the preview bar to your website.

Was this article helpful?

We’d love to learn from your feedback