#How would use authjs in instrumentation file?
1 messages · Page 1 of 1 (latest)
You cannot access the authentication session (e.g., via useSession from Auth.js/NextAuth.js) directly inside the instrumentation-client file. The instrumentation-client file runs before React hydration, outside the React component tree, and does not have access to React hooks or context, including authentication state. This is a limitation of the execution environment for instrumentation-client, which is designed for global, pre-hydration setup only and not for per-user or per-session logic see docs.
If you need to identify users in PostHog with their session data, you must do this in a Client Component after authentication is available. For example, you can create a small Client Component that uses useSession and calls posthog.identify when the session is ready:
'use client';
import { useEffect } from 'react';
import { useSession } from 'next-auth/react';
import posthog from 'posthog-js';
export function PostHogIdentify() {
const { data: session } = useSession();
useEffect(() => {
if (session?.user) {
posthog.identify(session.user.id, {
email: session.user.email,
name: session.user.name,
// add other properties as needed
});
}
}, [session]);
}
Then, include this component in your layout or wherever it will be mounted after authentication is available.
Summary:
- The instrumentation-client file cannot access per-user session data or React hooks.
- User identification for analytics must be done in a Client Component after authentication is available see docs.