React Native SDK

The Stytch React Native SDKs provide the easiest way for you to use Stytch in your React Native projects. We provide separate SDKs for Expo managed workflows as well as bare React Native projects to ensure ease of installation and use, as well as compatibility with iOS and Android builds. Using the SDKs allows you to easily authenticate your users without adding extra endpoints to your backend.

Compatibility and requirements

The Expo SDK is compatible with all actively supported Expo versions (currently Expo 41+).
The Expo SDK also supports all versions of iOS and Android supported by Expo (currently Android 5+ and iOS 11+)

The React Native SDK is compatible with React Native 0.60+

Supported authentication products

  • Email magic links
  • One-time passcodes
  • Session management
  • User management


Installation

Install the relevant package(s) as a project dependency via npm or yarn.

npm install @stytch/react-native react-native-device-info --save
npm install @stytch/react-native-expo --save

Initialize the SDK by creating a new StytchClient object provided in the package. We recommend storing the created client instance in a common file to use it in JavaScript methods such as Redux actions.

You do not need to manually link, but will need to run pod install if you are using @stytch/react-native.

StytchClient parameters


public_token*string

Provide the public token from the Stytch dashboard. This value is safe to embed client side.

At the root level of your application, initialize a new StytchProvider object using your public token. to provide all components with access to the StytchClient as well as User and Session data via hooks.

StytchProvider props


stytch*StytchClient | null

Provide the previously created StytchClient object.

Example

import { StytchClient, StytchProvider } from '@stytch/react-native';

const stytch = new StytchClient('PUBLIC_TOKEN');

const App = () => {
  return (
    <StytchProvider stytch={stytch}>
      <Component />
    </StytchProvider>
  );
};

Configuration

To authorize the Stytch SDK to run in your application, you must first add an Authorized Environment Bundle ID to your Stytch SDK Configuration.

Any application published to the Apple App Store or the Google Play Store must have a unique ID. In iOS development, this is referred to as a bundle identifier, and in Android it is referred to as the Application ID or package name.

If the bundle identifier / package name does not match the Authorized Environment Bundle ID in your Stytch SDK Configuration, then you will receive an invalid_mobile_identifier error on any requests made through the SDK. If you are encountering this error, ensure that you've followed the steps in this configuration correctly.

For bare React Native projects, the process takes a few extra steps, and there are separate processes for updating iOS bundle identifier vs. the Android package name.

For iOS, you first open the general settings for the project in Xcode. To get there, open the project workspace, and select the appname project from the project navigator. Once you've opened the general settings for the project, simply update the Bundle Identifier field.

For Android, there a number of steps. Firstly, you'll need to rename the folder structure inside android/app/src/main/java to reflect the package name for your project. If you had initialized your project with the name HelloWorld, you would find two files MainActivity.java and MainApplication.java inside android/app/src/main/java/com/helloworld. If you wanted to change your package name to com.myapp.test you'd have to update the folder structure so that those two files were insideandroid/app/src/main/java/com/myapp/test. After you've updated your folder structure, you need to update:

  • The package name on line 1 of MainActivity.java
  • The package name on line 1 of MainApplication.java
  • Line 2 of /android/app/src/main/AndroidManifest.xml
  • The package value for android_build_config and android_resource in /android/app/BUCK
  • The applicationId value in defaultConfig for the /android/app/build.gradle file.


Example apps

Demo React Native app

Example React Native app with bare workflow


Demo Expo app

Example React Native app with Expo managed workflow


One-time passcodes

One-time passcodes can be sent via email, phone number, or WhatsApp. One-time passcodes allow for a quick and seamless login experience on their own, or can layer on top of another login product like Email magic links to provide extra security as a multi-factor authentication (MFA) method.

Methods

To call these methods, One-time passcodes must be enabled in the SDK Configuration page of the Stytch dashboard.

Login Or Create via SMS

The Login or create method wraps Stytch's login_or_create via SMS API endpoint. Call this method to send an SMS passcode to new or existing users.

Method parameters


phone_number*string

The phone number of the user to send a one-time passcode.The phone number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, see Testing for more detail.


Configurationobject

Additional configuration.

Collapse


expiration_minutesint

Set the expiration for the one-time passcode, in minutes. The minimum expiration is 1 minute and the maximum is 10 minutes. The default expiration is 2 minutes.

Example

