JavaScript SDK

The JavaScript SDK provides a customizable pre-built login form to start a login flow, along with methods that communicate directly with the Stytch API. These help you get up and running with Stytch faster by avoiding the struggles associated with creating a login UI and removing the need to create endpoints on your backend to make requests to Stytch.

Compatibility and requirements

Languages

The SDK is available in vanilla Javascript along with specialized versions for React.

Browsers

  • Chrome and Safari on all platforms
  • Firefox on desktop platforms
  • TLS 1.2 must be supported by the browser


Installation

Install the @stytch/vanilla-js, @stytch/react packages via npm or yarn.

npm install @stytch/vanilla-js @stytch/react --save

Initialize the SDK with the StytchHeadlessB2BClient constructor provided in the vanilla-js package.

Example

import { StytchB2BProvider } from '@stytch/react/b2b';
import { StytchHeadlessB2BClient } from '@stytch/vanilla-js/b2b';

const stytch = new StytchHeadlessB2BClient('PUBLIC_TOKEN');

// Wrap your App in the StytchProvider
ReactDOM.render(
  <StytchB2BProvider stytch={stytch}>
    <App />
  </StytchB2BProvider>,
  document.getElementById('root'),
);


Member

Once a member has successfully logged in, the SDK can be used to view and manage that member's information along with information about the organization they belong to.

Methods

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

Get Member

The SDK provides two methods for getting a user. The recommended approach is to use the synchronous method, organization.getMemberSync, and listen to changes with the organization.onMemberChange method.

If logged in, the organization.getMemberSync method returns the cached member object. Otherwise it returns null. This method does not refresh the member's data. The @stytch/react library provides the useStytchMember hook that implements these methods for you to easily access the user and listen for changes.

The organization.onMemberChange 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, organization.getMember, wraps the search member endpoint. It fetches the member'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

React
import React from 'react';
import { useStytchMember } from '@stytch/react/b2b';

