Session Management
What is a session?
Sessions play a crucial role in Blueprint for user authentication. They ensure the synchronisation of user login statuses, contributing to a consistent and seamless user experience.
Blueprint's sessions do not store user data server-side. They are therefore defined as "stateless". They use authentication cookies to determine if a user is logged in.
How to use a session
Blueprint has a custom hook called useSession
to manage sessions. This hook calls the api/authentication/session route and returns session states such as isAuthenticated
and isMasquerading
.
isAuthenticated
checks if two Kraken tokens, accessToken and refreshToken, are present. If not, the user is not logged in.
isMasquerading
checks if the Kraken token masqueradeToken
is present. If not, the user is not masquerading.
What is a session used for?
The isAuthenticated
value from useSession
is used to check if a user is logged in. For example, the header can show "Account" or "Log out" based on this value.
How are sessions synchronised?
Blueprint uses react-query's caching mechanism to keep sessions in sync. The cache key comes from the sub
value of the initial ObtainKrakenToken
response. This sub value is encrypted and stored as a cookie and is used to identify each user session.
The useSession
hook uses three react-query options to keep the session state "fresh": refetchOnMount, refetchOnWindowFocus, and refetchOnReconnect. These options ensure that users remain logged in, even when using multiple tabs or after a period of inactivity
How does the useKrakenQuery
use sessions?
The useKrakenQuery
hook (used for Blueprint's GraphQL requests) only permits queries requiring authentication when the isAuthenticated
session value is true. This prevents unnecessary requests when a user is not authenticated.
Summary
Blueprint's sessions are stateless, synchronised with caching, and managed with the useSession
hook. They provide a reliable way to determine authentication states and ensure a consistent user experience throughout the application.
Useful information:
- Session endpoint:
api/auth/session
- react-query enabled option documentation