Vanilla
import React, { useCallback } from 'react';
import { useStytch } from '@stytch/react-native';
export const Login = () => {
  const stytchClient = useStytch();
  const sendPasscode = useCallback(() => {
    stytchClient.otps.sms.loginOrCreate('+12025550162', {
      expiration_minutes: 5,
    });
  }, [stytchClient]);
  return (
    <button onClick={sendPasscode}>
      Send passcode
    </button>
  );
};

RESPONSE

200
{
      "status_code": 200,
      "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
      "method_id": "phone-number-test-d5a3b680-e8a3-40c0-b815-ab79986666d0"
    }
Send via SMS

The Send method wraps Stytch's send via SMS API endpoint. Call this method to send an SMS passcode to existing users. This method requires that the user already exist within Stytch before a magic link may be sent. This method is useful for gating your login flow to only pre-created users, e.g. an invite or waitlist.

This method is also used when you need to add a phone number to an existing Stytch User. If there is a currently valid Stytch session, and the user inputs a phone number that does not match one on their Stytch User object, upon successful authentication the new phone number will be added to the existing user. Note, this does expose a potential account enumeration vector, see our article on preventing account enumeration for more details.

Method parameters


phone_number*string

The phone number of the user to send a one-time passcode.The phone number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, see Testing for more detail.


Configurationobject

Additional configuration.

Collapse


expiration_minutesint

Set the expiration for the one-time passcode, in minutes. The minimum expiration is 1 minute and the maximum is 10 minutes. The default expiration is 2 minutes.

Example

Vanilla
import React, { useCallback } from 'react';
import { useStytch } from '@stytch/react-native';
export const Login = () => {
  const stytchClient = useStytch();
  const sendPasscode = useCallback(() => {
    stytchClient.otps.sms.send('+12025550162', {
      expiration_minutes: 5,
    });
  }, [stytchClient]);
  return (
    <button onClick={sendPasscode}>
      Send passcode
    </button>
  );
};

RESPONSE

200
{
      "status_code": 200,
      "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
      "method_id": "phone-number-test-d5a3b680-e8a3-40c0-b815-ab79986666d0"
    }
Login Or Create via email

The Login or create method wraps Stytch's login_or_create via email API endpoint. Call this method to send an email passcode to new or existing users.

Method parameters


email*string

The email address of the user to send the one-time passcode to. You may use sandbox@stytch.com to test this endpoint, see Testing for more detail.


Configurationobject

Additional configuration.

Collapse


expiration_minutesint

Set the expiration for the one-time passcode, in minutes. The minimum expiration is 1 minute and the maximum is 10 minutes. The default expiration is 2 minutes.

Example

Vanilla
import React, { useCallback } from 'react';
import { useStytch } from '@stytch/react-native';
export const Login = () => {
  const stytchClient = useStytch();
  const sendPasscode = useCallback(() => {
    stytchClient.otps.email.loginOrCreate('sandbox@stytch.com', {
      expiration_minutes: 5,
    });
  }, [stytchClient]);
  return (
    <button onClick={sendPasscode}>
      Send passcode
    </button>
  );
};

RESPONSE

200
{
      "status_code": 200,
      "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
      "method_id": "email-test-81bf03a8-86e1-4d95-bd44-bb3495224953"
    }
Send via email

The Send method wraps Stytch's send via email API endpoint. Call this method to send an email passcode to existing users. This method requires that the user already exist within Stytch before a magic link may be sent. This method is useful for gating your login flow to only pre-created users, e.g. an invite or waitlist.

This method is also used when you need to add an email address to an existing Stytch User. If there is a currently valid Stytch session, and the user inputs an email address that does not match one on their Stytch User object, upon successful authentication the new email address will be added to the existing user. Note, this does expose a potential account enumeration vector, see our article on preventing account enumeration for more details.

Method parameters


email*string

The email address of the user to send the one-time passcode to. You may use sandbox@stytch.com to test this endpoint, see Testing for more detail.


Configurationobject

Additional configuration.

Collapse


expiration_minutesint

Set the expiration for the one-time passcode, in minutes. The minimum expiration is 1 minute and the maximum is 10 minutes. The default expiration is 2 minutes.

Example

Vanilla
import React, { useCallback } from 'react';
import { useStytch } from '@stytch/react-native';
export const Login = () => {
  const stytchClient = useStytch();
  const sendPasscode = useCallback(() => {
    stytchClient.otps.email.send('sandbox@stytch.com', {
      expiration_minutes: 5,
    });
  }, [stytchClient]);
  return (
    <button onClick={sendPasscode}>
      Send passcode
    </button>
  );
};

