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.


Example apps

Learn more about how Stytch works and get up and running quickly using an example app. Want to dive into the products but not the code? Try out our demo app.


Starting with a template

Examples using the Stytch frontend SDKs, for web and mobile. Includes Email Magic Links and all of our OAuth providers, including Google One Tap!

example app


Guides

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


Setting up a new auth solution with the Stytch API

Managing user login with Stytch enables you to authenticate users on an ongoing basis via one-click, passwordless login. When a user signs up for your app, you'll add them to Stytch. Then, whenever a user goes to login to your app, authenticate them via a magic link.

Stytch data flow
  1. Step 1: Build a sign up or login view

    If you don't already have one, you'll need to build a sign up or login view for your app. You can collect any information you want, but you'll need to include an email field so the user can login with their email later.

    Step description
  2. Step 2: Create a route for authentication

    Create a route that will act as your magic link endpoint. Users will be directed there from the login email. The route should accept a token as a query parameter that you will use to authenticate. For example, your route should be something like https://example.com/authenticate. Users will be directed to https://example.com/authenticate?token=abc, where abc is the token you'll pass to our authentication endpoint.

  3. 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.

  4. Step 4: Send a magic link to log in or create a Stytch user

    Send either a login or create magic link to the user based on if the email is associated with a user already. If the user was created, use the user_id returned in the response to manage that user within Stytch. Save this user_id with your user's record in your app's storage.

    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": "sandbox@stytch.com",
          "login_magic_link_url": "https://example.com/authenticate",
          "signup_magic_link_url": "https://example.com/authenticate"
        }'
  5. Step 6: Going live

    Request your Live API keys in the dashboard and store them somewhere safe. We suggest using environment variables for your projectID and secret to keep them secure. Then, update the URL you’re using from https://test.stytch.com to https://api.stytch.com


Setting up a new login solution with the Stytch SDK

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
  1. 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.

  2. 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="stytch-sdk"></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: "#stytch-sdk",
      style: style,
      loginOrSignupView: loginOrSignupView
    });
  3. 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.

  1. Step 1: Create a password reset UI

    Here’s an example of a password reset component.

    Step description
  2. 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.

  3. 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": "sandbox@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.

  1. 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
  2. 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.

  3. 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": "sandbox@stytch.com",
    		"invite_magic_link_url": "https://example.com/authenticate"
    	}'
  4. 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.

  1. Step 1: Update your login UI

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

    Step description
  2. 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": "sandbox@stytch.com"
    	}'
  3. 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.

  1. 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
  2. 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"
    	}'
  3. 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 (MFA) with SMS

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

  1. 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
  2. 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"
    	}'
  3. 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"
    	}'
  4. 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 via the API

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.

  1. 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.

  2. 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/REPLACE_WITH_OAUTH_CALLBACK_ID
  3. 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.

  4. 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
  5. 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="
    	}'

Integrate Google One Tap via the SDK

Implement Google One Tap via the Javascript SDK.

  1. 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.

  2. 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 JavaScript origins section, add the origin where One Tap will appear. For example, if you plan on showing One Tap at https://example.com/login, enter https://example.com. If you're using localhost for testing, we recommend adding both http://localhost and http://locahost:[port]. Under the Authorized redirect URIs section, add the URL below. 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/REPLACE_WITH_OAUTH_CALLBACK_ID
  3. 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.

  4. Step 5: Add the SDK to your app

    Now that Stytch and Google are configured, you need to add the Stytch SDK to your application.

    import React from "react";
    import { Stytch } from "@stytch/stytch-react";
    
    const Login = () => {
      const STYTCH_PUBLIC_TOKEN = "PUBLIC_TOKEN";
      const stytchProps = {
        loginOrSignupView: {
          products: ['oauth'],
          oauthOptions: {
            providers: [{
              type: 'google',
              one_tap: true,
              position: 'embedded'
            }]
          },
        },
        publicToken: STYTCH_PUBLIC_TOKEN,
      };
    
      return (
        <div className="sign-in-container">
          <Stytch
            publicToken={stytchProps.publicToken}
            loginOrSignupView={stytchProps.loginOrSignupView}
          />
        </div>
      );
    };
    
    export default Login;
  5. 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 and session_jwt 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 90 days long (129600 minutes). If you provide this field, the authenticate method’s response field will include values for session, session_token, and session_jwt.

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

  1. 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"
    	}'
  2. Remember me for 30 days since you last saw me

    Everytime a session is authenticated, extend it for another 30 days (43200 minutes). This means that if the session continues to be successfully authenticated at least once every 30 days the user will remain logged in indefinitely, unless the session is explicitly revoked.

    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
    	}'
  3. 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"
    	}'
  4. 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"
    	}'
  5. 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"
    	}'

