Node

Welcome to the Docs

Our products allow you to build frictionless, secure, and engaging authentication flows. Choose one of our SDKs and build your login flow in minutes, or go with our Direct API that offers maximum flexibility.

Overview

Our flexible SDK, your brand

Our SDKs offer flexible templates that can be tailored to your colors, fonts, and logo, so you can easily create seamless onboarding and authentication experiences that delight users and complement your brand—without the trouble of building UI from the ground up.

Maximum customization, minimal hassle

Our Direct API integration considers both developer and user experience to ensure fast, safe, and easy authentication flows. We make integration quick and painless, with clear and comprehensive documentation.

Product suite


Example apps

Learn more about how Stytch works and get up and running quickly using an example app.


Starting with a template

Examples using the Stytch frontend SDKs, for web and mobile.

example app


Guides

Step-by-step guides to quickly get up and running with Stytch.

Setting up a new auth solution with the Stytch SDK

Let Stytch handle the heavy lifting and leverage the fully customizable prebuilt frontend SDKs for mobile or web

Preferred frontend language

HTML

This is an integration guide for setting up the Stytch SDK in your app. First, you'll configure our frontend SDK in your client code to create a login experience in your app. Then, you'll add support to your server code for authenticating Stytch magic links. If you have any questions, check out the docs for the SDK or our example app that uses the code in this guide.

Stytch data flow

Step 1: Gather information

1.1 API Keys

To get started, you’ll need a project ID, secret, and public token that you can find in the API keys tab of the dashboard. You have both test and live credentials for your project. Test your integration using your test API keys. Once you’ve verified your integration, upgrade to your live API keys.

Step 2: Use Stytch.js

2.1 Include Stytch.js

Include the stytch.js script on each of your HTML views that implement login or sign-up. For information about asynchronous and deferred loading of the SDK, please see the reference.

<script id="js-stytch" src="https://js.stytch.com/stytch.js"></script>

Add an HTML element where the Stytch Magic Link will mount to. You can use any CSS Selector.

<div id="magic-link"></div>

2.2 Initialize the Stytch object