RESPONSE

200
{
      "status_code": 200,
      "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
      "method_id": "email-test-81bf03a8-86e1-4d95-bd44-bb3495224953"
    }
Login Or Create via WhatsApp

The Login or create method wraps Stytch's login_or_create via WhatsApp API endpoint. Call this method to send a WhatsApp passcode to new or existing users.

Method parameters


phone_number*string

The phone number of the user to send a one-time passcode.The phone number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, see Testing for more detail.


Configurationobject

Additional configuration.

Collapse


expiration_minutesint

Set the expiration for the one-time passcode, in minutes. The minimum expiration is 1 minute and the maximum is 10 minutes. The default expiration is 2 minutes.

Example

Vanilla
import React, { useCallback } from 'react';
import { useStytch } from '@stytch/react-native';
export const Login = () => {
  const stytchClient = useStytch();
  const sendPasscode = useCallback(() => {
    stytchClient.otps.whatsapp.loginOrCreate('+12025550162', {
      expiration_minutes: 5,
    });
  }, [stytchClient]);
  return (
    <button onClick={sendPasscode}>
      Send passcode
    </button>
  );
};

RESPONSE

200
{
      "status_code": 200,
      "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
      "method_id": "phone-number-test-d5a3b680-e8a3-40c0-b815-ab79986666d0"
    }
Send via WhatsApp

The Send method wraps Stytch's send via WhatsApp API endpoint. Call this method to send a WhatsApp passcode to existing users. This method requires that the user already exist within Stytch before a magic link may be sent. This method is useful for gating your login flow to only pre-created users, e.g. an invite or waitlist.

This method is also used when you need to add a phone number to an existing Stytch User. If there is a currently valid Stytch session, and the user inputs a phone number that does not match one on their Stytch User object, upon successful authentication the new phone number will be added to the existing user. Note, this does expose a potential account enumeration vector, see our article on preventing account enumeration for more details.

Method parameters


phone_number*string

The phone number of the user to send a one-time passcode.The phone number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, see Testing for more detail.


Configurationobject

Additional configuration.

Collapse


expiration_minutesint

Set the expiration for the one-time passcode, in minutes. The minimum expiration is 1 minute and the maximum is 10 minutes. The default expiration is 2 minutes.

Example

Vanilla
import React, { useCallback } from 'react';
import { useStytch } from '@stytch/react-native';
export const Login = () => {
  const stytchClient = useStytch();
  const sendPasscode = useCallback(() => {
    stytchClient.otps.whatsapp.send('+12025550162', {
      expiration_minutes: 5,
    });
  }, [stytchClient]);
  return (
    <button onClick={sendPasscode}>
      Send passcode
    </button>
  );
};

RESPONSE

200
{
      "status_code": 200,
      "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
      "method_id": "phone-number-test-d5a3b680-e8a3-40c0-b815-ab79986666d0"
    }
Authenticate

The authenticate method wraps the authenticate one-time passcode API method which validates the code passed in. If this method succeeds, the user will be logged in, granted an active session, and the session data will be persisted on device.

You can listen for successful login events anywhere in the codebase with the stytch.session.onChange() method or useStytchSession hook.

Method parameters


method_id*string

The ID of the method used to send a one-time passcode.


code*string

The code to authenticate.


Configuration*object

Additional configuration.

Collapse

session_duration_minutes*int

Set the session lifetime to be this many minutes from now. This will return both an opaque session_token and session_jwt for this session, which will automatically be stored in the browser cookies. The session_jwt will have a fixed lifetime of five minutes regardless of the underlying session duration, and will be automatically refreshed by the SDK in the background over time.

This value must be a minimum of 5 and may not exceed the maximum session duration minutes value set in the SDK Configuration page of the Stytch dashboard.

A successful authentication will continue to extend the session this many minutes.

Example

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

export const Authenticate = () => {
  const stytchClient = useStytch();
  const [code, setCode] = useState('');
  
  const method_id = "phone-number-test-d5a3b680-e8a3-40c0-b815-ab79986666d0"
  // returned from calling loginOrCreate for OTPs on SMS, WhatsApp or Email

  const authenticate = useCallback((e) => {
    e.preventDefault();
    stytchClient.otps.authenticate(code, method_id, {
      session_duration_minutes: 60,
    });
  }, [stytchClient, code]);

  const handleChange = useCallback((e) => {
    setCode(e.target.value);
  }, []);

  return (
    <form>
      <label for="otp-input">Enter code</label>
      <input
        id="otp-input"
        autocomplete="one-time-code"
        inputtype="numeric"
        pattern="[0-9]*"
        onChange={handleChange}
      />
      <button onClick={authenticate} type="submit">
        Submit
      </button>
    </form>
  );
};

