> ## Documentation Index
> Fetch the complete documentation index at: https://stytch.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Check for an active session

> Use the SDK to control your application's UI or navigation based on whether a user has an active session.

## 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:

> [tab] Next.js
>
> > [!TIP]
> >
> > Follow our [Next.js quickstart](https://stytch.com/docs/consumer-auth/build-auth/login-or-signup.md#next-js-app) for an example routing a user based on whether there's an active session.
>
> **1. 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.
>
> **2. Implement useStytchSession()**
>
> You can use the [`useStytchSession()`](https://stytch.com/docs/api-reference/consumer/frontend-sdks/nextjs/hooks/use-stytch-session) hook to retrieve a user's session data and listen for changes:
>
> ```jsx lines theme={null}
> import { useStytchSession } from '@stytch/nextjs';
> import { useRouter } from 'next/navigation';
>
> // Protected page example that routes a user to login if there's no active session
> export default function Home() {
>     const { session, isInitialized } = useStytchSession();
>     const router = useRouter();
>
>     useEffect(() => {
>         // Route the user to login if there's no session
>         if (!session && isInitialized) {
>             router.replace("/login");
>         }
>     }, [session, isInitialized, router]);
>
>     if (!isInitialized || !session) {
>         // Show loading while redirecting or if the SDK hasn't finished initializing
>         return <p>Loading...</p>;
>     }
>
>     // If there's an active session, show the home content
>     return <p>Welcome! You have an active session.</p>;
> }
> ```
>
> **3. Using the isInitialized and session values**
>
> The [`useStytchSession()`](https://stytch.com/docs/api-reference/consumer/frontend-sdks/nextjs/hooks/use-stytch-session) hook returns the values:
>
> **session** `object[] | null`
>
> The active [User Session](https://stytch.com/docs/api-reference/consumer/api/sessions/session-object.md) object. `null` if there's no active session.
>
> **isInitialized** `boolean`
>
> Whether or not the SDK has finished initializing. Ensure this is `true` before checking for an active session.
>
> **fromCache** `boolean`
>
> Whether the SDK is returning cached session data based on if the SDK has completed an [Authenticate Session](https://stytch.com/docs/api-reference/consumer/frontend-sdks/nextjs/methods/sessions/authenticate-session.md) call or not.
>
> > [!NOTE]
> >
> > For most cases, you can rely on checking the `session` value as long as `isInitialized` is `true`.
>
> **4. Using cached data and fromCache**
>
> The frontend SDK utilizes [stale-while-revalidate (SWR)](https://web.dev/case-studies/ads-case-study-stale-while-revalidate#what%27s-it-mean) for faster time-to-interactivity and UX:
>
> 1. The page first loads.
> 2. Stytch's SDK checks and returns cached User and Session data to your application.
> 3. The SDK refreshes User and Session data in background session authentication while your application starts.
>
> For use cases where you'd prefer to wait until the session data finishes updating instead of relying on cached data, you can verify that `fromCache` is `false` before checking the session value.

> [tab] React
>
> > [!TIP]
> >
> > Follow our [React quickstart](https://stytch.com/docs/consumer-auth/build-auth/login-or-signup.md#react) for an example routing a user based on whether there's an active session.
>
> **1. 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.
>
> **2. Implement useStytchSession()**
>
> You can use the [`useStytchSession()`](https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/hooks/use-stytch-session) hook to retrieve a user's session data and listen for changes:
>
> ```jsx lines theme={null}
> import { useStytchSession } from '@stytch/react';
> import { Navigate } from "react-router";
>
> // Protected page example that routes a user to login if there's no active session
> export const Home = () => {
>     const { session } = useStytchSession();
>
>     // Route users to login if there's no active session
>     if (!session) {
>         return <Navigate to="/login" />;
>     }
>
>     return <p>Welcome! You have an active session.</p>;
> };
> ```
>
> **3. Using the session value**
>
> The [`useStytchSession()`](https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/hooks/use-stytch-session) hook returns the values:
>
> **session** `object[] | null`
>
> The active [User Session](https://stytch.com/docs/api-reference/consumer/api/sessions/session-object.md) object. `null` if there's no active session.
>
> **isInitialized** `boolean`
>
> Whether the SDK has completed initialization.
>
> **fromCache** `boolean`
>
> Whether the SDK is returning cached session data based on if the SDK has completed an [Authenticate Session](https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/methods/sessions/authenticate-session.md) call or not.
>
> > [!NOTE]
> >
> > For most cases, you can rely on checking the `session` value.
>
> **4. Using cached data and fromCache**
>
> The frontend SDK utilizes [stale-while-revalidate (SWR)](https://web.dev/case-studies/ads-case-study-stale-while-revalidate#what%27s-it-mean) for faster time-to-interactivity and UX:
>
> 1. The page first loads.
> 2. Stytch's SDK checks and returns cached User and Session data to your application.
> 3. The SDK refreshes User and Session data in background session authentication while your application starts.
>
> For use cases where you'd prefer to wait until the session data finishes updating instead of relying on cached data, you can verify that `fromCache` is `false` before checking the session value.

> [tab] Vanilla JS
>
> > [!TIP]
> >
> > Follow our [Vanilla JS quickstart](https://stytch.com/docs/consumer-auth/build-auth/login-or-signup.md#vanilla-js) for an example routing a user based on whether there's an active session.
>
> **1. 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.
>
> **2. Implement getSync() to retrieve session data**
>
> You can use the [`session.getSync()`](https://stytch.com/docs/api-reference/consumer/frontend-sdks/vanilla-js/methods/sessions/get-session-sync) method to retrieve a user's session data:
>
> ```javascript lines theme={null}
> import { stytch } from "./stytch-client.js";  // or where Stytch is initialized
>
> function init() {
>     const session = stytch.session.getSync();
>     if (!session) {
>         // Redirect to login if there's no active session
>         window.location.href = "/login";
>         return;
>     }
>
>     // If there's an active session, show the protected content
>     document.getElementById('app').innerHTML = '<p>Welcome! You have an active session.</p>';
> }
>
> // Initialize when the page loads
> document.addEventListener("DOMContentLoaded", init);
> ```
>
> The `session.getSync()` method returns the value:
>
> **session** `object[] | null`
>
> The active [User Session](https://stytch.com/docs/api-reference/consumer/api/sessions/session-object.md) object. `null` if there's no active session.
>
> **3. Implement onChange() to listen for changes**
>
> You can use the [`session.onChange()`](https://stytch.com/docs/api-reference/consumer/frontend-sdks/vanilla-js/methods/sessions/on-change-session) method to listen for changes in the user's session:
>
> ```javascript lines theme={null}
> // Listen for session changes
> const unsubscribeSession = stytch.session.onChange((newSession) => {
>     session = newSession;
>     // Trigger any relevant actions in your application based on the session update
>     handleSessionChange();
> });
>
> window.addEventListener('beforeunload', () => {
>     unsubscribeSession && unsubscribeSession();
> });
> ```
>
> * The method takes in a callback that gets called whenever the Session object changes.
> * It returns an unsubscribe method for you to call when you no longer want to listen for changes.