Initialize the Stytch object in Javascript using your test public token (update to live public token once you've tested your integration) and a config object with callbacks. This might be in a <script> tag in your HTML view. Make sure it's below your element that you added in step 2.1.

Configuration:

  • onEvent: A callback function that responds to events sent from the SDK. For now, this includes a USER_EVENT_TYPE.
  • onSuccess: A callback function that responds to successfully sending a magic link.
  • onError: A callback function that responds to errors in the SDK. It is useful for debugging during development and error handling in production.
// Initialize stytch with public token
var STYTCH_PUBLIC_TOKEN = "PUBLIC TOKEN";
var stytch = Stytch(STYTCH_PUBLIC_TOKEN, {
  onEvent: async (response) => {
    // TODO: check whether the user exists in your DB
    const userExists = false;
    if (response.data.type === 'USER_EVENT_TYPE' && !userExists) {
      try {
        await fetch('/users', { 
          method: 'POST',
          mode: 'cors',
          body: JSON.stringify({ userId: response.data.userID }),
          headers: {
            'Content-Type': 'application/json'
          },
        });
      } catch(e) {
        console.log(e);
      }
    }
  },
  onSuccess: (response) => {
    // Handle successfully sent magic link
    console.log(response);
  },
  onError: (response) => {
    // Handle an error
    console.log(response);
  }
});

2.3 Customize Stytch.js

Customize the style and functionality of the SDK. The style object allows you to modify the look and feel to match your app. The config object updates what the magic link will be in the email your users receive (you'll need to implement the magic link endpoint in your app - see step 6). Check out the UI customization options in the SDK here.

// Check out the style options in the docs
var style = {
  fontFamily: '"Helvetica New", Helvetica, sans-serif',
  primaryColor: '#106ee9',
  primaryTextColor: "#090909",
};
var loginOrSignupView = {
  products: ['emailMagicLinks'],
  emailMagicLinksOptions: {
    loginRedirectURL: "https://example.com/authenticate",
    loginExpirationMinutes:30,
    signupRedirectURL: "https://example.com/authenticate",
    signupExpirationMinutes: 30,
};

2.4 Add redirect URLs to the Stytch dashboard

Add the login and signup URLs to the project's list of predefined redirect URLs in the dashboard. For more information on why this step is necessary, please check out the documentation here.

2.5 Mount Stytch.js

Finally, mount Stytch to your HTML element using the CSS selector. Make sure your mount function is in a script tag below the HTML element so stytch can mount to it.

stytch.mount({
  elementId: "#magic-link",
  style: style,
  loginOrSignupView: loginOrSignupView
});

Step 3: Add server side support to your app for Stytch

Stytch works best with support from your app's server. You'll need to create or modify a few endpoints. The Node examples use express to create http endpoints and express-session for sessions, but they can be replaced with any other http framework.

3.1 Install Stytch

Install the stytch package via npm or yarn. The stytch package provides backend support for the Stytch API.

npm install stytch --save

3.2 Create a user

POST/PUT user endpoint: When a user logs in to your app for the first time, the SDK will create a Stytch user for them and return a userId. We recommend adding a stytchUserId field to your user to save it.

app.post('/users', function (req, res) {
  var stytchUserId = req.body.userId;
  // TODO: Save stytchUserId with your user record in your app's storage
  res.send(`Created user with stytchUserId: ${stytchUserId}`);
});

3.3 Authenticate a user: GET route

GET authentication endpoint: When a user enters their email and clicks the login button, we will send them an email with a magic link to log in. You need to create a route for the magic link. There are a few ways to do this:

  • - Implement a GET route on your frontend that accepts a token and passes it to a route on your backend that passes the token to Stytch to authenticate. This is recommended if your frontend lives separately from your backend.
  • - Implement a GET route in your backend that accepts a token and passes it to Stytch to authenticate. This is recommended if your backend and frontend live in the same service.

3.4 Authenticate a user: POST route

POST to Stytch: If your url in the previous step was https://example.com, your user will be directed to https://example.com?token={token} when they click the magic link in the email. You'll pass this token to Stytch to authenticate it. If authentication is successful, create a user session and log them into your app. If you'd like to keep this user logged-in for a while, include "session_duration_minutes": 60 (an hour, for example). Check out the session management guide to learn how to handle the session.

const stytch = require('stytch');
const client = new stytch.Client({
  project_id: "PROJECT ID",
  secret: "SECRET",
  env: stytch.envs.test
});
app.get('/authenticate', function (req, res) {
  var token = req.query.token;
  client.magicLinks.authenticate(token)
  .then(response => {
    req.session.authenticated = true;
      req.session.save(function(err) {
    console.log(err);
    });
    res.redirect('/home')
  })
  .catch(error => {
    console.log(error);
    res.send('There was an error authenticating the user.');
  });
});

Replacing your password reset flow

Integrate Stytch as a replacement for your forgot password flow. This will be used to complement your existing login methods. To replace your login flow with Stytch, see the Augmenting existing auth flow guide.

Step 1: Create a password reset UI

Here’s an example of a password reset component.

Step description

Step 2: Add redirect URLs to the Stytch dashboard

Add the login and signup URLs to the project's list of predefined redirect URLs in the dashboard. For more information on why this step is necessary, please check out the documentation here.

Step 3: Create user

To send a login email, the user who forgot their password needs to be created with Stytch. Check if the user has a Stytch user ID. If they do not, create a Stytch user for them and save the user ID from the response. This needs to happen once for each user who forgets their password. We recommend saving the Stytch user ID in a new column of your users table or within a new table linking your users with their Stytch user ID.

curl --request POST \
	--url https://test.stytch.com/v1/users \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
		"email": "test@stytch.com"
	}'

Inviting users

Integrate Stytch to easily invite and authenticate users. When a user invites someone to their team, you'll send them a magic link invite with Stytch. The invited user will have a pending status until they click the link to authenticate. At this point, they will become an active user and you can log them in. For an example of how to build this, see our example app.

Step 1: Build an invite user UI

If you don't already have one, you'll need to build an invite user view for your app.

Step description

Step 2: Add redirect URLs to the Stytch dashboard

Add the invite URL to the project's list of predefined redirect URLs in the dashboard. For more information on why this step is necessary, please check out the documentation here.

Step 3: Invite user

When you want to send an invitation to a user, send a InviteByEmail request. The user will receive an email explaining they’ve been invited. This will create a Stytch user with an invited status. Remember to save the user ID from the response. The invite_magic_link_url request parameter is the URL the user will be redirected to from the email.

curl --request POST \
	--url https://test.stytch.com/v1/magic_links/email/invite \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
		"email": "test@stytch.com",
		"invite_magic_link_url": "https://example.com/authenticate"
	}'

Step 5: Later authentication

After the user has accepted their invitation, you can send a magic link to authenticate a user by sending a SendMagic request.


Augmenting existing auth flow

Integrate Stytch email magic links into your existing login flow. It’s easy to replace your existing login flow entirely or add an alternative login method alongside your existing options.

Step 1: Update your login UI

Here’s an example of a login component when Stytch is the only login method.

Step description

Step 2: Create user

Since each user needs to be created with Stytch, check if the user logging in or signing up has a Stytch user ID. If they do not, create a Stytch user for them and save the user ID from the response. This needs to happen once per user. We recommend saving the Stytch user ID in a new column of your users table or within a new table linking your users with their Stytch user ID.

curl --request POST \
	--url https://test.stytch.com/v1/users \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
		"email": "test@stytch.com"
	}'

