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.
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'),
);
Email Magic Links
The JavaScript SDK provides a pre-built UI to trigger Email Magic Links, and methods to send and authenticate magic links that you can connect to your own UI. Use either of these approaches to quickly get up and running with magic links.
Methods
The SDK provides methods that can be used to send magic links and authenticate tokens in the links later.
To call these methods, Email Magic Links must be enabled in the SDK Configuration page of the Stytch dashboard.
Login or signup
The Login or signup method wraps the login_or_signup Email Magic Link API endpoint.
Method parameters
organization_id*string
Globally unique UUID that identifies a specific Organization. The organization_id is critical to perform operations on an Organization, so be sure to preserve this value.
email_address*string
The email address of the Member.
login_redirect_urlstring
The URL that the Member clicks from the login Email Magic Link. This URL should be an endpoint in the backend server that verifies the request by querying Stytch's authenticate endpoint and finishes the login. If this value is not passed, the default 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.
signup_redirect_urlstring
The URL the Member clicks from the signup Email Magic Link. This URL should be an endpoint in the backend server that verifies the request by querying Stytch's authenticate endpoint and finishes the login. If this value is not passed, the default sign-up redirect URL that you set in your Dashboard is used. If you have not set a default sign-up redirect URL, an error is returned.
pkce_code_challengestring
A base64url encoded SHA256 hash of a one time secret used to validate that the request starts and ends on the same device.
login_template_idstring
Use a custom template for login emails. By default, it will use your default email template. The template must be from Stytch's built-in customizations or a custom HTML email for Magic Links - Login.
signup_template_idstring
Use a custom template for signup emails. By default, it will use your default email template. The template must be a template using our built-in customizations or a custom HTML email for Magic Links - Signup.
The Authenticate method wraps the authenticate magic link API endpoint which validates the magic link 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
magic_links_token*string
The Email Magic Link token to authenticate.
session_tokenstring
Reuse an existing session instead of creating a new one. If you provide a session_token, Stytch will update the session. If the session_token and magic_links_token belong to different Members, the session_token will be ignored. This endpoint will error if both session_token and session_jwt are provided.
session_jwtstring
Reuse an existing session instead of creating a new one. If you provide a session_jwt, Stytch will update the session. If the session_jwt and magic_links_token belong to different Members, the session_jwt will be ignored. This endpoint will error if both session_token and session_jwt are provided.
session_duration_minutesint
Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't already exist, returning both an opaque session_token and session_jwt for this session. Remember that the session_jwt will have a fixed lifetime of five minutes regardless of the underlying session duration, and will need to be refreshed over time.
This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). If a session_token or session_jwt is provided then a successful authentication will continue to extend the session this many minutes. If the session_duration_minutes parameter is not specified, a Stytch session will not be created.
pkce_code_verifierstring
A base64url encoded one time secret used to validate that the request starts and ends on the same device.
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.
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.
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.
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.
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.
{
"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.