B2B Saas Authentication

/

Guides

/

About B2B Saas Authentication

/

Integration Approaches

/

Frontend (headless)

Stytch and frontend development (headless)

Our frontend SDKs can be utilized headlessly for developing and managing your auth client-side. With a robust set of headless features, our frontend SDKs not only allow you to create custom UIs and screens but also provide you with controls to customize auth flows. This guide covers the fundamental aspects and key considerations when implementing our frontend SDKs headlessly.

Here’s a list of libraries and options we offer for frontend development that can be used headlessly:

Refer to the SDK reference page for full documentation. You can also explore the example apps to get hands-on with the code.

Overview

Diagram for headless implementation

At a high-level, implementing Stytch headlessly on the client-side involves the following steps:

  1. The end user attempts to log into your application with your custom-built UI.
  2. Your frontend handles the UI events, collects all the necessary authentication data, and then utilizes Stytch’s frontend SDK methods to call the Stytch API to perform an auth-related operation.
  3. Stytch API processes the request and returns a response with pertinent data.
  4. Your frontend handles the response as needed, which may involve calling the Stytch API again, updating your UI, or relaying the data to your backend.
  5. Once the end user successfully authenticates, Stytch’s frontend SDK automatically manages the storage of session tokens using browser cookies or mobile storage.

Using the frontend SDK headlessly enables you to build your own custom UI, customize auth flows, and handle organization and session management — directly on the frontend. Our frontend SDK supports most features of the Stytch platform; however, there are certain operations that can only be done with a backend implementation.

Code examples

Here are some example code snippets that demonstrate the general idea of implementing Stytch headlessly.

Authentication flows

// Start the authentication flow
import { useStytchB2BClient, useStytchMember, useStytchMemberSession } from '@stytch/nextjs/b2b';