Step 3: Add redirect URLs to the Stytch dashboard

Add the login and signup URLs to the project's list of predefined redirect URLs in the dashboard. For more information on why this step is necessary, please check out the documentation here.


Setting up a new auth solution with SMS

Integrate Stytch one-time passcodes as your authentication solution.

Step 1: Build your UI for SMS login

Here’s an example of an authentication flow. One screen accepts the user’s phone number and the other accepts their one-time passcode.

Step description
Step description

Step 2: Login or create user

The LoginOrCreateUserBySMS endpoint will be used to log in or sign up a user. This request will send a one-time passcode to the provided phone number. By default, the code will expire in 2 minutes. You can alter the expiration with the ExpirationMinutes request field. If the phone number isn’t associated with a user yet, a user will be created. If the user_created attribute in the response is true, save the user ID and phone ID from the response. We recommend saving these IDs in new columns of your users table or within a new table linking your users with their Stytch IDs.

curl --request POST \
	--url https://test.stytch.com/v1/otps/sms/login_or_create \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
	    "phone_number": "+12025550162"
	}'

Step 3: Authenticate one-time passcode

The AuthenticateOTP endpoint will be used in conjunction with all LoginOrCreateUserBySMS requests. The user should be prompted to enter the one-time passcode sent to them via SMS. After the user enters their code, send an AuthenticateOTP request with the code along with the phone ID used. If the response is a 200, the user is verified and can be logged in. If you'd like to keep this user logged-in for a while, include "session_duration_minutes": 60 (an hour, for example). Check out the session management guide to learn how to handle the session.

curl --request POST \
	--url https://test.stytch.com/v1/otps/authenticate \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
	    "method_id": "phone-number-test-d5a3b680-e8a3-40c0-b815-ab79986666d0",
        "code": "123456"
	}'

Add multi-factor authentication with SMS

Integrate Stytch one-time passcodes as your multi-factor authentication solution.

Step 1: Build your UI for multi-factor authentication

Here’s an example of a multi-factor authentication flow. One screen accepts the user’s phone number and the other accepts their one-time passcode.

Step description
Step description

Step 2: Create or update user

The user you want to authenticate needs to be a Stytch user with an associated phone number. If they are, continue to Step 3. If the user already has a Stytch ID, send a UpdateUser request to add a phone number. If they don’t, send a CreateUser request to create a user with a phone number. We recommend saving the user and phone IDs in new columns of your users table or within a new table linking your users with their Stytch IDs.