WebAuthn

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.

There are two steps during a WebAuthn authentication flow, registration and authentication. The first step handles registering a WebAuthn device to a user. The second step handles the authentication attempt.

For both the registration and authentication steps, you’ll make two Stytch requests. The first request returns the necessary components to communicate with the WebAuthn device. The second request is used to pass the response from the WebAuthn call back to Stytch for verification.

We’ll be using the webauthn-json library to assist this integration. This library converts the JSON request into the correct data types by unmarshalling and decoding the body and then outputs marshalled JSON that you can pass back to Stytch.

As you’re working through this guide, feel free to ask any questions if you get stuck in our Slack community or reach out to us at support@stytch.com

  1. Step 1: Create Stytch User

    If the user attempting to register isn’t associated with a Stytch user ID, you’ll have to add them with Stytch’s /v1/users/create endpoint if you haven’t already. Pass the user’s email address or phone number and store the returned user_id. The user_id will be used to register and authenticate with WebAuthn.

    curl --request POST \
    	--url https://test.stytch.com/v1/users \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    		"email": "sandbox@stytch.com"
    	}'
  2. Step 2: Start Registration Process

    To authenticate with WebAuthn, you first need to register an authenticator. This will have to happen once per registration. Start by generating the request needed for webauthn-json’s create call. To do this you’ll make a request to /v1/webauthn/register/start. You need two fields for the request, a Stytch user_id and the domain where the webauthn-json’s create call will be invoked, i.e. your login page’s domain. There are two optional fields, user_agent and authenticator_type. You can pass a user_agent to help identify the WebAuthn registration. This could be helpful for telling registrations apart. You can use authenticator_type to require a certain type of WebAuthn device, either platform (like a fingerprint reader) or cross-platform (like a YubiKey). If you omit the field, we’ll assume either type is acceptable.

    curl --request POST \
    	--url https://test.stytch.com/v1/webauthn/register/start \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    	    "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
    	    "domain": "example.com"
    	}'
  3. Step 3: Calling webauthn-json’s Create Method

    Using the public_key_credential_creation_options field from the /v1/webauthn/register/start response, call webauthn-json’s create method. You’ll want to handle any errors that crop up in this step, like if there are no WebAuthn devices available to register. If the WebAuthn call is successful, JSON.stringify the response and get ready for another Stytch call.

    import * as webauthnJson from '@github/webauthn-json'
    
    // You implemented this in Step 2
    const registerStartData = await callWebauthnRegisterStart()
    const credential = await webauthnJson.create({
      publicKey: registerStartData.public_key_credential_creation_options
    });
    // And you'll implement this in Step 4
    await callWebauthnRegister({
      public_key_credential: JSON.stringify(credential)
    })
  4. Step 4: Register the WebAuthn Registration with Stytch

    Next we’ll use the JSON string you created in Step 3 as the public_key_credential in our request to /v1/webauthn/register. Stytch will validate the credential and return the webauthn_registration_id if the registration is successful. The user now has a registered WebAuthn registration that can be used for authentication. We recommend saving the webauthn_registration_id and domain. This allows you to check that the user in question has a valid WebAuthn registration on file with Stytch before you call /v1/webauthn/authenticate/start for subsequent logins.

    curl --request POST \
    	--url https://test.stytch.com/v1/webauthn/register \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    	    "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
    	    "public_key_credential": "{\"type\":\"public-key\",\"id\":\"Ab6y28pCs5bVRIzSmrlufidfR57gRlEZ-KSTVGJYdkwAfR_SeaVXvdW6ND_XljM25cXYI-dSwrhjuNsj1L3uC0BHqN3mBQIzSswJneTv08RbDNZOLhjiwOEnQ03uPbL5eA7EcyinClOU_qwPMf5lowW1NSTWtaFvOlY\",\"rawId\":\"Ab6y28pCs5bVRIzSmrlufidfR57gRlEZ-KSTVGJYdkwAfR_SeaVXvdW6ND_XljM25cXYI-dSwrhjuNsj1L3uC0BHqN3mBQIzSswJneTv08RbDNZOLhjiwOEnQ03uPbL5eA7EcyinClOU_qwPMf5lowW1NSTWtaFvOlY\",\"response\":{\"clientDataJSON\":\"eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiaFladExOVDlTSWdacVBuS2ZiblFYM25DSjdOYXZUVF9TNm9DOVhSRVl2MEYiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjMwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9\",\"attestationObject\":\"o2NmbXRmcGFja2VkZ2F0dFN0bXSiY2FsZyZjc2lnWEYwRAIgLEvyXrb_aMCVOjpYBLpm3cPaaquDN0ouXaL27SF9Lp0CIB2f56tWUDvs6oBl3pMxIIrJqJhZKkK7btJtWVDLsFFbaGF1dGhEYXRhWP5Jlg3liA6MaHQ0Fw9kdmBbj-SuuaKGMseZXPO6gx2XY0VheZqwrc4AAjW8xgpkiwsl8fBVAwB6Ab6y28pCs5bVRIzSmrlufidfR57gRlEZ-KSTVGJYdkwAfR_SeaVXvdW6ND_XljM25cXYI-dSwrhjuNsj1L3uC0BHqN3mBQIzSswJneTv08RbDNZOLhjiwOEnQ03uPbL5eA7EcyinClOU_qwPMf5lowW1NSTWtaFvOlalAQIDJiABIVggFCI-4HODPxlfeBwfFyzQG_btRm_pB6mb9E1E-rANMwoiWCBCr6C2SQOGElh9N9OMzVBcMnOolAcvz3S0STbnNTHOmg\"},\"clientExtensionResults\":{}}"
    	}'
  5. Step 5: Start Authentication Process

    Similar to registering, authentication starts by generating the request for the webauthn-json’s get method. To do this you’ll make a request to /v1/webauthn/authenticate/start. You need two fields for the request, the user_id of the user and the domain the WebAuthn call will be invoked on.

    curl --request POST \
    	--url https://test.stytch.com/v1/webauthn/authenticate/start \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    	    "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6"
    	    "domain": "example.com"
    	}'
  6. Step 6: Calling webauthn-json’s Get Method

    Using the public_key_credential_request_options field from the /v1/webauthn/authenticate/start response, call webauthn-json’s get method. Again, you’ll want to handle any errors that might arise here. If webauthn-json’s get call is successful, JSON.stringify the response and get ready for another Stytch call.

    import * as webauthnJson from '@github/webauthn-json'
    
    // You implemented this in Step 5
    const authenticationStartData = await callWebauthnAuthenticateStart()
    const credential = await webauthnJson.get({
      publicKey: authenticationStartData.public_key_credential_request_options
    });
    // And you'll implement this in Step 7
    await callWebauthnAuthenticate({
      public_key_credential: JSON.stringify(credential)
    })
  7. Step 7: Authenticate the WebAuthn Registration with Stytch

    Using the JSON string you created from webauthn-json’s get method as the public_key_credential, make a request to /v1/webauthn/authenticate. Stytch will perform validation on the passed credential and return a 400 if there are any issues. If the authentication is successful, we’ll return a 200.

    curl --request POST \
    	--url https://test.stytch.com/v1/webauthn/authenticate \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    	    "public_key_credential": "{\"type\":\"public-key\",\"id\":\"Ab6y28pCs5bVRIzSmrlufidfR57gRlEZ-KSTVGJYdkwAfR_SeaVXvdW6ND_XljM25cXYI-dSwrhjuNsj1L3uC0BHqN3mBQIzSswJneTv08RbDNZOLhjiwOEnQ03uPbL5eA7EcyinClOU_qwPMf5lowW1NSTWtaFvOlY\",\"rawId\":\"Ab6y28pCs5bVRIzSmrlufidfR57gRlEZ-KSTVGJYdkwAfR_SeaVXvdW6ND_XljM25cXYI-dSwrhjuNsj1L3uC0BHqN3mBQIzSswJneTv08RbDNZOLhjiwOEnQ03uPbL5eA7EcyinClOU_qwPMf5lowW1NSTWtaFvOlY\",\"response\":{\"authenticatorData\":\"SZYN5YgOjGh7NBcPZHZgW1_krrmihjLHmVzzuoNcl2MFYZKokg\",\"clientDataJSON\":\"eyJ2eXBlOjopo2ViYBx0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiWEtEWDVJa25EWEU3by1KQlRkYTNfS1NiTXdmb3dMWDQxMldlNEFDY04tYWgiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjMwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9\",\"signature\":\"MEYCIQDU1FGXEBrq3hsQ2ye1pBcYLMu7zmzLVVdcbs6R21hGyAIhAJmpdBo2Hd7P4Ks9VFKBUYbKSIioMdhl2XIIjWHNKD77\",\"userHandle\":\"dXNlus1kZXZlbG9wLBC2M2E1MGI0LWEwMGEtNGU3NC89NTJmLTFlOGRhODE2nDBnMw\"},\"clientExtensionResults\":{}}"
    	}'
  8. Step 8: You're Done!

    You just finished all the critical components to authenticate your users via WebAuthn! Have any feedback after having integrated WebAuthn? Get in touch with us and tell us what you think in our Slack community or via support@stytch.com.


