How to use browser api from Page.tsx
Unanswered
Californian posted this in #help-forum
CalifornianOP
I am implementing a social media pixel into my nextjs project. The pixels for events use browser api - to record a page view:
How can I add this logic to a page which is a server component?
I also need to have a central place for initialising the pixel.
Currently in my layout.tsx I am calling a client component:
window.pixel.track('pageview') for example. How can I add this logic to a page which is a server component?
I also need to have a central place for initialising the pixel.
Currently in my layout.tsx I am calling a client component:
export function Pixel() {
const [loaded, setLoaded] = useState(false);
const pathname = usePathname();
useEffect(() => {
if (!loaded) return;
window.p.track("ViewContent", {
contents: [
{
content_name: "PageName",
},
],
});
}, [pathname, loaded]);
return (
<div>
<Script
id="social-media-pixel"
src="/scripts/social-media-pixel.js"
strategy="beforeInteractive"
onLoad={() => setLoaded(true)}
data-pixel-id={"your-id-here"} //pixel id
/>
</div>
);
};1 Reply
@Californian I am implementing a social media pixel into my nextjs project. The pixels for events use browser api - to record a page view: `window.pixel.track('pageview')` for example.
How can I add this logic to a page which is a server component?
I also need to have a central place for initialising the pixel.
Currently in my layout.tsx I am calling a client component:
typescript
export function Pixel() {
const [loaded, setLoaded] = useState(false);
const pathname = usePathname();
useEffect(() => {
if (!loaded) return;
window.p.track("ViewContent", {
contents: [
{
content_name: "PageName",
},
],
});
}, [pathname, loaded]);
return (
<div>
<Script
id="social-media-pixel"
src="/scripts/social-media-pixel.js"
strategy="beforeInteractive"
onLoad={() => setLoaded(true)}
data-pixel-id={"your-id-here"} //pixel id
/>
</div>
);
};
How can I add this logic to a page which is a server component?you can't. you must use a client component. what you are doing is fine.