Client-side SDKs
Use a client-side SDK to quickly build your user authentication on web and mobile. Looking for language-specific wrappers for our backend API? Check out our client libraries.
Use a client-side SDK to quickly build your user authentication on web and mobile. Looking for language-specific wrappers for our backend API? Check out our client libraries.
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.
To load the Stytch JavaScript SDK, we recommend adding
<script src="https://js.stytch.com/stytch.js"></script>
in your the document header to load the SDK synchronously. If you prefer to defer loading Stytch, see the Async & deferred loading section below.
Install the @stytch/stytch-react package via npm or yarn.
npm install @stytch/stytch-react --save
Initialize the SDK with the initStytch helper method provided in this package. We recommend storing the created client instance in a common file to use it in JavaScript methods such as in Redux actions.
initStytch parameters
Provide the public token from the Stytch dashboard. This value is safe to embed client side.
Use this value in the StytchProvider to have access to Stytch's hooks and React components. We recommend adding this to the top level of your application to easily use Stytch anywhere in your application.
StytchProvider props
Provide the return value from the initStytch function.
Example
import { StytchProvider, initStytch } from '@stytch/stytch-react';
const stytch = initStytch('PUBLIC_TOKEN');
const _app = () => {
return (
<StytchProvider stytch={stytch}>
<Component />
</StytchProvider>
);
};
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.
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.
The send method wraps the login_or_create Email magic link API endpoint.
Method parameters
The email of the user to send the invite magic link to.
Additional configuration.
Collapse
The url the user clicks from the login email magic link. This should be a url that your app receives and parses and subsequently send an API request to authenticate the magic link and log in the user. 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.
The url the user clicks from the sign-up email magic link. This should be a url that your app receives and parses and subsequently send an api request to authenticate the magic link and sign-up the user. 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.
Set the expiration for the login email magic link, in minutes. By default, it expires in 1 hour. The minimum expiration is 5 minutes and the maximum is 7 days (10080 mins).
Set the expiration for the sign-up email magic link, in minutes. By default, it expires in 1 week. The minimum expiration is 5 minutes and the maximum is 7 days (10080 mins).
Example
import { useStytch } from '@stytch/stytch-react';
export const Login = () => {
const stytchClient = useStytch();
const sendEmailMagicLink = () => {
stytchClient.magicLinks.email.loginOrCreate('sandbox@stytch.com', {
login_magic_link_url: 'https://example.com/authenticate',
login_expiration_minutes: 60,
signup_magic_link_url: 'https://example.com/authenticate',
signup_expiration_minutes: 60,
});
};
return (
<button onClick={sendEmailMagicLink}>
Send email
</button>
);
};
RESPONSE
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141"
}
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 useStytchSession hook if you are using React.
Method parameters
The magic link token from the token query parameter in the URL.
Additional configuration.
Collapse
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.
If a session_token or session_jwt is provided then a successful authentication will continue to extend the session this many minutes.
Example
import React, { useEffect } from 'react';
import { useStytch, useStytchSession } from '@stytch/stytch-react';
export const Authenticate = () => {
const stytchClient = useStytch();
const session = useStytchSession();
useEffect(() => {
if (session) {
window.location.href = 'https://example.com/profile'
} else {
const token = new URLSearchParams(window.location.search).get('token');
stytchClient.magicLinks.authenticate(token, {
session_duration_minutes: 60,
});
}
}, [stytchClient, session]);
return <div>Loading</div>;
};
RESPONSE
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
"method_id": "email-test-81bf03a8-86e1-4d95-bd44-bb3495224953",
"session_token": "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q",
"session_jwt": "eyJ...",
"session": {...},
}
The SDK also comes with a pre-built UI component for our Email magic links product. It wraps our login_or_create Email magic link API endpoint, which finds an existing user or creates a new user and sends them an email magic link.
To add Email magic links to the login UI, add SDKProductTypes.emailMagicLinks to the products array in the configuration and the appropriate emailMagicLinksOptions.
To see all authentication and customization options, see the UI config section below.
Example
import React from 'react';
import { Stytch, SDKProductTypes } from '@stytch/stytch-react';
const loginOrSignupViewConfig = {
emailMagicLinksOptions: {
createUserAsPending: true,
loginExpirationMinutes: 30,
loginRedirectURL: 'https://example.com/authenticate',
signupExpirationMinutes: 30,
signupRedirectURL: 'https://example.com/authenticate',
},
products: [
SDKProductTypes.emailMagicLinks,
],
};
export const Login = () => {
const STYTCH_PUBLIC_TOKEN = 'PUBLIC_TOKEN';
return (
<div className="sign-in-container">
<Stytch
loginOrSignupView={loginOrSignupViewConfig}
// Include publicToken if you're not using <StytchProvider>
publicToken={STYTCH_PUBLIC_TOKEN}
/>
</div>
);
};
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.
To call these methods, One-time passcodes must be enabled in the SDK Configuration page of the Stytch dashboard.
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
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.
Additional configuration.
Collapse
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
import React, { useCallback } from 'react';
import { useStytch } from '@stytch/stytch-react';
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
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"method_id": "phone-number-test-d5a3b680-e8a3-40c0-b815-ab79986666d0"
}
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
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.
Additional configuration.
Collapse
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
import React, { useCallback } from 'react';
import { useStytch } from '@stytch/stytch-react';
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
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"method_id": "email-test-81bf03a8-86e1-4d95-bd44-bb3495224953"
}
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
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.
Additional configuration.
Collapse
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
import React, { useCallback } from 'react';
import { useStytch } from '@stytch/stytch-react';
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
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"method_id": "phone-number-test-d5a3b680-e8a3-40c0-b815-ab79986666d0"
}
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 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 useStytchSession hook if you are using React.
Method parameters
The ID of the method used to send a one-time passcode.
The code to authenticate.
Additional configuration.
Collapse
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.
If a session_token or session_jwt is provided then a successful authentication will continue to extend the session this many minutes.
Example
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
{
"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",
}
OAuth is a popular authentication framework that delegates authentication to an external identity provider (often shortened to IdP) like Google, Facebook, Apple, and Microsoft. 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 a pre-built UI for OAuth flows, as well as methods to start and authenticate OAuth flows that you can connect to your own UI. Use either of these approaches to quickly get up and running with OAuth.
The SDK provides methods that can be used to get the URL to start an OAuth flow and authenticate tokens in the links later.
To call these methods, OAuth must be enabled in the SDK Configuration page of the Stytch dashboard.
The get URL methods return the URL to start OAuth flows. The following methods are available
Method parameters
Additional configuration.
Collapse
The URL that Stytch redirects to after the OAuth flow is completed for a user that already exists. This URL should be an endpoint in the backend server that verifies the request by querying Stytch's /oauth/authenticate endpoint and finishes the login. The URL should be configured as a Login URL in the Stytch Dashboard's Redirect URL page. If the field is not specified, the default in the Dashboard is used.
The URL that Stytch redirects to after the OAuth flow is completed for a user that does not yet exist. This URL should be an endpoint in the backend server that verifies the request by querying Stytch's /oauth/authenticate endpoint and finishes the login. The URL should be configured as a Sign Up URL in the Stytch Dashboard's Redirect URL page. If the field is not specified, the default in the Dashboard is used.
An optional list of custom scopes that you'd like to request from the user in addition to the ones Stytch requests by default.
Example
import { useStytch } from '@stytch/stytch-react';
export const Login = () => {
const stytchClient = useStytch();
return (
<a href={stytchClient.oauth.google.getUrl({
login_redirect_url: 'https://example.com/authenticate',
signup_redirect_url: 'https://example.com/authenticate',
custom_scopes: [
'https://www.googleapis.com/auth/documents.readonly',
'https://www.googleapis.com/auth/drive.readonly'
],
})}>
Log in with Google
</a>
);
};
The authenticate method wraps the authenticate OAuth API endpoint which validates the OAuth 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 useStytchSession hook if you are using React.
Method parameters
The OAuth token from the token query parameter in the URL.
Additional configuration.
Collapse
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.
If a session_token or session_jwt is provided then a successful authentication will continue to extend the session this many minutes.
Example
import React, { useEffect } from 'react';
import { useStytch, useStytchSession } from '@stytch/stytch-react';
export const Authenticate = () => {
const stytchClient = useStytch();
const session = useStytchSession();
useEffect(() => {
if (session) {
window.location.href = 'https://example.com/profile';
return;
}
const token = new URLSearchParams(window.location.search).get('token');
stytchClient.oauth.authenticate(token, {
session_duration_minutes: 60,
});
}, [stytchClient, session]);
return <div>Loading</div>;
};
RESPONSE
{
"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": {...},
"provider_subject": "10769150350006150715113082367",
"provider_type": "Google"
}
Our Javascript SDK wraps our start OAuth endpoint which kicks off the OAuth flow for your users. You'll want to set up each OAuth provider in your Dashboard before using it in the SDK. The SDK supports Google, Google One Tap, Microsoft, Github, GitLab, Facebook, Discord, Slack, and Apple OAuth.
To add OAuth to the login UI, add SDKProductTypes.oauth to the products array in the configuration and the appropriate oauthOptions.
To see all authentication and customization options, see the UI config section below.
Example
import React from 'react';
import { Stytch, SDKProductTypes, OAuthProvidersTypes, OneTapPositions } from '@stytch/stytch-react';
const loginOrSignupViewConfig = {
oauthOptions: {
loginRedirectURL: 'https://example.com/authenticate',
signupRedirectURL: 'https://example.com/authenticate',
providers: [
{
one_tap: true,
position: OneTapPositions.embedded,
type: OAuthProvidersTypes.Google,
},
{
type: OAuthProvidersTypes.Apple,
},
{
type: OAuthProvidersTypes.Discord,
},
{
type: OAuthProvidersTypes.Facebook,
custom_scopes: ['user_photos'],
},
{
type: OAuthProvidersTypes.Github,
custom_scopes: ['gist'],
},
{
type: OAuthProvidersTypes.GitLab,
},
{
type: OAuthProvidersTypes.Microsoft,
custom_scopes: ['https://graph.microsoft.com/calendars.read'],
},
{
type: OAuthProvidersTypes.Slack,
},
],
},
products: [
SDKProductTypes.oauth,
],
};
export const Login = () => {
const STYTCH_PUBLIC_TOKEN = 'PUBLIC_TOKEN';
return (
<div className="sign-in-container">
<Stytch
loginOrSignupView={loginOrSignupViewConfig}
// Include publicToken if you're not using <StytchProvider>
publicToken={STYTCH_PUBLIC_TOKEN}
/>
</div>
);
};
The Web Authentication API (WebAuthn) is a specification that allows web applications on supported browsers to authenticate a user via authenticator types such as built-in device biometrics (e.g. facial recognition on mobile and fingerprint readers on desktop) or secure hardware keys (e.g. YubiKeys). While WebAuthn has many benefits, developers need to understand the API to implement it securely. Stytch's WebAuthn product simplifies the process by abstracting the implementation details of WebAuthn for developers to make it as quick as possible to implement securely.
The Stytch SDK can be used to create new WebAuthn registrations for users, and authenticate existing WebAuthn registrations.
To call these methods, WebAuthn must be enabled in the SDK Configuration page of the Stytch dashboard.
Wraps Stytch's register_start and register WebAuthn endpoints and the navigator.credentials web API. Call this method to prompt the user to enroll a new WebAuthn factor and save the factor in Stytch.
You should preload the public key data by calling webauthn.registerStart when the authentication flow first starts. Call webauthn.register inside an event callback triggered by a user gesture. Otherwise, newer versions of Safari will not allow your website access to the WebAuthn API.
You can listen for successful user updates anywhere in the codebase with the stytch.user.onChange() method or useStytchUser() hook if you are using React.
Note: If a user has enrolled another MFA method, this method will require MFA. See the Multi-factor authentication section for more details.
webauthn.registerStart parameters
The domain for the WebAuthn registration. Defaults to window.location.hostname
The requested authenticator type of the WebAuthn device. The two valid value are platform and cross-platform. If no value passed, we assume both values are allowed.
webauthn.register parameters
The public_key_credential_creation_options value from the webauthn.registerStart response.
Example
import React, { useCallback, useEffect, useState } from 'react';
import { useStytch } from '@stytch/stytch-react';
export const Login = () => {
const stytchClient = useStytch();
const [webauthnCreds, setWebauthnCreds] = useState();
useEffect(() => {
const loadCreds = async () => {
const creds = await stytchClient.webauthn.registerStart();
setWebauthnCreds(creds.public_key_credential_creation_options);
}
loadCreds();
}, [stytchClient]);
const trigger = useCallback(() => {
webauthnCreds && stytchClient.webauthn.register(webauthnCreds);
}, [webauthnCreds, stytchClient]);
return (
<button disabled={!webauthnCreds} onClick={trigger}>
Authenticate WebAuthn Registration
</button>
);
};
RESPONSE
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
"webauthn_registration_id": "webauthn-registration-test-5c44cc6a-8af7-48d6-8da7-ea821342f5a6"
}
Wraps Stytch's authenticate_start WebAuthn endpoint and the navigator.credentials web API. Call this methods to prompt the user to authenticate an existing WebAuthn registration. In order to use these methods, the user must have already logged in with a primary method - OAuth, one-time passcodes, or magic links. If this method succeeds, the WebAuthn credential will be added to the user's existing session as an authentication_factor.
You should preload the public key data by calling webauthn.authenticateStart when the authentication flow first starts. Call webauthn.authenticate inside an event callback triggered by a user gesture. Otherwise, newer versions of Safari will not allow your website access to the WebAuthn API.
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 useStytchSession hook if you are using React.
webauthn.authenticateStart parameters
The domain for the WebAuthn authentication. Defaults to window.location.hostname
webauthn.authenticate parameters
The public_key_credential_request_options value from the webauthn.authenticateStart response.
Additional configuration.
Collapse
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.
If a session_token or session_jwt is provided then a successful authentication will continue to extend the session this many minutes.
Example
import React, { useCallback, useEffect, useState } from 'react';
import { useStytch } from '@stytch/stytch-react';
export const Login = () => {
const stytchClient = useStytch();
const [webauthnCreds, setWebauthnCreds] = useState();
useEffect(() => {
const loadCreds = async () => {
const creds = await stytchClient.webauthn.authenticateStart();
setWebauthnCreds(creds.public_key_credential_request_options);
}
loadCreds();
}, [stytchClient]);
const trigger = useCallback(() => {
webauthnCreds && stytchClient.webauthn.authenticate(webauthnCreds, {
session_duration_minutes: 60,
});
}, [webauthnCreds, stytchClient]);
return (
<button disabled={!webauthnCreds} onClick={trigger}>
Authenticate WebAuthn Registration
</button>
);
};
RESPONSE
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
"user": {...},
"webauthn_registration_id": "webauthn-registration-test-5c44cc6a-8af7-48d6-8da7-ea821342f5a6",
"session_jwt": "",
"session_token": "",
"session": null
}
Time-based One-time Passcodes (TOTPs) are one-time passcodes that are generated based on a shared secret and the current time. TOTPs are also often referred to as Authenticator Apps and are a common form of secondary authentication. Creating a Stytch instance of a TOTP for a User creates a shared secret. This secret is shared by Stytch with the end user's authenticator application of choice (e.g. Google Authenticator). The authenticator app can then generate TOTPs that are valid for a specific amount of time (generally 30 seconds). The end user inputs the TOTP and the developer can use the authenticate method to verify that the TOTP is valid.
The Stytch SDK can be used to generate new TOTP secrets for users, and authenticate existing TOTP secrets.
To call these methods, TOTPs must be enabled in the SDK Configuration page of the Stytch dashboard.
Wraps Stytch's create endpoint. Call this method to create a new TOTP instance for a user. The user can use the authenticator application of their choice to scan the QR code or enter the secret.
You can listen for successful user updates anywhere in the codebase with the stytch.user.onChange() method or useStytchUser() hook if you are using React.
Note: If a user has enrolled another MFA method, this method will require MFA. See the Multi-factor authentication section for more details.
The expiration for the TOTP instance. If the newly created TOTP is not authenticated within this time frame the TOTP will be unusable. Defaults to 60 (1 hour) with a minimum of 5 and a maximum of 1440.
Example
import React, { useCallback, useEffect, useState } from 'react';
import { useStytch } from '@stytch/stytch-react';
export const Login = () => {
const stytchClient = useStytch();
const trigger = useCallback(() => {
stytchClient.totps.create({ expiration_minutes: 60 });
}, [ stytchClient]);
return (
<button onClick={trigger}>
Create TOTP
</button>
);
};
RESPONSE
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"secret": "BTGNX5RKJRMQWQFRQKTG34JCF6XDRHZS",
"totp_id": "totp-test-41920359-8bbb-4fe8-8fa3-aaa83f35f02c",
"qr_code": "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAMgAAADIEAAAAADYoy0BAAAG8ElEQVR...8EAAD//7dQP/5Y00bRAAAAAElFTkSuQmCC",
"recovery_codes": [
"ckss-2skx-ebow",
"spbc-424h-usy0",
"hi08-n5tk-lns5",
"1n6i-l5na-8axe",
"aduj-eufq-w6yy",
"i4l3-dxyt-urmx",
"ayyi-utb0-gj0s",
"lz0m-02bi-psbx",
"l2qm-zrk1-8ujs",
"c2qd-k7m4-ifmc"
]
}
Wraps Stytch's authenticate endpoint. Call this method to authenticate a TOTP code entered by a user.
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 useStytchSession hook if you are using React.
The TOTP code to authenticate. The TOTP code should consist of 6 digits.
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.
If a session_token or session_jwt is provided then a successful authentication will continue to extend the session this many minutes.
Example
import React, { useCallback, useState } from 'react';
import { useStytch } from '@stytch/stytch-react';
export const Authenticate = () => {
const stytchClient = useStytch();
const [totpCode, setTotpCode] = useState('');
const authenticate = useCallback((e) => {
e.preventDefault();
stytch.totps.authenticate({ totp_code: totpCode, session_duration_minutes: 60 });
}, [stytchClient, totpCode]);
const handleChange = useCallback((e) => {
setTotpCode(e.target.value);
}, []);
return (
<form>
<label for="totp-input">Enter code</label>
<input
id="totp-input"
value={totpCode}
onChange={handleChange}
/>
<button onClick={authenticate} type="submit">
Submit
</button>
</form>
);
};
RESPONSE
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
"user": {...},
"totp_id": "totp-test-41920359-8bbb-4fe8-8fa3-aaa83f35f02c",
"session_jwt": "",
"session_token": "",
"session": null
}
Wraps Stytch's recovery_codes endpoint. Call this method to retrieve the recovery codes for a TOTP instance tied to a user.
You can listen for successful user updates anywhere in the codebase with the stytch.user.onChange() method or useStytchUser() hook if you are using React.
Note: If a user has enrolled another MFA method, this method will require MFA. See the Multi-factor authentication section for more details.
Example
import React, { useCallback, useEffect, useState } from 'react';
import { useStytch } from '@stytch/stytch-react';
export const Login = () => {
const stytchClient = useStytch();
const trigger = useCallback(() => {
stytchClient.totps.recoveryCodes();
}, [ stytchClient]);
return (
<button onClick={trigger}>
Get Recovery Codes
</button>
);
};
RESPONSE
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
"totps": [
{
"totp_id": "totp-test-41920359-8bbb-4fe8-8fa3-aaa83f35f02c",
"verified": true,
"recovery_codes": [
"ckss-2skx-ebow",
"spbc-424h-usy0",
"hi08-n5tk-lns5",
"1n6i-l5na-8axe",
"aduj-eufq-w6yy",
"i4l3-dxyt-urmx",
"ayyi-utb0-gj0s",
"lz0m-02bi-psbx",
"l2qm-zrk1-8ujs",
"c2qd-k7m4-ifmc"
]
}
]
}
Wraps Stytch's recover endpoint. Call this method to authenticate a recovery code for a TOTP instance.
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 useStytchSession hook if you are using React.
The recovery code to authenticate.
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.
If a session_token or session_jwt is provided then a successful authentication will continue to extend the session this many minutes.
Example
import React, { useCallback, useState } from 'react';
import { useStytch } from '@stytch/stytch-react';
export const Authenticate = () => {
const stytchClient = useStytch();
const [recoveryCode, setRecoveryCode] = useState('');
const recover = useCallback((e) => {
e.preventDefault();
stytch.totps.recover({ recovery_code: recoveryCode, session_duration_minutes: 60 });
}, [stytchClient, recoveryCode]);
const handleChange = useCallback((e) => {
setRecoveryCode(e.target.value);
}, []);
return (
<form>
<label for="recovery-code-input">Enter recovery code</label>
<input
id="recovery-code-input"
value={recoveryCode}
onChange={handleChange}
/>
<button onClick={recover} type="submit">
Submit
</button>
</form>
);
};
RESPONSE
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"session_jwt": "",
"session_token": "",
"session": null,
"user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
"user": {...},
"totp_id": "totp-test-41920359-8bbb-4fe8-8fa3-aaa83f35f02c"
}
Crypto wallets allow users to hold digital assets, like cryptocurrencies and NFTs, and easily cryptographically authenticate themselves on a blockchain.
The SDK provides methods that can be used to authenticate a user via their crypto wallet.
To call these methods, Crypto Wallets must be enabled in the SDK configuration page of the Stytch dashboard.
Wraps Stytch's authenticate_start and authenticate crypto wallet endpoints. Call this methods to prompt the user to sign a challenge using their crypto wallet.
Load the challenge data first by calling cryptoWallets.authenticateStart. Pass this challenge to your user's wallet for signing.
If this method succeeds and the user is not already logged in, the user will be logged in, granted an active session, and the session cookies will be minted and stored in the browser. If the user is already logged in, the crypto wallet will be added to the user.crypto_wallets[] array and associated with user's existing session as an authentication_factor.
You can listen for successful login events anywhere in the codebase with the stytch.session.onChange() method or useStytchSession hook if you are using React.
cryptoWallet.authenticateStart parameters
The type of wallet to authenticate. Currently ethereum and solana are supported.
The address to authenticate.
cryptoWallet.authenticate parameters
The type of wallet to authenticate. Currently ethereum and solana are supported.
The address to authenticate.
The signature from the message.
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.
If a session_token or session_jwt is provided then a successful authentication will continue to extend the session this many minutes.
Example
import React, { useCallback } from 'react';
import { useStytch } from '@stytch/stytch-react';
export const Login = () => {
const stytchClient = useStytch();
const trigger = useCallback(async () => {
/* Request user's address */
const [crypto_wallet_address] = await ethereum.request({
method: 'eth_requestAccounts',
});
/* Ask Stytch to generate a challenge for the user */
const { challenge } = await stytch.cryptoWallets.authenticateStart({
crypto_wallet_address,
crypto_wallet_type: 'ethereum',
});
/* Ask the user to sign the challenge */
const signature = await ethereum.request({
method: 'personal_sign',
params: [challenge, crypto_wallet_address],
});
/* Send the signature back to Stytch for validation */
await stytch.cryptoWallets.authenticate({
crypto_wallet_address,
crypto_wallet_type: 'ethereum',
signature,
session_duration_minutes: 60,
});
}, [stytchClient]);
return (
<button onClick='{trigger}'>
Sign in with Ethereum
</button>
);
};
RESPONSE
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
"user": {...},
"session_jwt": "",
"session_token": ""
}
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.
To call these methods, Manage user data must be enabled in the SDK Configuration page of the Stytch dashboard.
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 library provides 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 from 'react';
import { useStytchUser } from '@stytch/stytch-react';
export const Home = () => {
const stytchUser = useStytchUser();
return stytchUser ? (
<p>Welcome, {stytchUser.name.first_name}</p>
) : (
<p>Log in to continue!</p>
);
};
Wraps Stytch's update user endpoint. Use this method to change the user's name, and save additional phone numbers, crypto wallets, and email addresses.
You can listen for successful user updates anywhere in the codebase with the stytch.user.onChange() method or useStytchUser() hook if you are using React.
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
Object with the fields to be updated
Collapse
The name of the user. If at least one name field is passed, all name fields will be updated.
Collapse
The first name of the user. Replaces an existing first name, if it exists.
The middle name(s) of the user. Replaces an existing middle name, if it exists.
The last name of the user. Replaces an existing last name, if it exists.
Multiple emails can exist for one user. Add additional emails via this endpoint. To delete an email, use the delete user email endpoint.
Collapse
An email for the user.
Multiple phone numbers can exist for one user. Add additional phone numbers via this endpoint. To delete a phone number, use the delete user phone number endpoint.
Collapse
A phone number for the user. The phone number should be in E.164 format.
Multiple crypto wallets can exist for a single user. You may add crypto wallets to a Stytch user via this endpoint, this endpoint accepts a list of crypto objects, i.e. a set of crypto_wallet_addresss and crypto_wallet_types.
To delete a crypto wallet, use the /users/crypto_wallets/CRYPTO_WALLET_ID endpoint.
Collapse
A crypto wallet address.
A crypto wallet type.
Example
import React, { useCallback } from 'react';
import { useStytch } from '@stytch/stytch-react';
export const Login = () => {
const stytchClient = useStytch();
const updateName = useCallback(() => {
stytchClient.user.update({
name: {
first_name: 'Jane',
last_name: 'Doe',
},
});
}, [stytchClient]);
const addPhoneNumber = useCallback(() => {
stytchClient.user.update({
phone_numbers: [{ phone_number: '+12025550162' }],
});
}, [stytchClient]);
const addEmail = useCallback(() => {
stytchClient.user.update({
emails: [{ email: 'sandbox@stytch.com' }],
});
}, [stytchClient]);
const addCryptoWallet = useCallback(() => {
stytchClient.user.update({
crypto_wallets: [{
crypto_wallet_address: '0x6df2dB4Fb3DA35d241901Bd53367770BF03123f1',
crypto_wallet_type: 'ethereum',
}],
});
}, [stytchClient]);
return (
<>
<button onClick={updateName}>
Update name
</button>
<button onClick={addPhoneNumber}>
Add phone number
</button>
<button onClick={addEmail}>
Add email
</button>
<button onClick={addCryptoWallet}>
Add crypto wallet
</button>
</>
);
};
RESPONSE
{
"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": {...}
}
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 if you are using React.
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
ID of the email, phone number, or WebAuthn registeration to be deleted.
Example
import React, { useCallback } from 'react';
import { useStytch } from '@stytch/stytch-react';
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
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
"user": {...}
}
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.
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 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
import React, { useEffect } from 'react';
import { useStytchSession } from '@stytch/stytch-react';
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} />;
};
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
Additional configuration.
Collapse
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.
If a session_token or session_jwt is provided then a successful authentication will continue to extend the session this many minutes.
Example
import React, { useEffect } from 'react';
import { useStytch } from '@stytch/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 null;
};
RESPONSE
{
"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"
}
],
"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"
}
Wraps Stytch's revoke Session endpoint and revokes the user's current session. This method should be used to log out a user.
Example
import React, { useCallback } from 'react';
import { useStytch } from '@stytch/stytch-react';
export const LogOutButton = () => {
const stytchClient = useStytch();
const logout = useCallback(() => {
stytchClient.session.revoke();
}, [stytchClient]);
return (
<button onClick={logout}>
Log out
</button>
);
};
RESPONSE
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141"
}
CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a security measure that attempts to verify that a user is human and not a malicious bot. This helps protect your application against spammy sign ups and other automated bot attacks. Set up CAPTCHA in your Dashboard via our step by step guide and the SDK will protect every login according to your configured threshold. Only Google Enterprise is currently supported, but please contact us if there is a CAPTCHA provider you would like to see supported in the future!
The public token for your project. You can find your public token under the API keys tab in your developer dashboard. Required if not using React and within the StytchProvider.
The config object for login or signup functionality.
Collapse
The products array allows you to specify the authentication methods that you would like to expose to your users.
The order of the products that you include here will also be the order in which they appear in the login form, with the first product specified appearing at the top of the login form.
Currently the Javascript SDK supports our emailMagicLinks and oauth products.
The options for email magic links. This is required if emailMagicLinksis present in the products array.
Collapse
The URL that will appear in your email template and accepts a token (ex: you implement 'https://example.com/authenticate?token=123' in your app and pass 'https://example.com/authenticate' as the redirect URL). This link should route to an endpoint that authenticates your user via Stytch's authenticate magic link endpoint and redirect to your app's experience for existing users.
Number of minutes the magic link is valid for.
The URL that will appear in your email template and accepts a token (ex: you implement 'https://example.com/authenticate?token=123' in your app and pass 'https://example.com/authenticate' as the redirect URL). This link should route to an endpoint that authenticates your user via Stytch's authenticate magic link endpoint and redirect to your app's experience for new users.
Number of minutes the magic link is valid for.
This flag determines whether the status of a new user will be pending. Users are created with an active status by default. If this flag true, users will be saved with a pending status in Stytch's backend. An example usage of this would be to invite users.
Collapse
An array of OAuth providers you wish to use. Each Provider is an object with a type key that determines the type of provider. Each Provider accepts an optional custom_scopes array of scopes that Stytch will request for your application in addition to the base set of scopes required for login. The order of the providers in the array determines the order of the rendered buttons.
Collapse
Adds the Google OAuth login button and Google One Tap. If you enable one_tap you must also provide a position parameter; embedded will display Google One Tap within the existing JavaScript SDK login form alongside the other configured sign-in options, floating will display the One Tap prompt in the top right corner.
If Google OAuth is the only authentication option specified and one_tap is set to floating, the normal Google OAuth login button will not appear in the SDK login form and only the floating One Tap box will be displayed.
See Stytch's storybook for examples.
Note: If you enable Google One Tap, ensure that you've added your app or website's URL as an authorized JavaScript origin in your Google Developer dashboard. If you're using localhost, make sure to add both http://localhost and http://localhost:port (e.g http://localhost:3000). See Step 5 in your Google OAuth setup guide here.
Note: Google One Tap cannot be used to authorize additional custom scopes.
// with One Tap
{ type: 'google', one_tap: true, position: 'embedded' | 'floating' }
// with standard OAuth
{ type: 'google', custom_scopes?: ['...'] }
Adds the Microsoft OAuth start button.
{ type: 'microsoft', custom_scopes?: ['...'] }
Adds the Apple OAuth start button. Apple has no additional scopes that may be requested at this time.
{ type: 'apple' }
Adds the GitHub OAuth start button.
{ type: 'github', custom_scopes?: ['...'] }
Adds the Gitlab OAuth start button.
{ type: 'gitlab', custom_scopes?: ['...'] }
Adds the Facebook OAuth start button.
{ type: 'facebook', custom_scopes?: ['...'] }
Adds the Slack OAuth start button.
{ type: 'slack', custom_scopes?: ['...'] }
Adds the Discord OAuth start button.
{ type: 'discord', custom_scopes?: ['...'] }
The URL that your users will redirect to after completing the OAuth authentication flow at a given OAuth provider, i.e. after the user returns from authenticating via Google.
This URL should route to an endpoint within your app that will complete the Stytch OAuth authentication flow, by hitting our oauth/authenticate endpoint.
If not specified, the user will be redirected to the default login redirect URL that you've configured in your Dashboard.
The URL that your users will redirect to after completing the OAuth authentication flow at a given OAuth provider, i.e. after the user returns from authenticating via Google.
This URL should route to an endpoint within your app that will complete the Stytch OAuth authentication flow, by hitting our oauth/authenticate endpoint.
If not specified, the user will be redirected to the default sign up redirect URL that you've configured in your Dashboard.
The style object allows you to customize the look of the SDK. You can specify some of them or none at all. We'll use our defaults for the ones you don't specify. Check out the UI customization options in the SDK here.
Collapse
The font family that will apply to all text in the SDK.
Your primary brand color. This color will be applied to primary actions, like buttons.
The color for most of the text in the SDK.
The color for secondary text in the SDK, such as disclaimers.
A light grey color that will be applied to visual elements in the SDK.
A dark grey color that will be applied to visual elements in the SDK.
The width of the SDK.
When this value is false, the title and description text will not show in the SDK.
Optional callbacks that are triggered by various events in the SDK. See more details about the callbacks here.
Collapse
A callback function that responds to events sent from the SDK. For now, this includes a USER_EVENT_TYPE.
A callback function that responds to successfully sending a magic link.
A callback function that responds to errors in the SDK. It is useful for debugging during development and error handling in production.
Example
import React from "react";
import { Stytch } from "@stytch/stytch-react";
const Login = () => {
const STYTCH_PUBLIC_TOKEN = "PUBLIC_TOKEN";
const stytchProps = {
loginOrSignupView: {
products: ['emailMagicLinks', 'oauth'],
emailMagicLinksOptions: {
loginRedirectURL: "https://example.com/authenticate",
loginExpirationMinutes: 30,
signupRedirectURL: "https://example.com/authenticate",
signupExpirationMinutes: 30,
createUserAsPending: true,
},
oauthOptions: {
providers: [{type: 'google', 'one_tap': true, position: 'floating'}, {type: 'microsoft'}]
},
},
style: {
fontFamily: 'Arial',
width: '321px',
primaryColor: '#106ee9',
},
publicToken: STYTCH_PUBLIC_TOKEN,
callbacks: {
onEvent: (data) => {
// TODO: check whether the user exists in your DB
const userExists = false;
if (data.eventData.type === 'USER_EVENT_TYPE' && !userExists) {
fetch("/users", {
method: "POST",
body: JSON.stringify({
userId: data.eventData.userId,
email: data.eventData.email,
}),
});
}
},
onSuccess: (data) => console.log(data),
onError: (data) => console.log(data),
},
};
return (
<div className="sign-in-container">
<Stytch
publicToken={stytchProps.publicToken}
loginOrSignupView={stytchProps.loginOrSignupView}
style={stytchProps.style}
callbacks={stytchProps.callbacks}
/>
</div>
);
};
export default Login;
Callbacks are optional functions for the Javascript SDK.
onEvent
A function that is called when a Stytch user is retrieved or created. The function expects an argument of an event object. The object has eventType and eventData objects.
{
"eventType": "CALLBACK_EVENT",
"eventData": {
"type": "USER_EVENT_TYPE",
"userId": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
"emailId": "email-test-81bf03a8-86e1-4d95-bd44-bb3495224953",
"email": "example@stytch.com"
}
},
onSuccess
{
"eventType": "SUCCESS_EVENT",
"eventData": {
"message": "Successfully sent magic link to example@stytch.com",
}
},
onError
A function that is called when a error occurs. The function expects an argument of an event object. The object has eventType and eventData objects.
{
"eventType": "ERROR_EVENT",
"eventData": {
"message": "Error sending magic link",
}
},
Stytch will automatically save the user's session data in two cookies:
Both cookies will be sent on every request to your backend servers. Your servers must validate either the stytch_session or stytch_session_jwt before processing the request. The session may be validated using any of our supported client libraries.
For example, if you load the SDK on https://app.mycoolsite.com we will set
Note: If you load the SDK on localhost, we will not mark the cookie as secure.
Here is an example of validating the opaque session in Node.js / Express.
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
app.use(authenticateStytchSession);
const client = new stytch.Client({
project_id: process.env.STYTCH_PROJECT_ID,
secret: process.env.STYTCH_SECRET,
env: stytch.envs.test,
});
const authenticateStytchSession = (req, res, next) => {
return client.sessions.authenticate({
session_token: req.cookies['stytch_session'],
})
.then(session => {
req.stytchSession = session;
return next();
})
.catch(next)
} ;
Heres an example of validating the JWT in Node.js / Express.
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
app.use(authenticateStytchSession);
const client = new stytch.Client({
project_id: process.env.STYTCH_PROJECT_ID,
secret: process.env.STYTCH_SECRET,
env: stytch.envs.test,
});
const authenticateStytchSession = (req, res, next) => {
return client.sessions.authenticateJwt(req.cookies['stytch_session_jwt'])
.then(session => {
req.stytchSession = session;
return next();
})
.catch(next)
};
On first load, many websites must make a network request to determine whether a user 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:
If a SWR approach isn't right for you, you can explicitly call stytch.user.get() to refresh the user object with a network call, and/or stytch.session.authenticate() to make sure the user is still logged in.
To guard against potential misuse of the client-side library by bad actors, the SDK has a few restrictions:
The JavaScript SDK is not a complete replacement for the Stytch API - they are designed to be used together in order to create secure and low-friction login experiences. Some processes must necessarily happen on your server rather than client (for example, validating a session_token).
The Stytch SDK allows users to edit the verification mechanisms associated with their account (adding an email, deleting a phone number, adding a second factor method, etc.).
In order to access these routes, we require the that the user be authenticated with a secure combination of factors.
Stytch factors are split into three general groups based on what they prove:
In order for a session to be considered secure, it must include factors from at least two categories. For example, if a user completes a successful Email magic link flow and a successful SMS passcode flow, they will be considered securely authenticated. A user that completes an Email magic link flow + an OAuth flow with their Google account will not. In addition, at least one factor in the session must be less than an hour old.
Important: If a user does not have enough registered factors, they will always be allowed to add one.
Asynchronous loading of JavaScript can help improve the user experience of your site by not blocking DOM rendering during script loading. If you don't need immediate use of the SDK methods or UI elements, this may be a good option.
You can avoid blocking DOM rendering by adding an async or defer attribute to the script. Note that the global Stytch function will not be available until after the script has loaded. If you plan on showing the Login SDK to users immediately, we do not recommend using these attributes.
<script id="js-stytch" defer src="https://js.stytch.com/stytch.js"></script>
<script>
var script = document.querySelector("#js-stytch");
script.addEventListener("load", function () {
var STYTCH_PUBLIC_TOKEN = "PUBLIC_TOKEN";
var stytch = Stytch(STYTCH_PUBLIC_TOKEN);
stytch.mount(...)
});
</script>
If you are using the React or plain JavaScript libraries, you can use the loadAndInitStytch method for async loading.
The Stytch iOS SDK is under construction and will be available later this year. Interested in using it? Contact us.
The Stytch Android SDK is under construction and will be available later this year. Interested in using it? Contact us.