RESPONSE

200
{
  "status_code": 200,
  "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
  "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
  "session_token": "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q",
  "session_jwt": "eyJ...",
  "session": {...},
  "method_id": "phone-number-test-d5a3b680-e8a3-40c0-b815-ab79986666d0",
}


Passwords

The React Native SDK provides methods for creating, storing, and authenticating password based users, as well as support for account recovery (password reset) and account deduplication with passwordless login methods.

Methods

The SDK provides methods that can be used to create and authenticate users with a password authentication factor.

To call these methods, Passwords must be enabled in the SDK Configuration page of the Stytch dashboard.

Create

The create method wraps the create Password API endpoint.


email*string

The email of the new user.


password*string

The password for the new user.


session_duration_minutes*int

Set the session lifetime to be this many minutes from now. This will return both an opaque session_token and session_jwt for this session, which will automatically be stored in the browser cookies. The session_jwt will have a fixed lifetime of five minutes regardless of the underlying session duration, and will be automatically refreshed by the SDK in the background over time.

This value must be a minimum of 5 and may not exceed the maximum session duration minutes value set in the SDK Configuration page of the Stytch dashboard.

A successful authentication will continue to extend the session this many minutes.

Example

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

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

  const createPassword = useCallback(() => {
    stytchClient.passwords.create({
      email: example@domain.com,
      password: skME)rbNQ$4@e9c&,
      session_duration_minutes: 60,
    });
  }, [stytchClient]);

  return (
    <button onClick={createPassword}>
      Create Password
    </button>
  );
};

RESPONSE

200
{
  "status_code": 200,
  "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
  "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
  "email_id": "email-test-81bf03a8-86e1-4d95-bd44-bb3495224953"
}
Authenticate

The authenticate method wraps the authenticate Password API endpoint. If this method succeeds, the user will be logged in, granted an active session, and the session data will be persisted on device.

You can listen for successful login events anywhere in the codebase with the stytch.session.onChange() method or useStytchSession hook.


email*string

The email of the user.


password*string

The password of the user.


session_duration_minutes*int

Set the session lifetime to be this many minutes from now. This will return both an opaque session_token and session_jwt for this session, which will automatically be stored in the browser cookies. The session_jwt will have a fixed lifetime of five minutes regardless of the underlying session duration, and will be automatically refreshed by the SDK in the background over time.

This value must be a minimum of 5 and may not exceed the maximum session duration minutes value set in the SDK Configuration page of the Stytch dashboard.

A successful authentication will continue to extend the session this many minutes.

Example

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

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

  const authenticatePassword = useCallback(() => {
    stytchClient.passwords.authenticate({
      email: example@domain.com,
      password: skME)rbNQ$4@e9c&,
      session_duration_minutes: 60,
    });
  }, [stytchClient]);

  return (
    <button onClick={authenticatePassword}>
      Authenticate Password
    </button>
  );
};

RESPONSE

200
{
  "status_code": 200,
  "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
  "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6"
}
Reset By Email Start

The resetByEmailStart method wraps the reset_by_email_start Password API endpoint. If this method succeeds, the user will be logged in, granted an active session, and the session data will be persisted on device.

You can listen for successful login events anywhere in the codebase with the stytch.session.onChange() method or useStytchSession hook.


email*string

The email of the user that requested the password reset.


Configurationobject

Additional configuration.

Collapse


reset_password_redirect_urlstring

The url that the user clicks from the password reset email to finish the reset password flow. This should be a url that your app receives and parses before showing your app's reset password page. After the user submits a new password to your app, it should send an API request to complete the password reset process. If this value is not passed, the default reset password redirect URL that you set in your Dashboard is used. If you have not set a default reset password redirect URL, an error is returned.


login_redirect_urlstring

The url that the user clicks from the password reset email to skip resetting their password and directly login. This should be a url that your app receives, parses, and subsequently sends an API request to the magic link authenticate endpoint to complete the login process without reseting their password. If this value is not passed, the login redirect URL that you set in your Dashboard is used. If you have not set a default login redirect URL, an error is returned.,


