Skip to main content

Use case

  • Gate your app’s UI or navigation: Restrict access to application features that require authentication.
  • Route authenticated members: Direct members with active sessions to your main application experience.
  • Redirect unauthenticated members: Send members without sessions to your login or signup flow.

Retrieve a member session

Select a framework:
Follow our Next.js quickstart for an example routing a member 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 useStytchMemberSession()

You can use the useStytchMemberSession() hook to retrieve a member’s session data and listen for changes:
import { useStytchMemberSession } from '@stytch/nextjs/b2b';
import { useRouter } from 'next/navigation';

// Protected page example that routes a member to login if there's no active session
export default function Home() {
    const { session, isInitialized } = useStytchMemberSession();
    const router = useRouter();

    useEffect(() => {
        // Route the member 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>;
}

Using the isInitialized and session values

The useStytchMemberSession() hook returns the values:
isInitialized
boolean
Whether or not the SDK has finished initializing. Ensure this is true before checking for an active session.
session
object[] | null
The active Member Session object. null if there’s no active session.
fromCache
boolean
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:
  1. The page first loads.
  2. Stytch’s SDK checks and returns cached Member and Session data to your application.
  3. The SDK refreshes Member 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.