Time-based one-time passcodes (TOTP)

Time-based one-time passcodes (TOTP) are a passwordless two-factor authentication option that can be used when you need high security assurance. TOTP authentication solutions are ideal for particularly sensitive use cases that are also highly attractive in terms of the potential payoff they offer – think money movement in fintech or cryptocurrency, or access to a company’s HR or payroll information. When integrated as a second authentication factor, TOTP serves as an additional safeguard by requiring users to prove possession of their device. It works by generating a one-time passcode that’s based on the current time and a shared secret between an authenticator app like Google Authenticator or Authy, and the server (in this case, Stytch). Users, who must have an authenticator app downloaded on their device, are asked to input the unique passcode within a certain period of time, usually 30 seconds, as evidence of their identity. Once the user supplies the TOTP code, your app can use Stytch’s /totps/authenticate endpoint to verify that passcodes are valid and ultimately grant users access.

  1. Step 1: Create Stytch User

    If the user attempting to register isn’t already associated with a Stytch user_id, you’ll need to create a Stytch User with the /users/create endpoint. Pass the user’s email address or phone number into the User create endpoint and store the returned user_id. The user_id will be used to register and authenticate with TOTP.

    curl --request POST \
    	--url https://test.stytch.com/v1/users \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    		"email": "sandbox@stytch.com"
    	}'
  2. Step 2: Create a TOTP for the user

    Next, you’ll want to create a TOTP for the user by passing the user_id into the /totps/create endpoint. This endpoint also takes in an expiration_minutes value; this value is the expiration for the TOTP instance. The newly create TOTP instance must be authenticated at least once within this timeframe otherwise it will expire and be render unusable. Make sure to expeditiosly prompt the user to complete the TOTP flow quickly after TOTP creation. Defaults to 60 (1 hour) with a minimum of 5 and a maximum of 1440 (1 day).

    This endpoint returns four unique fields in addition to the stand fields like status_code and request_id. The secret is shared between the authenticator app and your server. The totp_id is the Stytch identifier for a given TOTP instance. The qr_code is the base64-encoded representation of the QR code image. You can embed this directly into your website and it will display as a QR code that users can scan. And finally recovery_codes, if the user loses access to their authenticator app, they can input these recovery codes into the /v1/totps/recover endpoint at any point. If the recovery code is valid, then the recover endpoint will return a 200, and you, the developer, can choose to delete the TOTP instance and generate a new one or simply display the secret back to the user. Note that 10 recovery codes are generated, and each one can only be used once.

    curl --request POST \
    	--url https://test.stytch.com/v1/totps \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    	    "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
    	    "expiration_minutes": 60,
    	}'
  3. Step 3: Authenticating a TOTP code

    Make sure that the user authenticates their first TOTP immediately after creating the TOTP so that the TOTP instance does not expire. When the user sends you the TOTP code, you will hit the /totps/authenticate endpoint with the user's user_id and the supplied totp_code to authenticate it.

    In this step, to accomodate for network and user action delays, TOTP codes from the previous and next 30-second periods are allowed by this endpoint. If you’d like to begin a new Stytch session or re-use an existing one, you may pass in session_duration_minutes(to begin a new session) or session_token(to re-use an existing one). Please check out our Session management guide for more information.

    curl --request POST \
        --url https://test.stytch.com/v1/totps/authenticate \
        -u 'PROJECT_ID:SECRET' \
        -H 'Content-Type: application/json' \
        -d '{
            "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
            "totp_code": "576831",
        }'
  4. Step 4: You're Done!

    You just finished all the critical components to add a second factor of authentication via TOTP! Have any feedback after having integrated TOTP? Get in touch with us and tell us what you think in our Slack community or via support@stytch.com.


