B2B Saas Authentication

/

Frontend SDKs

/

Headless

/

Session Management

/

Get Tokens

Get tokens

Returns the session_token and session_jwt values associated with the logged-in user's active session. If no active session is present, returns null.

Note that the Stytch SDK stores the session_token and session_jwt values as session cookies in the user's browser. Those cookies will be automatically included in any request that your frontend makes to a service (such as your backend) that shares the domain set on the cookies, so in most cases, you will not need to explicitly retrieve the session_token and session_jwt values using the getTokens() method. However, we offer this method to serve some unique use cases where explicitly retrieving the tokens may be necessary.

import { useEffect, useMemo } from 'react';
import { useStytchMemberSession, useStytchB2BClient } from '@stytch/react/b2b';

export const GetSessionTokens = () => {
  const stytch = useStytchB2BClient();
  const { session } = useStytchMemberSession();

  // This will update the sessionTokens every time the session updates (on login, session refresh, MFA, etc.)
  const sessionTokens = useMemo(() => {
    return session ? stytch.session.getTokens() : null;
  }, [session, stytch.session]);

  // This useEffect block will trigger anytime the sessionTokens change
  useEffect(() => {
    if (sessionTokens) {
      // Do something with the tokens
      console.log('session token', sessionTokens.session_token);
      console.log('session jwt', sessionTokens.session_jwt);
    }
  }, [sessionTokens]);

  return null;
};