curl --request POST \
	--url https://test.stytch.com/v1/users \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
		"phone_number": "+12025550162"
	}'

Step 3: Send one-time passcode

Now that the phone number is associated with a Stytch user, send a SendOTPBySMS request. This will send a one-time passcode to the provided phone number. By default, the code will expire in 2 minutes. You can alter the expiration with the ExpirationMinutes request field.

curl --request POST \
	--url https://test.stytch.com/v1/otps/sms/send \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
	    "phone_number": "+12025550162"
	}'

Step 4: Authenticate one-time passcode

The AuthenticateOTP endpoint will be used in conjunction with all SendOTPBySMS requests. The user should be prompted to enter the one-time passcode sent to them via SMS. After the user enters their code, send a AuthenticateOTP request with the code along with the phone ID used. If the response is a 200, the user is verified and can be logged in.

curl --request POST \
	--url https://test.stytch.com/v1/otps/authenticate \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
	    "method_id": "phone-number-test-d5a3b680-e8a3-40c0-b815-ab79986666d0",
        "code": "123456"
	}'

Integrate Google OAuth flow

Integrate Google OAuth into your existing login flow. The first three steps involve setting up a Google Cloud Project to get OAuth Credentials. Skip those steps if you already have your Google OAuth credentials.

Step 1: Setup Google Project

Before you can use the Stytch Google OAuth flow, you need to enter a Google OAuth client ID and client secret into the Stytch dashboard. Google requires you to create a Google Cloud project to get a client ID and client secret. Please follow the steps here to create one.

Step 3: Setup Google OAuth Credentials

After setting up the Google project and OAuth consent, go to this page to create the OAuth credentials. There is a create credentials button at the top of the page with an option to create an OAuth client id when selected. When the create OAuth credentials page loads, select Web application (regardless if it is a mobile or non-web application) for the application type and enter a name for your credentials. Under the Authorized redirect URIs section, add the following URL. After you finish creating the OAuth client, Google displays Client ID and client secret in a popup. You will need to enter them into the Stytch Dashboard here.

https://test.stytch.com/v1/oauth/callback/OAUTH CALLBACK ID

Step 4: Add redirect URLs to the Stytch dashboard

Add the login and signup URLs to the project's list of predefined redirect URLs in the dashboard. For more information on why this step is necessary, please check out the documentation here.

Step 5: Add the Google OAuth start URL

Now that Stytch and Google are configured, you need to add Stytch Google OAuth to your application. The Stytch OAuth flow is started by having a user click the Google OAuth Start URL. This URL redirects the user to the Google OAuth sign-in page with all the required OAuth fields prefilled. Your frontend needs to display Stytch Google OAuth Start URL as a button and send the user to that URL when clicked.

https://test.stytch.com/v1/public/oauth/google/start?public_token=PUBLIC TOKEN

Step 6: Authenticate OAuth request

After Google redirects the user back to Stytch's API, the Stytch API redirects the user to your backend server with a token to either the login redirect URL or the signup redirect URL to verify Stytch redirected the user. If the response is a 200, the user is verified and can be logged in.

curl --request POST \
	--url https://test.stytch.com/v1/oauth/authenticate \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
	  "token": "SeiGwdj5lKkrEVgcEY3QNJXt6srxS3IK2Nwkar6mXD4="
	}'


Session management

Stytch user sessions are identified by a session token that should be stored client-side (usually a browser cookie) and authenticated on each request. To start a session, use the authenticate magic link or authenticate OTP endpoint as usual and add the session_duration_minutes parameter to set the lifetime of the session. The responses of these endpoints will include a session_token that you can forward to the client and store. Before performing any action that requires authorization, call authenticate session to ensure that the session is still valid.

How to use sessions

Beginning a session

When handling the token for a new authentication factor (authenticate magic link and authenticate OTP), include a session_duration_minutes field to begin a new session. Sessions can be between 5 minutes and one year long. If you provide this field, the authenticate method’s response field will include values for session or session_token.

Authenticating a session

