/
Contact usSee pricingStart building

    About B2B Saas Authentication

    Introduction
    Stytch B2B Basics
    Integration Approaches
      Full-stack overview
      Frontend (pre-built UI)
      Frontend (headless)
      Backend
    Next.js
      Routing
      Authentication
      Sessions
    Migrations
      Overview
      Reconciling data models
      Migrating user data
      Additional migration considerations
      Zero-downtime deployment
      Defining external IDs for members
      Exporting from Stytch
    Custom Domains
      Overview

    Authentication

    Single Sign On
    • Resources

      • Overview
        External SSO Connections
        Standalone SSO
    • Integration Guides

      • Start here
        Backend integration guide
        Headless integration guide
        Pre-built UI integration guide
    OAuth
    • Resources

      • Overview
        Authentication flows
        Identity providers
        Google One Tap
        Provider setup
    • Integration Guides

      • Start here
        Backend integration
        Headless frontend integration
        Pre-built UI frontend integration
    Connected AppsBeta
      Setting up Connected Apps
      About Remote MCP Servers
    • Resources

      • Integrate with AI agents
        Integrate with a remote MCP server
    Sessions
    • Resources

      • Overview
        JWTs vs Session Tokens
        How to use Stytch JWTs
        Custom Claims
    • Integration Guides

      • Start here
        Backend integration
        Frontend integration
    Email OTP
      Overview
    Magic Links
    • Resources

      • Overview
        Email Security Scanner Protections
    • Integration Guides

      • Start here
        Backend integration
        Headless frontend integration
        Pre-built UI frontend integration
    Multi-Factor Authentication
    • Resources

      • Overview
    • Integration Guides

      • Start here
        Backend integration
        Headless frontend integration
        Pre-built UI frontend integration
    Passwords
      Overview
      Strength policies
    UI components
      Overview
      Implement the Discovery flow
      Implement the Organization flow
    DFP Protected Auth
      Overview
      Setting up DFP Protected Auth
      Handling challenges
    M2M Authentication
      Authenticate an M2M Client
      Rotate client secrets
      Import M2M Clients from Auth0

    Authorization & Provisioning

    RBAC
    • Resources

      • Overview
        Stytch Resources & Roles
        Role assignment
    • Integration Guides

      • Start here
        Backend integration
        Headless frontend integration
    SCIM
    • Resources

      • Overview
        Supported actions
    • Integration Guides

      • Using Okta
        Using Microsoft Entra
    Organizations
      Managing org settings
      JIT Provisioning

    Testing

    E2E testing
    Sandbox values
Get support on SlackVisit our developer forum

Contact us

B2B Saas Authentication

/

Guides

/

Authentication

/

Magic Links

/

Integration Guides

/

Headless frontend integration

Headless Frontend Integration of Email Magic Links

In Stytch’s B2B product there are two different versions of the EML authentication flow:

  1. Discovery Authentication: used for self-serve Organization creation or login prior to knowing the Organization context
  2. Organization-specific Authentication: used when you already know the Organization that the end user is trying to log into

The guides below cover how to offer Email Magic Links for both scenarios, using Stytch's headless frontend SDK.

Discovery Sign-Up or Login

The discovery flow is designed for situations where your end users are signing up or logging in from a central landing page, and have not specified which organization they are trying to access or are attempting to create a new Organization.

The sequence for how this flow works when using a headless integration approach is as follows:

Headless integration of discovery Magic Links

1
Complete config steps

If you haven't done so already:

  1. Complete the steps in the EML Integration Guide Start Here
  2. Enable the Frontend SDKs in your Stytch Dashboard
  3. In the Frontend SDK config, enable Create Organizations under "Enabled Methods"

2
Initiate discovery flow from login page

In your application’s UI, introduce a way for end users to input their email and trigger a magicLinks.email.discovery.send() method call with the provided email.

For example, with our React SDK:

import { useStytchB2BClient } from '@stytch/react/b2b';

