Authentication

Authentication flows can be handled on the frontend (NextJS SDK) or the backend (Node SDK).

Implementation differs between Discovery and Organization login flows; the examples below will use the Organization login flow.

Authentication flows

The following is an example implementation of an Organization login flow using our Email Magic Links product with our NextJS SDK.

// To launch our prebuilt UI components
import React, { useEffect, useState } from "react";
import { StytchB2B } from "@stytch/nextjs/b2b";
import {
  AuthFlowType,
  B2BProducts,
  StytchB2BUIConfig,
} from "@stytch/vanilla-js";

const TenantedLoginForm = () => {
  const [config, setConfig] = useState<StytchB2BUIConfig | null>();

  useEffect(() => {
    setConfig({
      products: [B2BProducts.emailMagicLinks],
      sessionOptions: { sessionDurationMinutes: 60 },
      emailMagicLinksOptions: {
        loginRedirectURL: `${window.location.origin}/authenticate`,
        signupRedirectURL: `${window.location.origin}/authenticate`,
      },
      authFlowType: AuthFlowType.Organization,
    });
  }, []);

  return config ? <StytchB2B config={config} /> : null;
};

export default TenantedLoginForm;

Since Email Magic Links is a redirect-based authentication flow, you’ll also need to re-launch the UI component at the loginRedirectURL and signupRedirectURL defined above to ultimately authenticate the Magic token:

const Authenticate = () => {
  const [config, setConfig] = useState<StytchB2BUIConfig | null>();
  const router = useRouter();

  useEffect(() => {
    setConfig({
      products: [B2BProducts.emailMagicLinks],
      sessionOptions: { sessionDurationMinutes: 60 },
      authFlowType: AuthFlowType.Organization,
    });
  }, []);

  return config ? (
    <StytchB2B
      config={config}
      callbacks={{
        onEvent: async ({ type, data }) => {
          if (type === StytchEventType.B2BDiscoveryIntermediateSessionExchange) {
            router.push(`/${data.organization.organization_slug}/dashboard`);
          } else if (type === StytchEventType.B2BDiscoveryOrganizationsCreate) {
            router.push(`/${data.organization.organization_slug}/dashboard`);
          } else if (type === StytchEventType.B2BMagicLinkAuthenticate) {
            router.push(`/${data.organization.organization_slug}/dashboard`);
          } else if (type === StytchEventType.B2BSSOAuthenticate) {
            router.push(`/${data.organization.organization_slug}/dashboard`);
          }
        },
      }}
    />
  ) : null;
};

export default Authenticate;

Read more about how our pre-built UI components handles Organization login and Discovery login flows.