const Login = (organization) => {
  const stytchB2BClient = useStytchB2BClient();

  const sendEmailMagicLink = async () => {
    await stytchB2BClient.magicLinks.email.loginOrSignup({
      email_address: 'sandbox@stytch.com',
      organization_id: organization.organization_id
    });
  };

  return <button onClick={sendEmailMagicLink}>Login</button>;
...
// Complete the authentication flow
const Authenticate = () => {
  const stytchB2BClient = useStytchB2BClient();
  const router = useRouter();

  useEffect(() => {
    const token = router?.query?.token?.toString();
    stytchB2BClient.magicLinks.authenticate({
      magic_links_token: token,
      session_duration_minutes: 60,
    });
  }, [router, stytchB2BClient]);
...

Session management

// Validate session for protected pages and resources
const isAuthenticated = () => {
  const { session, fromCache }  = useStytchMemberSession();
  const router = useRouter();

  useEffect(() => {
    if (session && !fromCache) {
      // there's an active session
      router.replace("/profile");
    } 
  }, [session, fromCache, router]);
...
// Revoke session
const LogOut = () => {
  const stytchB2BClient = useStytchB2BClient();

  const revokeSession = async () => {
    await stytchB2BClient.session.revoke();
    router.push("/");
  };

  return <button onClick={revokeSession}>Log out</button>
...

Organization and member management

// Manage organization records
const EditOrganization = () => {
  const stytchB2BClient = useStytchB2BClient();

  const updateOrganization = async (e) => {
    e.preventDefault();
    const data = new FormData(e.target);

    await stytchB2BClient.organizations.update({
      organization_name: data.get('org-name'),
      mfa_policy: data.get('org-mfa-policy'),
      email_allowed_domains: data.get('org-email-domains'),
      email_invite: data.get('org-invite-setting'),
      email_jit_provisioning: data.get('org-jit-setting')
    });
  };

  return <form onSubmit={updateOrganization}>...</form>
...
// Manage member records
const EditMemberProfile = (member) => {
  const stytchB2BClient = useStytchB2BClient();

  const updateMember = async (e) => {
    e.preventDefault();
    const data = new FormData(e.target);

    await stytchB2BClient.organizations.member.update({
      member_id: member.member_id
      name: data.get('name'),
      untrusted_metadata: {
        profile_pic_url: data.get('profile-pic-url'),
      }
    });
  };

  return <form onSubmit={updateMember}>...</form>
...

Considerations when using our frontend SDKs

Session token storage

Our frontend JavaScript SDK automatically stores all minted Stytch session_token and session_jwt values in browser cookies or mobile storage. In order to strike the best balance between developer experience and security, these cookies are not HttpOnly. If HttpOnly cookies are a requirement for you, we recommend using a backend-only Stytch integration, where you can fully customize where and how session tokens are stored.

You can also allow session cookies to be available to all subdomains, e.g. api.yourapp.com, by configuring the StytchClientOptions. See this documentation for all options for cookie settings.

Hydrating sessions on the backend

Session authentication, specifically after the initial end user login, should be implemented on the backend in order to protect your application’s sensitive routes, data, or actions by authenticating each request’s session token or JWT.

If you’re authenticating users and minting sessions with our frontend SDKs, browser cookies will automatically be created for the session. As long as your backend shares a domain with your frontend, the session_token and session_jwt cookies will be included in the request headers on every call made to your backend. Your application can then use Stytch’s backend API endpoints to authenticate the session before returning any protected resources to your frontend.

You can read more about session hydration here.

Backend restricted operations

Certain Stytch operations and features are only available as backend implementations. These include but are not limited to:

PKCE (Proof Key for Code Exchange)

PKCE (Proof Key for Code Exchange) is a specification that makes certain login flows more secure by cryptographically validating that the flow starts and ends on the same device. When using our frontend JavaScript SDK, you can turn PKCE on or off for each Stytch product by simply flipping a toggle in the Frontend SDKs tab in the Stytch Dashboard.

For security purposes, PKCE is required when using any of our frontend mobile SDKs and when using a deep link as a redirect URL. When using a backend-only Stytch integration, you will be required to complete some additional implementation steps in order to enable PKCE, if desired.

Account enumeration

Stytch's Discovery Sign-up or Login flow is designed to protect against account enumeration, by requiring that the end user authenticate prior to being shown the Organizations they can log into. For centralized login pages, we strongly recommend this type of authenticated discovery as it is critical for both end user and organization data privacy.

Our Organization Login flow is intended to be hosted on an organization-specific page (e.g. <organization_slug>.your-app.com or your-app.com/teams/<organization_slug>) in order to make it more difficult to abuse for account enumeration compared to a centralized login page. However, by design this login view does not fully protect against account enumeration, as it surfaces the Organization's name and login methods. If the Organization allows Password or Magic Link authentication, these methods can also leak information about whether or not the user has an existing account on the Organization or is allowed to join based on Just-in-Time (JIT) Provisioning by Email Domain.

If your application requires further protections against account enumeration, we recommend enabling opaque errors, which can be toggled via the Frontend SDKs tab in the Stytch Dashboard. This feature prevents the Password and Magic Link methods from revealing whether a user has an existing account or is allowed to join based on JIT provisioning.

Alternatively, you can always take a backend-only integration approach to have complete control over the information and error messages that are shown to end users.

Toll fraud

SMS toll fraud, sometimes known as SMS pumping, is a form of fraud where bad actors partner with complicit telecom providers to send large amounts of traffic to unprotected SMS endpoints. In Stytch's B2B product, SMS OTP can only be used as a secondary factor, which greatly reduces the risk of abuse given the hurdle of needing to provide a verified email prior to being able to initiate the SMS.

Stytch provides the additional security measures in order to further reduce the risk of toll fraud attacks:

  • Rate Limits: Stytch has several layers of rate limits in place in order to mitigate the size and scope of toll fraud attacks
  • Smart Country Selection: By default, Stytch disables a number of high risk countries. You can find the full list on our unsupported countries reference. Reach out to support@stytch.com to enable additional international countries
  • Alerting and monitoring: Our on-call team has robust alerting and monitoring in place across several factors to ensure that we’re aware of and able to help mitigate manually if attackers have compromised your app

To fully protect against programmatic fraud, including toll fraud attacks, we recommend using our Device Fingerprinting Protected Auth Feature. Reach out to support here to learn more.

What’s next

Read our backend implementation guide.

If you have additional questions about our different integration options, please feel free to reach out to us in our community Slack, our developer forum, or at support@stytch.com for further guidance.