Use case
- Gate your app’s UI or navigation: Restrict access to application features that require authentication.
- Route authenticated users: Direct users with active sessions to your main application experience.
- Redirect unauthenticated users: Send users without sessions to your login or signup flow.
Retrieve a user session
Select a framework:- Next.js
- React
- Vanilla JS
Determine where to authenticate sessions in your application
We recommend placing this logic close to the entry point to each page you want to control in your application.
Implement useStytchSession()
You can use the
useStytchSession() hook to retrieve a user’s session data and listen for changes:Using the isInitialized and session values
The
useStytchSession() hook returns the values:The active User Session object.
null if there’s no active session.Whether or not the SDK has finished initializing. Ensure this is
true before checking for an active session.Whether the SDK is returning cached session data based on if the SDK has completed an Authenticate Session call or not.
For most cases, you can rely on checking the
session value as long as isInitialized is true.Using cached data and fromCache
The frontend SDK utilizes stale-while-revalidate (SWR) for faster time-to-interactivity and UX:
- The page first loads.
- Stytch’s SDK checks and returns cached User and Session data to your application.
- The SDK refreshes User and Session data in background session authentication while your application starts.
fromCache is false before checking the session value.