On each request, before doing anything that requires authorization, call authenticate session to ensure that the session is valid. If it is, use the user_id value to identify the user and send the session_token value to the user in a session cookie. If it isn’t valid, clear the session cookie to log the user out and do not process the request. sessions.authenticate always returns the session token for convenience. We recommend following OWASP's guide on cookie storage.

Extending or revoking a session

To extend a session’s lifetime, call authenticate session with the session_duration_minutes parameter. The session will be set to expire that many minutes from now. This will still return the original session token even though its lifetime was extended. To revoke a session, call revoke session with the session ID or session token (whichever is more convenient). We recommend showing the user a list of all their active sessions so they can revoke any they don’t recognize by IP address and/or User-Agent. To attach those values to sessions, add them to the attributes parameter in calls to authenticate magic link or authenticate OTP.

Session management examples

Below are examples of ways to use session management

Remember me for 30 days after login

Create a session that expires 30 days (43200 minutes) after initial login

curl --request POST \
	--url https://test.stytch.com/v1/magic_links/authenticate \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
		"token": "SeiGwdj5lKkrEVgcEY3QNJXt6srxS3IK2Nwkar6mXD4=",
		"session_duration_minutes": 43200
	}'

curl --request POST \
	--url https://test.stytch.com/sessions/authenticate \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
		"session_token": "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q"
	}'

Remember me for 30 days since you last saw me

Everytime a magic link is authenticated, extend the session for another 30 days (43200 minutes)

curl --request POST \
	--url https://test.stytch.com/v1/magic_links/authenticate \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
		"token": "SeiGwdj5lKkrEVgcEY3QNJXt6srxS3IK2Nwkar6mXD4=",
		"session_duration_minutes": 43200
	}'

curl --request POST \
	--url https://test.stytch.com/sessions/authenticate \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
		"session_token": "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q",
		"session_duration_minutes": 43200
	}'

Log out a user

Log the user out of a given session

curl --request POST \
	--url https://test.stytch.com/v1/sessions/revoke \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
		"session_id": "session-test-fe6c042b-6286-479f-8a4f-b046a6c46509"
	}'

Log a user out of all sessions

Get all sessions for a given user's ID and individually revoke each of them.

curl --request GET \
	--url https://test.stytch.com/v1/sessions?user_id=user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6 \
	-u 'PROJECT ID:SECRET'

curl --request POST \
	--url https://test.stytch.com/v1/sessions/revoke \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
		"session_id": "session-test-fe6c042b-6286-479f-8a4f-b046a6c46509"
	}'

Multiple Authentication Factors

Create a single session from multiple authentication factors.

# Create a new session using the first factor
curl --request POST \
	--url https://test.stytch.com/v1/magic_links/authenticate \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
		"token": "SeiGwdj5lKkrEVgcEY3QNJXt6srxS3IK2Nwkar6mXD4=",
		"session_duration_minutes": 43200
	}'

# Use the session token to attach the second factor
curl --request POST \
	--url https://test.stytch.com/v1/otps/authenticate \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
		"method_id": "phone-number-test-d5a3b680-e8a3-40c0-b815-ab79986666d0",
		"code": "123456",
		"session_token": "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q"
	}'

Client libraries

Stytch has official libraries for different programming languages to easily integrate the Stytch API on the back end.


SDKs

Use a client-side SDK to quickly build your user authentication on web and mobile.


Javascript SDK

The Stytch Javascript SDK provides a prebuilt, customizable login UI that you can use to get up and running with Stytch even faster. We offer a plain Javascript version and a React component.

Interested in using the Javascript SDK with a different product? Contact us.

SDK demo

Check out the UI customization options in the SDK here.

OAuth

Our Javascript SDK wraps our OAuth start 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, Microsoft, and Apple OAuth. Google One Tap support is coming soon.

SDK example UI

Parameters


publicToken*string

The public token for your project. You can find your public token under the API keys tab in your developer dashboard.


loginOrSignupView*object

The config object for login or signup functionality.

Collapse
products*array

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.

emailMagicLinksOptions*object

The options for email magic links. This is required if emailMagicLinks is present in the products array.