reset_password_expiration_minutesint

Set the expiration for the password reset, in minutes. By default, it expires in 30 minutes. The minimum expiration is 5 minutes and the maximum is 7 days (10080 mins).

Example

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

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

  const resetPasswordStart = useCallback(() => {
    stytchClient.passwords.resetByEmailStart({
      email: example@domain.com,
    });
  }, [stytchClient]);

  return (
    <button onClick={resetPasswordStart}>
      Reset Password Start
    </button>
  );
};

RESPONSE

200
{
  "status_code": 200,
  "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
  "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
  "email_id": "email-test-81bf03a8-86e1-4d95-bd44-bb3495224953"
}
Reset By Email

The resetByEmail method wraps the reset_by_email Password API endpoint. If this method succeeds, the user will be logged in, granted an active session, and the session data will be persisted on device.

You can listen for successful login events anywhere in the codebase with the stytch.session.onChange() method or useStytchSession hook.


password*string

The new password for the user.


session_duration_minutes*int

Set the session lifetime to be this many minutes from now. This will return both an opaque session_token and session_jwt for this session, which will automatically be stored in the browser cookies. The session_jwt will have a fixed lifetime of five minutes regardless of the underlying session duration, and will be automatically refreshed by the SDK in the background over time.

This value must be a minimum of 5 and may not exceed the maximum session duration minutes value set in the SDK Configuration page of the Stytch dashboard.

A successful authentication will continue to extend the session this many minutes.

Example

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

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

  const token = new URLSearchParams(window.location.search).get('token');

  const resetPassword = useCallback(() => {
    stytchClient.passwords.resetByEmail({
      token: token,
      password: skME)rbNQ$4@e9c&,
      session_duration_minutes: 60,
    });
  }, [stytchClient, token]);

  return (
    <button onClick={resetPassword}>
      Reset Password
    </button>
  );
};

RESPONSE

200
{
  "status_code": 200,
  "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
  "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6"
}
Strength Check

The strengthCheck method wraps the strength_check Password API endpoint. If this method succeeds, the user will be logged in, granted an active session, and the session data will be persisted on device.

You can listen for successful login events anywhere in the codebase with the stytch.session.onChange() method or useStytchSession hook.


password*string

The password to strength check.


emailstring

The email associated with the password. Provide this for a more accurate strength check.


session_duration_minutes*int

Set the session lifetime to be this many minutes from now. This will return both an opaque session_token and session_jwt for this session, which will automatically be stored in the browser cookies. The session_jwt will have a fixed lifetime of five minutes regardless of the underlying session duration, and will be automatically refreshed by the SDK in the background over time.

This value must be a minimum of 5 and may not exceed the maximum session duration minutes value set in the SDK Configuration page of the Stytch dashboard.

A successful authentication will continue to extend the session this many minutes.

Example

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

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

  const createPassword = useCallback(() => {
    stytchClient.passwords.strengthCheck({
      email: example@domain.com,
      password: skME)rbNQ$4@e9c&,
    });
  }, [stytchClient]);

  return (
    <button onClick={strengthCheck}>
      Strength Check
    </button>
  );
};

RESPONSE

200
{
  "status_code": 200,
  "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
  "valid_password": true,
  "score": 4,
  "breached_password": false,
  "feedback": {
    "suggestions": [],
    "warning": ""
  }
}

Users

Once a user has successfully logged in, the SDK can be used to view and manage that user's information, add additional authentication factors, or delete factors that are no longer used.

Methods

To call these methods, Manage user data must be enabled in the SDK Configuration page of the Stytch dashboard.

Get user

The SDK provides two 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.

If logged in, the user.getSync method returns the cached user object. Otherwise it returns null. This method does not refresh the user's data. The @stytch/react-native and @stytch/react-native-expo libraries provide the useStytchUser hook that implements these methods for you to easily access the user and listen for changes.

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.

The asyncronous 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.

Example

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

