Consumer Authentication

/

Frontend SDKs

/

Headless

/

Users

/

Get user

Get user

The SDK provides synchronous and asynchronous methods for getting a user. The recommended approach is to use the synchronous method, user.getSync, and listen to changes with the user.onChange method.

The user.getSync is a synchronous method for getting a user. This is the recommended approach. You can listen to changes with the onChange method. If logged in, this returns the cached user object, otherwise it returns null. This method does not refresh the user's data.

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

The user.onChange method takes in a callback that gets called whenever the user 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 useStytchUser hook that implements these methods for you to easily access the user and listen for changes.

The asynchronous method, user.get, wraps the get user endpoint. It fetches the user's data and refreshes the cached object if changes are detected. The Stytch SDK will invoke this method automatically in the background, so you probably won't need to call this method directly.

import React from 'react';
import { useStytchUser } from '@stytch/react';

export const Home = () => {
  const { user } = useStytchUser();

  return user ? <p>Welcome, {user.name.first_name}</p> : <p>Log in to continue!</p>;
};