#track search params on every page
1 messages · Page 1 of 1 (latest)
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:
- Create a Client Component that uses
useSearchParamsto check for therefparameter:
'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
}
- 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:
-
Cookies can be a better choice if you need to access this information on the server-side as well.
-
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.
- 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).