export const Login = () => {
  const stytch = useStytchB2BClient();

  const sendDiscoveryEmail = () => {
    stytch.magicLinks.email.discovery.send({
      email_address: 'sandbox@stytch.com',
    });
  };

  return <button onClick={sendDiscoveryEmail}>Send email</button>;
};

Using the vanilla JS SDK this would look as follows:

<button onclick="sendDiscoveryEmail()">Send email</button>

<script>
  import { StytchB2BHeadlessClient } from '@stytch/vanilla-js/b2b/headless';
  const stytch = new StytchB2BHeadlessClient('STYTCH_PUBLIC_TOKEN');
  const sendDiscoveryEmail = () => {
    stytch.magicLinks.email.discovery.send({
      email_address: 'sandbox@stytch.com',
    });
  };
</script>

3
Configure redirect

Stytch will redirect the user to the Discovery RedirectURL you specified in the Stytch dashboard earlier. Upon receiving this callback you will exchange the token in the call for a list of Discovered Organizations that the user can choose to log into. An intermediate_session_token (IST) will also be returned, but the headless SDK will take care of setting this in cookies and including it in the follow up calls.

In React this looks like:

export const DiscoveryAuthenticate = () => {
  const stytch = useStytchB2BClient();

  useEffect(() => {
    const authenticate = async () => {
      const token = new URLSearchParams(window.location.search).get('token');
      const tokenType = new URLSearchParams(window.location.search).get('stytch_token_type');

      if (token && tokenType === 'discovery') {
        const { email_address, discovered_organizations } =
          await stytch.magicLinks.discovery.authenticate({
            discovery_magic_links_token: token,
          });
        // surface discovered organizations to user to select from
        console.log({ email_address, discovered_organizations });
      }
    };

    authenticate();
  }, [stytch.magicLinks.discovery]);

  return <div>Loading</div>;
};

In vanilla Javascript this looks like:

import { StytchB2BHeadlessClient } from '@stytch/vanilla-js/b2b/headless';
  const stytch = new StytchB2BHeadlessClient('STYTCH_PUBLIC_TOKEN');

  const token = new URLSearchParams(window.location.search).get('token');
  const tokenType = new URLSearchParams(window.location.search).get('stytch_token_type');

  if (token && tokenType === 'discovery') {
    const { email_address, discovered_organizations } = stytch.magicLinks.discovery.authenticate({
      discovery_magic_links_token: token
    });
    // surface discovered organizations to user to select from
    console.log({ email_address, discovered_organizations });
  }

4
Handle user selection

If the end user selects to login to an existing Organization, you can call the exchange intermediate session method with the selected OrgID.

For example, in React you would add:

import React, { useEffect } from 'react';
import { useStytchB2BClient } from '@stytch/react/b2b';

export const ExchangeIntermediateSession = () => {
  const stytch = useStytchB2BClient();

  useEffect(() => {
    stytch.discovery.intermediateSessions.exchange({
      organization_id: 'organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931'
    });
  });

  return <div>Log In</div>;
};

In vanilla Javascript you would add the following:

<button onclick="exchangeIntermediateSession()">Log In</button>

  <script>
    import { StytchB2BHeadlessClient } from '@stytch/vanilla-js/b2b/headless';
      const stytch = new StytchB2BHeadlessClient('STYTCH_PUBLIC_TOKEN');
      const ExchangeIntermediateSession = () => {
        stytch.discovery.intermediateSessions.exchange({
          organization_id: 'organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931'
        });
      };
  </script>

You can also optionally allow users the ability to create a new Organization instead of logging into an existing one. In order to enable this, ensure that you have enabled Create Organizations in the FE SDKs section of the Stytch Dashboard.

To support creating a new Organization through discovery in your application, add the following code with our React SDK:

import React, { useEffect } from 'react';
import { useStytchB2BClient } from '@stytch/react/b2b';

export const CreateOrganization = () => {
  const stytch = useStytchB2BClient();

  useEffect(() => {
    stytch.discovery.organizations.create();
  });

  return <div>Create Organization</div>;
};