Collapse
loginRedirectUrl*string

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.

loginExpirationMinutesint

Number of minutes the magic link is valid for.

signupRedirectUrl*string

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.

signupExpirationMinutesint

Number of minutes the magic link is valid for.

createUserAsPendingboolean

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.

oauthOptions*object

The options for OAuth. This is required if oauth is present in the products array.

Collapse
providers*Array<Provider>

An array of OAuth providers you wish to use. Each Provider is an object with a single key. The order of the providers in the array determines the order of the rendered buttons.

Collapse
Googleobject

Adds the Google OAuth start button.

{ type: 'google' }

Microsoftobject

Adds the Microsoft OAuth start button.

{ type: 'microsoft' }

Appleobject

Adds the Apple OAuth start button.

{ type: 'apple' }

loginRedirectUrlstring

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.

signupRedirectUrlstring

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.


styleobject

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
fontFamilystring

The font family that will apply to all text in the SDK.

primaryColorstring

Your primary brand color. This color will be applied to primary actions, like buttons.

primaryTextColorstring

The color for most of the text in the SDK.

secondaryTextColorstring

The color for secondary text in the SDK, such as disclaimers.

lightGreystring

A light grey color that will be applied to visual elements in the SDK.

darkGreystring

A dark grey color that will be applied to visual elements in the SDK.

widthstring

The width of the SDK.

hideHeaderTextboolean

When this value is false, the title and description text will not show in the SDK.


callbacksobject

Optional callbacks that are triggered by various events in the SDK. See more details about the callbacks here.

Collapse
onEvent(data) => void

A callback function that responds to events sent from the SDK. For now, this includes a USER_EVENT_TYPE.

onSuccess(data) => void

A callback function that responds to successfully sending a magic link.

onError(data) => void

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'}, {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

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

Asynchronous and deferred loading

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 initially show the Login SDK to users — for example, if it is hidden in a modal — 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>

iOS SDK

The Stytch iOS SDK provides a prebuilt, customizable login UI that you can use to get up and running with Stytch even faster. Explore the iOS SDK here on GitHub.

Customization

You can customize prebuilt UI by setting StytchUI customization's values


StytchTextStyleobject

Style object for text UI

Collapse
fontUIFont

Text font

sizeCGFloat

Text size

colorUIColor

Text color


titleStyleStytchTextStyle

Title text style


showTitleBool

Show/hide title


subtitleStyleStytchTextStyle

Subtitle text style


showSubtitleBool

Show/hide subtitle


inputTextStyleStytchTextStyle

Input text style


inputPlaceholderStyleStytchTextStyle

Input placeholder text style


inputBackgroundColorUIColor

Input field background color


inputBorderColorUIColor

Input field border color


inputCornerRadiusCGFloat

Input field corner radius


buttonTextStyleStytchTextStyle

Action button text style


buttonBackgroundColorUIColor

Action button background color


buttonCornerRadiusCGFloat

Action button corner radius


showBrandLogoBoolean

Show/hide brand logo


Window background colorUIColor

backgroundColor


Android SDK

The Stytch Android SDK provides a prebuilt, customizable login UI that you can use to get up and running with Stytch even faster. Explore the Android SDK here on GitHub.

Also, take a look at this example app that demonstrates how to integrate with the Stytch SDK.

Requirements

The SDK supports API level 21 and above (distribution stats).

  • - minSdkVersion = 21
  • - Android Gradle Plugin 4.1.1
  • - AndroidX

Customization

You can customize prebuilt UI by setting StytchUI customization's values


StytchTextStyleobject

Style object for text UI

Collapse
sizeScalablePixels

Text size in sp

colorStytchColor

Text color

fontStytchFont

Text font


backgroundColorStytchColor

Window background color


hideActionBarBoolean

If true, no toolbar/action bar will be shown at top of screen


actionBarColorStytchColor

Toolbar/Action bar color


titleStyleStytchTextStyle

Title text style


subtitleStyleStytchTextStyle

Subtitle text style


consentTextStyleStytchTextStyle

(SMS Passcode flow only) SMS consent text style


