/
Contact usSee pricingStart building
Node
​

    About Stytch

    Introduction
    Integration Approaches
      Full-stack overview
      Frontend (pre-built UI)
      Frontend (headless)
      Backend
    Migrations
      Migration overview
      Migrating users statically
      Migrating users dynamically
      Additional migration considerations
      Zero-downtime deployment
      Defining external IDs for users
      Exporting from Stytch
    Custom Domains
      Overview

    Authentication

    DFP Protected Auth
      Overview
      Setting up DFP Protected Auth
      Handling challenges
    Magic Links
    • Email Magic Links

      • Getting started with the API
        Getting started with the SDK
        Replacing your password reset flow
        Building an invite user flow
        Add magic links to an existing auth flow
        Adding PKCE to a Magic Link flow
        Magic Link redirect routing
    • Embeddable Magic Links

      • Getting started with the API
    MFA
      Overview
      Backend integration
      Frontend integration
    Mobile Biometrics
      Overview
    M2M Authentication
      Authenticate an M2M Client
      Rotate client secrets
      Import M2M Clients from Auth0
    OAuth
    • Identity providers

      • Overview
        Provider setup
      Getting started with the API (Google)
      Add Google One Tap via the SDK
      Email address behavior
      Adding PKCE to an OAuth flow
    Connected AppsBeta
      Setting up Connected Apps
      About Remote MCP Servers
    • Resources

      • Integrate with AI agents
        Integrate with MCP servers
        Integrate with CLI Apps
    Passcodes
      Getting started with the API
      Getting started with the SDK
    • Toll fraud

      • What is SMS toll fraud?
        How you can prevent toll fraud
      Unsupported countries
    Passkeys & WebAuthn
    • Passkeys

      • Passkeys overview
        Set up Passkeys with the frontend SDK
    • WebAuthn

      • Getting started with the API
        Getting started with the SDK
    Passwords
      Getting started with the API
      Getting started with the SDK
      Password strength policy
    • Email verification

      • Overview
        Email verification before password creation
        Email verification after password creation
    Sessions
      How to use sessions
      Backend integrations
      Frontend integrations
      Custom claims
      Custom claim templates
      Session tokens vs JWTs
      How to use Stytch JWTs
    TOTP
      Getting started with the API
      Getting started with the SDK
    Web3
      Getting started with the API
      Getting started with the SDK

    Authorization

    Implement RBAC with metadata

    3rd Party Integrations

    Planetscale
    Supabase
    Feathery
    Unit

    Testing

    E2E testing
    Sandbox values
Get support on SlackVisit our developer forum

Contact us

Consumer Authentication

/

Guides

/

Authentication

/

TOTP

/

Getting started with the API

Setting up 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.

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.

const stytch = require("stytch")

const client = new stytch.Client({
    project_id: "PROJECT_ID",
    secret: "SECRET",
    env: stytch.envs.test,
  }
);

const params = {
    email: "sandbox@stytch.com",
};
client.users.create(params)
    .then(resp => {
        console.log(resp)
    })
    .catch(err => {
        console.log(err)
    });

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 expeditiously prompt the user to complete the TOTP flow quickly after TOTP creation. Defaults to 1440 (1 day) 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.

const stytch = require("stytch")

const client = new stytch.Client({
    project_id: "PROJECT_ID",
    secret: "SECRET",
    env: stytch.envs.test,
  }
);

const params = {
    user_id: "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
    expiration_minutes: 60
};
client.totps.create(params)
    .then(resp => { console.log(resp) })
    .catch(err => { console.log(err) });

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.

const stytch = require("stytch")

const client = new stytch.Client({
    project_id: "PROJECT_ID",
    secret: "SECRET",
    env: stytch.envs.test,
  }
);

const params = {
    user_id: "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
    totp_code: "576831"
};
client.totps.authenticate(params)
    .then(resp => { console.log(resp) })
    .catch(err => { console.log(err) });

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 forum, support@stytch.com, or in our community Slack.

Step 1: Create Stytch User

Step 2: Create a TOTP for the user

Step 3: Authenticating a TOTP code

Step 4: You're Done!