Crypto wallets

Choose cryptocurrency

Ethereum

Our Crypto wallets product unlocks Web3 authentication in your app in four easy steps. For this guide we'll walk through integrating MetaMask, but you may integrate any Ethereum based wallet with Stytch, we'll talk about this more later in the guide.

As you're working through this guide, feel free to ask any questions you run into in our Slack community or via support@stytch.com.

  1. Step 1: Get Ethereum address

    To start, we need the user’s Ethereum address we want to authenticate with. We can use the following code snippet to fetch the user’s MetaMask Ethereum address from the browser. You’ll have to check if window.ethereum is defined – if it isn’t, the user doesn’t have MetaMask installed.

    const [address] = await window.ethereum.request({ method: 'eth_requestAccounts' });
        
  2. Step 2: Start Ethereum authentication

    Using the Ethereum address, make a request to /v1/crypto_wallets/authenticate/start. If you want to add this Ethereum address to an existing user, pass in that user’s user_id. If the Ethereum address doesn’t belong to a user yet, leaving out a user_id will create a new user automatically.

    curl --request POST \
    	--url https://test.stytch.com/v1/crypto-wallets/authenticate/start \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    	    "crypto_wallet_type": "ethereum",
    	    "crypto_wallet_address": "0x6df2dB4Fb3DA35d241901Bd53367770BF03123f1",
            "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6" // optional
    	}'
  3. Step 3: Signing the message

    Using the challenge field from the /v1/crypto_wallets/authenticate/start response, request the user to sign the message. The user will see a MetaMask popup asking to sign a message with the content from the challenge. You’ll also have to gracefully handle the situation where a user chooses to reject the message.

    // get challenge from authenticate/start call
    const signature = await window.ethereum.request({"method": "personal_sign", "params": [challenge, address]})
    Step description
  4. Step 4: Finish Ethereum authentication

    Using the signature from the signMessage call described in the last step, make a request to /v1/crypto_wallets/authenticate. Optionally, you may provide an existing session_token to reuse an existing session, and/or provide a session_duration_minutes value to set the lifetime of the session.

    Stytch will perform validation on the address, challenge, and signature and return a 400 if there are any issues. If the authentication is successful, we’ll return a 200.

    curl --request POST \
    	--url https://test.stytch.com/v1/crypto-wallets/authenticate/start \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    	    "crypto_wallet_type": "ethereum",
    	    "crypto_wallet_address": "0x6df2dB4Fb3DA35d241901Bd53367770BF03123f1",
            "signature": "0x0c4f82edc3c818b6beff4b89e0682994e5878074609903cecdfb843241728be32f75949e2fbae63dcccdef97c0e3789a26441f7e11456cc1f2ef79b3a436010f1b"
    	}'
  5. Step 5: You're Done!

    You just finished all the critical components to authenticate your users with a MetaMask wallet! Have any feedback after having integrated Ethereum with your app? Get in touch with us and tell us what you think in our Slack community or via support@stytch.com.


