#track search params on every page

1 messages · Page 1 of 1 (latest)

verbal sierra
#

I'm trying to track referrers and store them in localstorage on every single page by checking for a ref search param. How could I do this for every single page without duplicating code?
Also, would it be better storing this in cookies, and if so, would there be any legal issues I'd have to consider?

vale ivyBOT
#

Hi @verbal sierra. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To track search params on every page in Next.js, you can use the useSearchParams hook in a Client Component. Here's how you could implement this:

  1. Create a Client Component that uses useSearchParams to check for the ref parameter:
'use client'

import { useSearchParams } from 'next/navigation'
import { useEffect } from 'react'

export function ReferrerTracker() {
  const searchParams = useSearchParams()

  useEffect(() => {
    const ref = searchParams.get('ref')
    if (ref) {
      localStorage.setItem('referrer', ref)
    }
  }, [searchParams])

  return null
}
  1. Include this component in your root layout or a layout that wraps all your pages:
import { ReferrerTracker } from './ReferrerTracker'

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <ReferrerTracker />
      </body>
    </html>
  )
}

This approach allows you to track the ref parameter on every page without duplicating code Next.js Docs: useSearchParams (https://nextjs.org/docs/app/api-reference/functions/use-search-params#examples).

Regarding your question about storing this information in cookies instead of localStorage:

  1. Cookies can be a better choice if you need to access this information on the server-side as well.

  2. However, using cookies for tracking purposes may have legal implications, especially under privacy laws like GDPR. You would need to consider:

    • Obtaining user consent before setting non-essential cookies.
    • Providing clear information about what data you're collecting and why.
    • Offering users the ability to opt-out of tracking.
#
  1. If you decide to use cookies, make sure to implement them securely. Next.js provides built-in support for handling cookies securely in both server and client components Next.js Docs: Authentication (https://nextjs.org/docs/app/building-your-application/authentication#selecting-session-management-in-nextjs).

Given these considerations, if you only need this information on the client-side, sticking with localStorage might be simpler and avoid potential legal issues related to cookies. However, if you need server-side access or want to track across devices, cookies might be necessary, but you'll need to ensure compliance with relevant privacy laws.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: