Session management

The SDK may be used to check whether a user has a cached session, view the current session, refresh the session, and revoke the session. To authenticate a session on your backend, you must use either the Stytch API or a Stytch Backend SDK.

Methods

Get session

The SDK provides the session.getSync method to retrieve the current session. The session.onChange method can be used to listen to session changes.

If logged in, the session.getSync method returns the cached session object. Otherwise it returns null.

The session.getInfo method is similar to session.getSync, but it returns an object containing the session object and a fromCache boolean. If fromCache is true, the session object is from the cache and a state refresh is in progress.

The session.onChange 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 such changes.

In React, the @stytch/react library provides the useStytchSession hook that implements these methods for you to easily access the session and listen for changes.

import React, { useEffect } from 'react';
import { useStytchSession } from '@stytch/react';

export const withMfaRequired = (Component) => (props) => {
  const { session } = useStytchSession();

  useEffect(() => {
    if (!session || session.authentication_factors.length < 2) {
      window.location.replace('/home');
    }
  }, [session]);

  if (!session || session.authentication_factors.length) {
    return null;
  }

  return <Component {...props} />;
};

Refresh session

Wraps Stytch's authenticate Session endpoint and validates that the session issued to the user is still valid. The SDK will invoke this method automatically in the background. You probably won't need to call this method directly. It's recommended to use session.getSync and session.onChange instead.


Method parameters


Configurationobject

Additional configuration.

session_duration_minutesint
import React, { useEffect } from 'react';
import { useStytch } from '@stytch/react';

export const RefreshSession = () => {
  const stytchClient = useStytch();

  useEffect(() => {
    const refresh = () => {
      if (stytchClient.session.getSync()) {
        stytchClient.session.authenticate({
          session_duration_minutes: 60,
        });
      }
    };
    // Refresh session every 50 minutes
    let interval = setInterval(refresh, 3000000);
    return () => clearInterval(interval);
  }, [stytchClient]);

  return <></>;
};

RESPONSE

200
{
    "status_code": 200,
    "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
    "session": {
      "attributes": {
        "ip_address": "203.0.113.1",
        "user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
      },
      "authentication_factors": [
        {
          "delivery_method": "email",
          "email_factor": {
            "email_address": "sandbox@stytch.com",
            "email_id": "email-test-81bf03a8-86e1-4d95-bd44-bb3495224953"
          },
          "last_authenticated_at": "2021-08-09T07:41:52Z",
          "created_at": "2021-08-09T07:41:52Z",
          "updated_at": "2021-08-09T07:41:52Z",
          "type": "magic_link"
        }
      ],
      "custom_claims": {
        "claim1": "value1",
        "claim2": "value2",
      },
      "expires_at": "2021-08-10T07:41:52Z",
      "last_accessed_at": "2021-08-09T07:41:52Z",
      "session_id": "session-test-fe6c042b-6286-479f-8a4f-b046a6c46509",
      "started_at": "2021-08-09T07:41:52Z",
      "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
    },
    "session_jwt": "example_jwt"
    "session_token": "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q"
    "user": {...},
  }

Revoke session

Wraps Stytch's revoke Session endpoint and revokes the user's current session. This method should be used to log out a user.

import React, { useCallback } from 'react';
import { useStytch } from '@stytch/react';

export const LogOutButton = () => {
  const stytchClient = useStytch();

  const logout = useCallback(() => {
    stytchClient.session.revoke();
  }, [stytchClient]);

  return <button onClick={logout}>Log out</button>;
};

RESPONSE

200
{
    "status_code": 200,
    "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141"
  }

Update session

Update a user's session tokens to hydrate a front-end session from the backend. For example, if you log your users in with one of our backend SDKs, you can pass the resulting session_token and session_jwt to this method to prime the frontend SDK with a valid set of tokens. You must then make an authenticate call to authenticate the session tokens and retrieve the user's current session.

import React, { useCallback, useEffect } from 'react';
import { useStytch, useStytchUser } from '@stytch/react';

export const App = () => {
  const stytchClient = useStytch();
  const { user } = useStytchUser();

  useEffect(() => {
    if (user) {
      // redirect to logged in experience
    }
  }, [user]);

  const authenticate = useCallback(() => {
    stytchClient.session.updateSession({
      session_token: 'a session token from your backend',
      session_jwt: 'a session JWT from your backend',
    });

    stytchClient.session.authenticate({ session_duration_minutes: 60 });
  }, [stytchClient]);

  return <button onClick={authenticate}>Hydrate session</button>;
};

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 is necessary.

import React, { useEffect } from 'react';
import { useStytch, useStytchSession } from '@stytch/react';

export const GetSessionTokens = () => {
  const stytchClient = useStytch();
  const { session } = useStytchSession();

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

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

  return null;
};