inputTextStyleStytchTextStyle

User input (email/phone number/passcode) text style


inputHintStyleStytchTextStyle

Input hint text style


inputBackgroundColorStytchColor

Background color of input boxes


inputCornerRadiusDensityIndependentPixels

Radius of rounded corners of input boxes, in dp


buttonTextStyleStytchTextStyle

Button text style


buttonDisabledTextColorStytchColor

Set a different text color when buttons are in the disabled state


buttonEnabledBackgroundColorStytchColor

Button background color when in enabled state


buttonDisabledBackgroundColorStytchColor

Button background color when in disabled state


buttonCornerRadiusDensityIndependentPixels

Radius of rounded corners of buttons, in dp


errorTextStyleStytchTextStyle

Error message text style


Security

Responsible disclosure

If you believe you’ve discovered a potential vulnerability, please let us know by emailing us at security@stytch.com. We will acknowledge your email within 48 hours. Provide us with a reasonable amount of time to resolve the issue before disclosing it to the public or a third party. We aim to resolve critical issues within 30 days of disclosure. Make a good faith effort to avoid violating privacy, destroying data, or interrupting or degrading the Stytch service. Please only interact with accounts you own or for which you have explicit permission from the account holder. While researching, please refrain from:

  • Distributed Denial of Service (DDoS)
  • Spamming
  • Social engineering or phishing of Stytch employees or contractors
  • Any attacks against Stytch’s physical property or data centers

Thank you for helping to keep Stytch and our users safe!

Privacy policy

See here for our current privacy policy.


Resources

Learn more about how Stytch works.

API keys

The Stytch API uses basic authentication with your project_id and secret. There are two environments, TEST and LIVE, and the API keys as well as urls, test.stytch.com and api.stytch.com respectively, are unique to each environment.

Supported browsers

Stytch.js strives to support all recent versions of major browsers:

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

If you encounter a bug with other platforms, let us know and we'll prioritize fixing based on popularity of the given browser and severity of the bug.

Testing

In some scenarios, it may be helpful to test sending a magic link without actually sending an email. You can use the email sandbox@stytch.com to test sending a magic link. If your API credentials and the request format are correct you will receive a 200 status response, but no email will actually be sent.

You can use the following test tokens to test the authenticate magic endpoint and receive the corresponding responses.

  • 200 Success: DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=

  • 401 Unauthorized: 3pzjQpgksDlGKWEwUq2Up--hCHC_0oamfLHyfspKDFU=

  • 404 Magic link not found: CprTtwhnRNiMBiUS2jSLcWYrfuO2POeBNdo5HhW6qTM=

You can use the following session tokens to test the authenticate session endpoint.

  • 200 Success: WJtR5BCy38Szd5AfoDpf0iqFKEt4EE5JhjlWUY7l3FtY

  • 404 Session not found: 59cnLELtq5cFVS6uYK9f-pAWzBkhqZl8AvLhbhOvKNWw

IP validation

You can specify up to 10 IPs that your requests must come from to ensure that only your servers are able to access the Stytch API. By default we allow all IPs. If you'd like to add IP validation, send an email to support@stytch.com with the subject "IP Validation" with your live project ID and the IPs you'd like to allow (max 10 IPs).


Integrations

Learn how to integrate Stytch with common technologies and frameworks.


Replacing Firebase with email magic links

Integrate Stytch email magic links as a replacement for your Firebase integration. Both sign-up and login flows will be merged into a single, passwordless flow.

Step 1: Update your login UI

Here’s an example of a login component when Stytch is the only login method.

Step description

Step 2: Add redirect URLs to the Stytch dashboard

Add the login and signup URLs to the project's list of predefined redirect URLs in the dashboard. For more information on why this step is necessary, please check out the documentation here.

Step 3: Log in or create user