export const Home = () => {
  const stytchUser = useStytchUser();

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

Wraps Stytch's update user endpoint. Use this method to change the user's name, untrusted metadata, and attributes.

You can listen for successful user updates anywhere in the codebase with the stytch.user.onChange() method or useStytchUser() hook.

Note: If a user has enrolled another MFA method, this method will require MFA. See the Multi-factor authentication section for more details.

Method parameters


nameobject

The name of the user. If at least one name field is passed, all name fields will be updated.

Collapse

first_namestring

The first name of the user. Replaces an existing first name, if it exists.

middle_namestring

The middle name(s) of the user. Replaces an existing middle name, if it exists.

last_namestring

The last name of the user. Replaces an existing last name, if it exists.


untrusted_metadataobject

The untrusted_metadata field contains an arbitrary JSON object of application-specific data. Untrusted metadata can be edited by end users directly via the SDK, and cannot be used to store critical information. See the Metadata reference for complete field behavior details.

Example

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

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

  const updateName = useCallback(() => {
    stytchClient.user.update({
      name: {
        first_name: 'Jane',
        last_name: 'Doe',
      },
      untrusted_metadata: {
        display_theme: 'DARK_MODE',
      }
    });
  }, [stytchClient]);


  return (
    <>
      <button onClick={updateName}>
        Update name
      </button>
    </>
  );
};

RESPONSE

200
{
  "emails": [
    {
      "email_id": "email-test-81bf03a8-86e1-4d95-bd44-bb3495224953",
      "email": "",
      "verified": false
    }
  ],
  "phone_numbers": [
    {
      "phone_id": "phone-number-test-d5a3b680-e8a3-40c0-b815-ab79986666d0",
      "phone_number": "+12025550162",
      "verified": false
    }
  ],
  "crypto_wallets": [
    {
      "crypto_wallet_id": "crypto-wallet-test-dbbd372e-79f8-48ea-907c-5f0755e7d328",
      "crypto_wallet_address": "0x6df2dB4Fb3DA35d241901Bd53367770BF03123f1",
      "crypto_wallet_type": "ethereum",
      "verified": true
    }
  ],
  "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
  "status_code": 200,
  "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
  "user": {...}
}
Delete authentication factors

Wraps Stytch's delete authentication factors family of endpoints and can be used to remove factors from a user.

These methods cannot be used to remove all factors from a user. A user must have at least one email, phone number, or OAuth provider associated with their account at all times, otherwise they will not be able to log in again.

You can listen for successful user updates anywhere in the codebase with the stytch.user.onChange() method or useStytchUser() hook.

Note: If a user has enrolled another MFA method, this method will require MFA. See the Multi-factor authentication section for more details.

Method parameters


method_id*string

ID of the email, phone number, or WebAuthn registeration to be deleted.

Example

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

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

  const deleteEmail = useCallback(() => {
    stytchClient.user.deleteEmail('email-test-81bf03a8-86e1-4d95-bd44-bb3495224953');
  }, [stytchClient]);

  const deletePhoneNumber = useCallback(() => {
    stytchClient.user.deletePhoneNumber('phone-number-test-d5a3b680-e8a3-40c0-b815-ab79986666d0');
  }, [stytchClient]);

  const deleteWebauthnRegistration = useCallback(() => {
    stytchClient.user.deleteWebauthnRegistration('webauthn-registration-test-5c44cc6a-8af7-48d6-8da7-ea821342f5a6');
  }, [stytchClient]);

  return (
    <>
      <button onClick={deleteEmail}>
        Delete email
      </button>
      <button onClick={deletePhoneNumber}>
        Delete phone number
      </button>
      <button onClick={deleteWebauthnRegistration}>
        Delete WebAuthn registration
      </button>
    </>
  );
};

RESPONSE

200
{
  "status_code": 200,
  "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
  "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
  "user": {...}
}

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 server-side library.

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 @stytch/react-native and @stytch/react-native-expo libraries provide the useStytchSession hook that implements these methods for you to easily access the session and listen for changes.

The session.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.

Example

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

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

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

  if (!stytchSession || stytchSession.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


Configuration*object

Additional configuration.

Collapse

session_duration_minutes*int

Set the session lifetime to be this many minutes from now. This will return both an opaque session_token and session_jwt for this session, which will automatically be stored in the browser cookies. The session_jwt will have a fixed lifetime of five minutes regardless of the underlying session duration, and will be automatically refreshed by the SDK in the background over time.

This value must be a minimum of 5 and may not exceed the maximum session duration minutes value set in the SDK Configuration page of the Stytch dashboard.

A successful authentication will continue to extend the session this many minutes.

Example

Vanilla
import React, { useEffect } from 'react';
import { useStytch } from '@stytch/react-native';

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 null;
};

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",
        "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",
  },
  "user": {...},
  "session_jwt": "example_jwt"
  "session_token": "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q"
}
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.

Example

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

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"
}