Or with our vanilla Javascript SDK:

<button onclick="createOrganization()">Create Organization</button>

<script>
  import { StytchB2BHeadlessClient } from '@stytch/vanilla-js/b2b/headless';
  const stytch = new StytchB2BHeadlessClient('STYTCH_PUBLIC_TOKEN');
  const createOrganization = () => {
    stytch.discovery.organizations.create();
  };
</script>

The discovery.organizations.create() method has two optional parameters: organization_slug and organization_name where you can pass custom values. If organization name and slug are not provided Stytch will auto generate a name and slug based on the end user’s email address.

5
Test it out

Run your application and test out doing discovery login and sign-up!

Organization Login

If end users of your application login via a page that indicates which Organization they are trying to log into (e.g. <org-slug>.your-app.com or your-app.com/team/<org-slug>) you can offer organization login on that page.

The high level flow using our headless SDK is as follows:

Headless integration of Magic Link auth to organization

1
Complete config steps

If you haven't done so already:

  1. Complete the steps in the EML Integration Guide Start Here, including creating an Organization
  2. Enable the Frontend SDKs in your Stytch Dashboard

2
Support email input on organization login page

On your login page for the organization, take in a user's email address and call the magicLinks.email.loginOrSignup() method.

In our React SDK this would look like:

import { useStytchB2BClient } from '@stytch/react/b2b';

export const Login = () => {
  const stytch = useStytchB2BClient();

  const sendEmailMagicLink = () => {
    stytch.magicLinks.email.loginOrSignup({
      email_address: 'sandbox@stytch.com',
      organization_id: 'organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931',
    });
  };

  return <button onClick={sendEmailMagicLink}>Send email</button>;
};

In vanilla Javascript this would look as follows:

<button onclick="sendEmailMagicLink()">Login with email</button>

<script>
  import { StytchB2BHeadlessClient } from '@stytch/vanilla-js/b2b/headless';
  const stytch = new StytchB2BHeadlessClient('STYTCH_PUBLIC_TOKEN');
  const sendEmailMagicLink = () => {
    stytch.magicLinks.email.loginOrSignup({
      email_address: 'sandbox@stytch.com',
      organization_id:'organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931',
    });
  };
</script>

3
Configure callback

Stytch will redirect the user to the Login or Signup RedirectURL that you specified in the magicLinks.email.loginOrSignup() call, or the relevant default in the Stytch dashboard. The URL’s query parameters will contain stytch_token_type=multi_tenant_magic_links and an authentication token. Your application should extract the token from the URL and call the appropriate authentication method to finish the login process.

In our React SDK you would add the following:

import React, { useEffect } from 'react';
import { useStytchB2BClient, useStytchMemberSession } from '@stytch/react/b2b';

export const Authenticate = () => {
  const stytch = useStytchB2BClient();
  const { session } = useStytchMemberSession();

  useEffect(() => {
    if (session) {
      window.location.href = 'https://example.com/profile';
    } else {
      const token = new URLSearchParams(window.location.search).get('token');
      stytch.magicLinks.authenticate({
        magic_links_token: token,
        session_duration_minutes: 60,
      });
    }
  }, [stytch, session]);

  return <div>Loading</div>;
};

In vanilla Javascript you would add:

import { StytchB2BHeadlessClient } from '@stytch/vanilla-js/b2b/headless';
const stytch = new StytchB2BHeadlessClient('STYTCH_PUBLIC_TOKEN');

const token = new URLSearchParams(window.location.search).get('token');
stytch.magicLinks.authenticate({
  magic_links_token: token,
  session_duration_minutes: 60,
});

3
Test it out

Run your application and test out the flow using the Organization that you created earlier!

Discovery Sign-Up or Login

1.

Complete config steps

2.

Initiate discovery flow from login page

3.

Configure redirect

4.

Handle user selection

5.

Test it out

Organization Login

1.

Complete config steps

2.

Support email input on organization login page

3.

Configure callback

3.

Test it out