export const Home = () => {
  const { member } = useStytchMember();

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

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 @stytch/react library provides the useStytchMemberSession 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 Member Session object changes. It returns an unsubscribe method for you to call when you no longer want to listen for such changes.

Example

React
import React from 'react';
import { useStytchMemberSession } from '@stytch/react/b2b';

export const Home = () => {
  const { member_session } = useStytchMemberSession();

  return member_session ? (
    <p> Member Session ID: {member_session.member_session_id}</p>
  ) : (
    <p> No Active Session </p>
  );
};
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


session_tokenstring

A secret token for a given Stytch Session. Read more about session_token in our Session Management guide.


session_jwtstring

The JSON Web Token (JWT) for a given Stytch Session. Read more about session_jwt in our Session Management guide.


session_duration_minutesint

The Session lifetime of this many minutes from now; minimum of 5 and a maximum of 129600 minutes (90 days). Note that a successful authentication will continue to extend the Session this many minutes.


session_custom_claimsobject

Add a custom claims map to the Session being authenticated. Claims are only created if a Session is initialized by providing a value in session_duration_minutes. Claims will be included on the Session object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, supply a null value. Custom claims made with reserved claims (iss, sub, aud, exp, nbf, iat, jti) will be ignored. Total custom claims size cannot exceed four kilobytes.

Example

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

export const RefreshSession = () => {
  const stytch = useStytchB2BClient();

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

  return <></>;
};

RESPONSE

200
{
	"status_code": 200,
	"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
	"member_session": {...},
	"session_token": "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q",
	"session_jwt": "",
	"member": {...},
	"organization": {...}
}
Revoke session

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

Example

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

export const LogOutButton = () => {
  const stytch = useStytchB2BClient();

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

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

RESPONSE

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

SSO

SSO (or Single Sign On) refers to a number of popular authentication frameworks that delegate authentication to an external identity provider (often shortened to IdP) like Okta, Google, or ForgeRock. These external identity providers are owned and managed by IT admins. A user relies on their membership from that provider to sign in instead of creating another password, and developers can enrich their users' experiences with the information shared by the providers.

The Javascript SDK provides methods to start and authenticate SSO flows that you cann connect to your own UI.

Methods

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

Start SSO Flow

Method parameters

The sso.start() method stars a SSO flow by redirecting the browser to Stytch's SSO Start endpoint. The method will also generate a PKCE code_verifier and store it in localstorage on the device.


connection_id*string

The ID of the SSO connection to use for the login flow.


login_redirect_urlstring

The URL Stytch redirects to after the SSO flow is completed for a Member that already exists. This URL should be a route in your application which will run sso.authenticate (see below) and finish the login.

The URL must be configured as a Login URL in the Redirect URL page. If the field is not specified, the default Login URL will be used.


signup_redirect_urlstring

The URL Stytch redirects to after the SSO flow is completed for a Member that does not yet exist. This URL should be a route in your application which will run sso.authenticate (see below) and finish the login.

The URL must be configured as a Sign Up URL in the Redirect URL page. If the field is not specified, the default Sign Up URL will be used.

Example

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

export const Login = () => {
  const stytchClient = useStytchB2BClient();
  
  const startSSO = () => stytchClient.sso.start({
      connection_id: 'saml-connection-test-51861cbc-d3b9-428b-9761-227f5fb12be9',
      login_redirect_url: 'https://example.com/authenticate',
      signup_redirect_url: 'https://example.com/authenticate'
  });

  return (
    <button onClick={startSSO}>
      Log in with Okta
    </button>
  );
};
Authenticate

The authenticate method wraps the authenticate SSO API endpoint which validates the SSO token passed in. If this method succeeds, the user will be logged in, granted an active session, and the session cookies will be minted and stored in the browser.

You can listen for successful login events anywhere in the codebase with the stytch.session.onChange() method or useStytchMemberSession hook if you are using React.

Method parameters


sso_token*string

The token to authenticate.


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

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

export const Authenticate = () => {
  const stytchClient = useStytchB2BClient();
  const { session } = useStytchMemberSession();

  useEffect(() => {
    if (session) {
      window.location.href = 'https://example.com/profile'
    } else {
      const token = new URLSearchParams(window.location.search).get('token');
      stytchClient.sso.authenticate({
        sso_token: token,
        session_duration_minutes: 60,
      });
    }
  }, [stytchClient, session]);

  return <div>Loading</div>;
};

RESPONSE

200
{
  "status_code": 200,
  "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
  "member_id": "member-test-32fc5024-9c09-4da3-bd2e-c9ce4da9375f",
  "organization_id": "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931",
  "session_token": "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q",
  "session_jwt": "eyJ...",
  "session": {...},
  "member": {...},
  "organization": {...},
}

Resources

Stytch Client Options

The Stytch Client can be configured by passing in an optional object as the second parameter. This currently lets developers configure options related to the cookies set by Stytch's SDK.

Stytch automatically saves the user's session in two cookies: stytch_session that will contain the opaque session token returned from the API and stytch_session_jwtthat will contain the session JWT returned from the API.

import { StytchHeadlessB2BClient } from "@stytch/vanilla-js/b2b"

const STYTCH_PUBLIC_TOKEN = 'YOUR_PUBLIC_TOKEN'; 

const stytchOptions = {
  cookieOptions: {
    opaqueTokenCookieName: "my_stytch_session",
    jwtCookieName: "my_stytch_session_jwt",
    path: "/"
    availableToSubdomains: false,
  }
}

const stytchClient = new StytchHeadlessB2BClient(STYTCH_PUBLIC_TOKEN, stytchOptions)

Options

{
 "cookieOptions": {
    /**
     * The name of the cookie containing the opaque Stytch session token.
     * Defaults to `stytch_session`
     */
    "opaqueTokenCookieName": "string",

    /**
     * The name of the cookie containing the opaque Stytch session token.
     * Defaults to `stytch_session_jwt`
     */
    "jwtCookieName": "string",

    /**
     * What HTTP paths the cookies should be available on.
     * Equal to configuring the `;path=${}` param in the set-cookie directive.
     * Defaults to unset.
     */
    "path": "string",

    /**
     * Whether to make the cookies available to subdomains.
     * When true, equivalent to configuring the `;domain=${window.location.host}` directive
     * When false, equivalent to leaving the directive unset
     * Defaults to true.
     */
    "availableToSubdomains": "boolean",
  }
}

SWR & caching

On first load, many websites must make a network request to determine whether a member is logged in before the site can start rendering the user interface. This slows down users' ability to interact with the application and ultimately leaves them with a sluggish experience.

Stytch JavaScript SDK embraces stale-while-revalidate (SWR) - a caching and data fetching strategy that promises faster time-to-interactivity and snappier UX. While SWR is most closely associated with React, the principles can apply to any web application.

Here's how it works:

  • The page first loads. Stytch's SDK checks cached data to determine if a member has logged in previously on the same device, and returns that data to your app immediately.
  • Stytch's SDK refreshes the user's data in the background while your app starts.
  • Your app makes requests to your backend to pull in application-specific data. Your backend validates the session stored in the request's cookies, and then completes the request.
  • In the rare case that the user's session has been terminated from another device, your backend will fail the request and return a 401 error. The Stytch SDK will also notify your app that the session is no longer valid through the useStytchMember and useStytchMemberSession hooks or HOCs.

If a SWR approach isn't right for you, you can explicitly call stytch.organization.getMember() to refresh the user object with a network call, and/or stytch.session.authenticate() to make sure the user is still logged in.