The LoginOrCreateUser endpoint will be used to replace any methods used to log in or sign up a user, like Firebase’s SignupNewUser and VerifyPassword endpoints. This request will either send a login or create magic link to the user based on if the email is associated with a user already. If the user is created, shown by the user_created attribute in the response, save the user ID from the response to use with other Stytch endpoints. This needs to happen once per user. We recommend saving the Stytch user ID in a new column of your users table or within a new table linking your users with their Stytch user ID. The login_magic_link_url and signup_magic_link_url request parameters are the URLs the user will be redirected to from the email depending on if the user was existing or created respectively.

curl --request POST \
	--url https://test.stytch.com/v1/magic_links/email/login_or_create \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
	    "email": "test@stytch.com",
        "login_magic_link_url": "https://example.com/login",
        "signup_magic_link_url": "https://example.com/signup"
	}'

Step 5: How to replace Firebase endpoints

Both the sign up and log in flows that are separate with Firebase will merge into a single flow with Stytch. Rather than calling Firebase’s SignUp or SignInWithPassword endpoints based on if the user exists or not, you can just call our LoginOrCreateUser endpoint. After the user clicks on the email magic link, call AuthenticateMagicLink with the token passed in the query params. The response dictates if the user should be logged in or not.

Step 6: Session management

While we work to integrate session management into our feature set, you’re welcome to continue using the same Firebase endpoints to manage your tokens. This can be done in parallel with our Magic Link feature. After a user has been authenticated via the AuthenticateMagicLink endpoint, continue by making a request to Firebase’s CustomToken or similar endpoints to manage tokens.


Replacing AWS Cognito with email magic links

Integrate Stytch email magic links as a replacement for your AWS Cognito integration. Both sign-up and login flows will be merged into a single, passwordless flow.

Step 1: Update your login UI

Here’s an example of a login component when Stytch is the only login method.

Step description

Step 2: Add redirect URLs to the Stytch dashboard

Add the login and signup URLs to the project's list of predefined redirect URLs in the dashboard. For more information on why this step is necessary, please check out the documentation here.

Step 3: Log in or create user

The LoginOrCreateUser endpoint will be used to replace any methods used to log in or sign up a user, like Cognito’s InitiateAuth and SignUp endpoints. This request will either send a login or create magic link to the user based on if the email is associated with a user already. If the user is created, shown by the user_created attribute in the response, save the user ID from the response to use with other Stytch endpoints. This needs to happen once per user. We recommend saving the Stytch user ID in a new column of your users table or within a new table linking your users with their Stytch user ID. The login_magic_link_url and signup_magic_link_url request parameters are the URLs the user will be redirected to from the email depending on if the user was existing or created respectively.

curl --request POST \
	--url https://test.stytch.com/v1/magic_links/email/login_or_create \
	-u 'PROJECT ID:SECRET' \
	-H 'Content-Type: application/json' \
	-d '{
	    "email": "test@stytch.com",
        "login_magic_link_url": "https://example.comlogin",
        "signup_magic_link_url": "https://example.comsignup"
    }'

Step 5: How to replace AWS Cognito endpoints

Both the sign up and log in flows that are separate with AWS Cognito will merge into a single flow with Stytch. Rather than calling AWS Cognito’s SignUp or InitiateAuth endpoints based on if the user exists or not, you can just call our LoginOrCreateUser endpoint. After the user clicks on the email magic link, call AuthenticateMagicLink with the token passed in the query params. The response dictates if the user should be logged in or not. This request replaces AWS Cognito’s endpoints like ConfirmSignUp.

Step 6: Session management

While we work to integrate session management into our feature set, you’re welcome to continue using the same AWS Cognito endpoints to manage your tokens. This can be done in parallel with our Magic Link feature. After a user has been authenticated via the AuthenticateMagicLink endpoint, continue by making a request to AWS Cognito’s InitiateAuth with the user’s username and password to get the access tokens as you have been. This will require you to store the user’s username & password if you’ve relied on AWS Cognito to store them before. You will have to generate passwords for new users to use their InitiateAuth endpoint.


Stytch and Planetscale for user authentication

Use Stytch and Planetscale to build out your entire user authentication flow and database.

Docs Guide Image

Step 1: Please use Node to continue this integration guide

This guide is only supported for Node. Please select Node in the language selector at the top of this page to view this guide.