Client libraries

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


Security

Stytch services are designed, developed, monitored, and updated to protect you and your users's data and privacy. Stytch is compliant with a range of industry standards and frameworks that assist with your own security and regulatory needs.

  • SOC 2 - Stytch maintains a SOC 2 type II report attesting to the company’s compliance with the AICPA’s Trust Service Criteria.
  • HIPAA - Stytch is compliant with the Health Insurance Portability and Accountability Act as a business associate.
  • GDPR & CCPA - Stytch is committed to complying with and helping its customers comply with the General Data Protection Regulation (GDPR) and California Consumer Privacy Act (CCPA).

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 tokens in the /magic_links/authenticate endpoint and receive the corresponding responses.

  • 200 Success: DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=

  • 401 Unauthorized: 3pzjQpgksDlGKWEwUq2Up--hCHC_0oamfLHyfspKDFU=

  • 404 Magic link not found: CprTtwhnRNiMBiUS2jSLcWYrfuO2POeBNdo5HhW6qTM=

In some scenarios, it may be helpful to test sending a One-time Passcode (OTP) without actually sending a message. You can use the phone number +10000000000, for our /otps/sms/send and /otps/whatsapp/send endpoints, and sandbox@stytch.com for our /otps/email/send endpoint, to test sending an OTP in either our Live or Test environments. If your API credentials and the request format are correct, you will receive a 200 status response but no message will actually be sent.

You can use the following code, and the method_id you received in the 200 response from /otps/xxx/send, in the /otps/authenticate endpoint and receive the corresponding response.

  • 200 Success: 000000

You can use the following session_tokens to test the /sessions/authenticate 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.

  1. Step 1: Update your login UI

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

    Step description
  2. 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.

  3. 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": "sandbox@stytch.com",
            "login_magic_link_url": "https://example.com/login",
            "signup_magic_link_url": "https://example.com/signup"
    	}'
  4. 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.

  5. 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.

  1. Step 1: Update your login UI

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

    Step description
  2. 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.

  3. 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": "sandbox@stytch.com",
            "login_magic_link_url": "https://example.comlogin",
            "signup_magic_link_url": "https://example.comsignup"
        }'
  4. 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.

  5. 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
  1. 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.


Stytch and Supabase

Check out the Stytch integration guide in the Supabase documentation. In this guide you will build a simple expense tracker application using Stytch for authentication and Supabase as a database.