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

<Tabs>
  <Tab title="Next.js" icon="triangle">
    <Tip>Follow our [Next.js quickstart](/consumer-auth/build-auth/login-or-signup#next-js-app) for an example routing a user based on whether there's an active session.</Tip>

    <Steps>
      <Step title="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.
      </Step>

      <Step title="Implement useStytchSession()">
        You can use the [`useStytchSession()`](/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>;
        }
        ```
      </Step>

      <Step title="Using the isInitialized and session values" icon="info">
        The [`useStytchSession()`](/api-reference/consumer/frontend-sdks/nextjs/hooks/use-stytch-session) hook returns the values:

        <ResponseField name="session" type="object[] | null">
          The active [User Session](/api-reference/consumer/api/sessions/session-object) object. `null` if there's no active session.
        </ResponseField>

        <ResponseField name="isInitialized" type="boolean">
          Whether or not the SDK has finished initializing. Ensure this is `true` before checking for an active session.
        </ResponseField>

        <ResponseField name="fromCache" type="boolean">
          Whether the SDK is returning cached session data based on if the SDK has completed an [Authenticate Session](/api-reference/consumer/frontend-sdks/nextjs/methods/sessions/authenticate-session) call or not.
        </ResponseField>

        <Info>For most cases, you can rely on checking the `session` value as long as `isInitialized` is `true`.</Info>
      </Step>

      <Step title="Using cached data and fromCache" icon="info">
        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.
      </Step>
    </Steps>
  </Tab>

  <Tab title="React" icon="react">
    <Tip>Follow our [React quickstart](/consumer-auth/build-auth/login-or-signup#react) for an example routing a user based on whether there's an active session.</Tip>

    <Steps>
      <Step title="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.
      </Step>

      <Step title="Implement useStytchSession()">
        You can use the [`useStytchSession()`](/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>;
        };
        ```
      </Step>

      <Step title="Using the session value" icon="info">
        The [`useStytchSession()`](/api-reference/consumer/frontend-sdks/react/hooks/use-stytch-session) hook returns the values:

        <ResponseField name="session" type="object[] | null">
          The active [User Session](/api-reference/consumer/api/sessions/session-object) object. `null` if there's no active session.
        </ResponseField>

        <ResponseField name="isInitialized" type="boolean">
          Whether the SDK has completed initialization.
        </ResponseField>

        <ResponseField name="fromCache" type="boolean">
          Whether the SDK is returning cached session data based on if the SDK has completed an [Authenticate Session](/api-reference/consumer/frontend-sdks/react/methods/sessions/authenticate-session) call or not.
        </ResponseField>

        <Info>For most cases, you can rely on checking the `session` value.</Info>
      </Step>

      <Step title="Using cached data and fromCache" icon="info">
        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.
      </Step>
    </Steps>
  </Tab>

  <Tab title="Vanilla JS" icon="js-square">
    <Tip>Follow our [Vanilla JS quickstart](/consumer-auth/build-auth/login-or-signup#vanilla-js) for an example routing a user based on whether there's an active session.</Tip>

    <Steps>
      <Step title="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.
      </Step>

      <Step title="Implement getSync() to retrieve session data">
        You can use the [`session.getSync()`](/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:

        <ResponseField name="session" type="object[] | null">
          The active [User Session](/api-reference/consumer/api/sessions/session-object) object. `null` if there's no active session.
        </ResponseField>
      </Step>

      <Step title="Implement onChange() to listen for changes">
        You can use the [`session.onChange()`](/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.
      </Step>
    </Steps>
  </Tab>
</Tabs>
