My goal is to use a client component to capture the IP and userAgent information. I have that working now. But it only works on a client component. My server components need to know this information as well.
Can I put that in an anonymous session somehow. Then my server components and client components can see this information as needed for writing log entries, etc.
I have next-auth setup. I just don’t know anything about anonymous sessions or if servers can see cookies or how to share that information to all my client and server pages.
I know it’s possible. Just no clue how. Anyone have any ideas?
Then create an anonymous session object to store the captured information.
Store the anonymous session object in a client-side storage mechanism like cookies.
When making server-side requests, attach the anonymous session object to the request headers or body.
Extract the anonymous session object from the incoming request in your server-side code.
And that’s all, you can access the captured IP address and user agent information from the server components.strong text
I have an api that returns the ip and userAgent data to a client-side component.
While this is not an ideal solution, I created a client component that calls that and collects the data. Then, along with some props, updates my log file with the data I need. That works well, but only works as a react client component, so far.
That means to use it for logging, I have a component. It can be pulled into any server side component so it creates good log entries.
The downside is that it only works as a component, so it cannot be called (as far as I know) from the code portions of components. So to record a programmatic problem, I have to render my page regardless and then pass the error message to this component. It feels hacky, but it does work and I get the accurate report of ip, userAgent, props, and whatever else I need.
I’ll continue to explore ways to implement something that ties the client session to the user session. Unfortunately, next-auth doesn’t seem to easily support anonymous sessions and I’m not sure how to implement sessions another way - not yet.
Thanks for the suggestions. I’m certain I’ll sort that out soon. But at least I have a version that works and tracks every user interaction with my website whether they log in or not.