User Session
Overview
The User Session feature is designed to manage user session state and information within the application. It provides a consistent way to handle user authentication and session management, ensuring that user data is accessible throughout the application lifecycle.
User-facing behavior
- Users can log in and out, with their session state being maintained across different parts of the application.
- When a user is authenticated, their session information, including user details, is readily available.
- The application displays loading states while session data is being fetched, improving user experience during authentication processes.
Architecture and data flow
- The User Session feature utilizes a custom hook,
useSession, which interacts with theuseAuthhook from the@workos-inc/authkit-nextjslibrary to manage authentication state. - The
getSessionfunction in the session management utilities retrieves session data, including user information and access tokens. - The flow of data involves:
- Fetching user authentication status and session ID.
- Constructing user session objects that include user details like email and avatar URL.
- Handling both normal and end-to-end testing scenarios through environment variable checks.
Key implementation details
- The
useSessionhook returns session data and loading state:
export const useSession = (): { session: ClientSession | null; loading: boolean } => {
const { user, sessionId, loading } = useAuth();
if (!user || !sessionId) {
return { session: null, loading };
}
return {
loading,
session: {
sessionId,
user: {
workosId: user.id,
email: user.email,
name: getName(user.firstName, user.lastName),
avatarUrl: user.profilePictureUrl ?? null,
},
},
};
};
- The
getSessionfunction handles both normal and E2E testing scenarios:
const allowE2EBypass =
process.env['E2E_BYPASS_AUTH'] === '1' &&
process.env['PLAYWRIGHT_E2E'] === '1' &&
process.env['NODE_ENV'] !== 'production';
if (allowE2EBypass) {
return {
sessionId: 'e2e-session',
accessToken: 'e2e-access-token',
user: {
workosId: process.env['E2E_WORKOS_ID'] ?? 'e2e_workos_user',
email: process.env['E2E_USER_EMAIL'] ?? 'e2e@wikismith.local',
name: 'E2E Test User',
avatarUrl: null,
},
};
}
- User details are constructed using a helper function that combines first and last names:
const getName = (firstName?: string | null, lastName?: string | null): string | null => {
const name = [firstName, lastName].filter(Boolean).join(' ').trim();
return name.length > 0 ? name : null;
};
Key files
apps/web/src/hooks/use-session.ts- Custom hook for managing user session state and loading status, providing a structured way to access session dataapps/web/src/hooks/use-session.ts:12-28.apps/web/src/lib/auth/session.ts- Contains session management utilities, including thegetSessionfunction that retrieves user session data and handles E2E testing scenariosapps/web/src/lib/auth/session.ts:1-35.