> ## Documentation Index
> Fetch the complete documentation index at: https://stytch.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Add login or signup

> Build a centralized login or signup page across orgs with Discovery login, where users authenticate first before selecting which organization to log into.

## Quickstart

Select a framework to start:

<Tabs>
  <Tab title="Next.js - App" icon="triangle">
    <Columns cols={3}>
      <Card title="Example app" icon="github" href="https://github.com/stytchauth/stytch-all-examples/tree/main/frontend/nextjs/prebuilt/b2b">
        Next.js code example
      </Card>

      <Card title="Web demo" icon="compass" href="https://www.surveyamp.com/login">
        Try out the login flow
      </Card>

      <Card title="SDK reference" icon="book-text" href="/api-reference/b2b/frontend-sdks/nextjs/overview">
        Next.js SDK reference
      </Card>
    </Columns>

    <Steps>
      <Step title="Before you start">
        * Have a `public_token` from your Stytch project & environment.
        * Enable and configure [Frontend SDKs](https://stytch.com/dashboard/sdk-configuration) in your Dashboard.
        * Add your application's domain to your project's [Authorized Domains](https://stytch.com/dashboard/sdk-configuration).
      </Step>

      <Step title="Install the Next.js SDK and configure your API key">
        1. In your Next.js app, run the command to install the SDK:

        ```bash npm icon=terminal theme={null}
        npm install @stytch/nextjs --save
        ```

        2. Then add your Stytch `public_token` to your project's `.env` file:

        ```dotEnv .env icon=file-code theme={null}
        NEXT_PUBLIC_STYTCH_PUBLIC_TOKEN=$PUBLIC_TOKEN
        ```
      </Step>

      <Step title="Set up a Stytch context provider">
        1. Create a custom `Stytch` wrapper component that initializes the Stytch client.

        ```jsx components/stytch-provider.tsx icon=file-code lines theme={null}
        'use client';

        import { createStytchB2BClient, StytchB2BProvider } from '@stytch/nextjs/b2b';

        const stytchClient = createStytchB2BClient(
          process.env.NEXT_PUBLIC_STYTCH_PUBLIC_TOKEN
        );

        export default function Stytch({ children }: { children: React.ReactNode }) {
          return <StytchB2BProvider stytch={stytchClient}>{children}</StytchB2BProvider>;
        }
        ```

        2. Wrap your application with `<Stytch>` to provide context to all child components:

        ```jsx app/layout.tsx icon=file-code lines {1,11} theme={null}
        import Stytch from './components/stytch-provider';

        export default function RootLayout({
          children,
        }: {
          children: React.ReactNode
        }) {
          return (
            <html>
              <body>
                <Stytch>{children}</Stytch>
              </body>
            </html>
          );
        }
        ```
      </Step>

      <Step title="Add <StytchB2B> UI component">
        1. Create a `<StytchB2B>` component.
        2. Set authentication methods and relevant options in the [config object](/api-reference/b2b/frontend-sdks/nextjs/prebuilt-ui/login/configuration).

        ```jsx components/LoginOrSignupDiscoveryForm.tsx icon=file-code lines theme={null}
        import { AuthFlowType, B2BProducts, StytchB2B } from '@stytch/nextjs/b2b';

        const config = {
          authFlowType: AuthFlowType.Discovery,
          products: [B2BProducts.emailMagicLinks, B2BProducts.oauth],
          emailMagicLinksOptions: {
            discoveryRedirectURL: 'https://localhost:3000/authenticate',
          },
          oauthOptions: {
            discoveryRedirectURL: 'https://localhost:3000/authenticate',
            providers: ['google'],
          },
          sessionOptions: {
            sessionDurationMinutes: 60,
          },
        };

        export const LoginOrSignupDiscoveryForm = () => {
          return <StytchB2B config={config} />;
        };
        ```
      </Step>

      <Step title="Set redirect URLs, if necessary">
        Point `discoveryRedirectURL` to the URL in your app where users are redirected back to after clicking on their email magic link or after completing OAuth:

        * **Using a single route:** Set the redirect back to the `/login` route if you plan on having one shared experience for both the start (login or signup) and end (MFA, organization discovery) of the authentication flow.
        * **Using separate routes:** Set the redirect to a new route (e.g. `/authenticate`) if you want a different user experience between the start and the end of the authentication flow. For example, a marketing-oriented login page that redirects to a more focused authentication experience for MFA and organization selection.

        <Note>
          For security, add redirect URLs in the [Dashboard](https://stytch.com/dashboard/redirect-urls) before being used.
        </Note>
      </Step>

      <Step title="Add <LoginOrSignupDiscoveryForm> to your login page(s)">
        1. Add `<LoginOrSignupDiscoveryForm>` to your `/login` page.

        ```jsx app/login/page.tsx icon=file-code theme={null}
        import { useEffect } from 'react';
        import { useRouter } from 'next/navigation';
        import { useStytchMemberSession } from '@stytch/nextjs/b2b';
        import { LoginOrSignupDiscoveryForm } from "src/components/LoginOrSignupDiscoveryForm";

        export default function Login() {
          const { session, isInitialized } = useStytchMemberSession();
          const router = useRouter();

          // Route users to your app once they have fully authenticated (either immediately or upon completing the remainder of the auth flow, like MFA)
          useEffect(() => {
            if (session && isInitialized) {
              router.replace("/home");
            }
          }, [session, isInitialized, router]);

          if (!isInitialized || session) {
            return <p>Loading...</p>;
          }

          return <LoginOrSignupDiscoveryForm/>;
        }
        ```

        2. If you're using separate routes, add `<LoginOrSignupDiscoveryForm>` to your `/authenticate` redirect route as well, e.g. `app/authenticate/page.tsx` or `pages/authenticate.tsx`.
      </Step>

      <Step title="Handle session and member data" icon="check">
        After a user selects an organization, the `<StytchB2B>` component automatically exchanges their `intermediate_session_token` for a fully minted `session_token` and `session_jwt`, both of which are stored in browser cookies.

        At this point, you can retrieve [Session data](/api-reference/b2b/api/sessions/session-object) and [Member data](/api-reference/b2b/api/members/member-object) via the SDK. For example, [`useStytchMemberSession()`](/api-reference/b2b/frontend-sdks/nextjs/hooks/use-stytch-member-session) lets you easily check for an active session.
      </Step>
    </Steps>
  </Tab>

  <Tab title="Next.js - Pages" icon="triangle">
    <Columns cols={3}>
      <Card title="Example app" icon="github" href="https://github.com/stytchauth/stytch-all-examples/tree/main/frontend/nextjs/prebuilt/b2b">
        Next.js code example
      </Card>

      <Card title="Web demo" icon="compass" href="https://www.surveyamp.com/login">
        Try out the login flow
      </Card>

      <Card title="SDK reference" icon="book-text" href="/api-reference/b2b/frontend-sdks/nextjs/overview">
        Next.js SDK reference
      </Card>
    </Columns>

    <Steps>
      <Step title="Before you start">
        * Have a `public_token` from your Stytch project & environment.
        * Enable and configure [Frontend SDKs](https://stytch.com/dashboard/sdk-configuration) in your Dashboard.
        * Add your application's domain to your project's [Authorized Domains](https://stytch.com/dashboard/sdk-configuration).
      </Step>

      <Step title="Install the Next.js SDK and configure your API key">
        1. In your Next.js app, run the command to install the SDK:

        ```bash npm icon=terminal theme={null}
        npm install @stytch/nextjs --save
        ```

        2. Then add your Stytch `public_token` to your project's `.env` file:

        ```dotEnv .env icon=file-code theme={null}
        NEXT_PUBLIC_STYTCH_PUBLIC_TOKEN=$PUBLIC_TOKEN
        ```
      </Step>

      <Step title="Wrap your application in <StytchB2BProvider>">
        1. Initialize the Stytch client through `createStytchB2BClient()`.
        2. Pass the Stytch client to the `<StytchB2BProvider>` component at the root of your application, making it accessible to all child components.

        ```jsx pages/_app.tsx {2,3,6,10,12} icon=file-code lines theme={null}
        // For Page Router setups
        import { createStytchB2BClient, StytchB2BProvider } from '@stytch/nextjs/b2b';

        const stytch = createStytchB2BClient(process.env.NEXT_PUBLIC_STYTCH_PUBLIC_TOKEN!);

        export default function MyApp({ Component, pageProps }: AppProps) {
          return (
            <StytchProvider stytch={stytch}>
              <Component {...pageProps} />
            </StytchProvider>
          );
        }
        ```
      </Step>

      <Step title="Add <StytchB2B> UI component">
        1. Create a `<StytchB2B>` component.
        2. Set authentication methods and relevant options in the [config object](/api-reference/b2b/frontend-sdks/nextjs/prebuilt-ui/login/configuration).

        ```jsx components/LoginOrSignupDiscoveryForm.tsx icon=file-code lines theme={null}
        import { StytchB2B } from '@stytch/nextjs/b2b';
        import { AuthFlowType, B2BProducts } from '@stytch/vanilla-js/b2b';

        const config = {
          authFlowType: AuthFlowType.Discovery,
          products: [B2BProducts.emailMagicLinks, B2BProducts.oauth],
          emailMagicLinksOptions: {
            discoveryRedirectURL: 'https://localhost:3000/authenticate',
          },
          oauthOptions: {
            discoveryRedirectURL: 'https://localhost:3000/authenticate',
            providers: ['google'],
          },
          sessionOptions: {
            sessionDurationMinutes: 60,
          },
        };

        export const LoginOrSignupDiscoveryForm = () => {
          return <StytchB2B config={config} />;
        };
        ```
      </Step>

      <Step title="Set redirect URLs, if necessary">
        Point `discoveryRedirectURL` to the URL in your app where users are redirected back to after clicking on their email magic link or after completing OAuth:

        * **Using a single route:** Set the redirect back to the `/login` route if you plan on having one shared experience for both the start (login or signup) and end (MFA, organization discovery) of the authentication flow.
        * **Using separate routes:** Set the redirect to a new route (e.g. `/authenticate`) if you want a different user experience between the start and the end of the authentication flow. For example, a marketing-oriented login page that redirects to a more focused authentication experience for MFA and organization selection.

        <Note>
          For security, add redirect URLs in the [Dashboard](https://stytch.com/dashboard/redirect-urls) before being used.
        </Note>
      </Step>

      <Step title="Add <LoginOrSignupDiscoveryForm> to your login page(s)">
        1. Add `<LoginOrSignupDiscoveryForm>` to your `/login` page.

        ```jsx pages/login.tsx icon=file-code lines theme={null}
        import { useEffect } from 'react';
        import { useRouter } from 'next/router';
        import { useStytchMemberSession } from '@stytch/nextjs/b2b';
        import { LoginOrSignupDiscoveryForm } from "src/components/LoginOrSignupDiscoveryForm";

        export default function Login() {
          const { session, isInitialized } = useStytchMemberSession();
          const router = useRouter();

          // Routes users to your app once they have fully authenticated (either immediately or upon completing the remainder of the auth flow, like MFA)
          useEffect(() => {
            if (session && isInitialized) {
              router.replace("/home");
            }
          }, [session, isInitialized, router]);

          if (!isInitialized || session) {
            return <p>Loading...</p>;
          }

          return <LoginOrSignupDiscoveryForm/>;
        }
        ```

        2. If you're using separate routes, add `<LoginOrSignupDiscoveryForm>` to your `/authenticate` redirect route as well, e.g. `app/authenticate/page.tsx` or `pages/authenticate.tsx`.
      </Step>

      <Step title="Handle session and member data" icon="check">
        After a user selects an organization, the `<StytchB2B>` component automatically exchanges their `intermediate_session_token` for a fully minted `session_token` and `session_jwt`, both of which are stored in browser cookies.

        At this point, you can retrieve [Session data](/api-reference/b2b/api/sessions/session-object) and [Member data](/api-reference/b2b/api/members/member-object) via the SDK. For example, [`useStytchMemberSession()`](/api-reference/b2b/frontend-sdks/nextjs/hooks/use-stytch-member-session) lets you easily check for an active session.
      </Step>
    </Steps>
  </Tab>

  <Tab title="React" icon="react">
    <Columns cols={3}>
      <Card title="Example app" icon="github" href="https://github.com/stytchauth/stytch-all-examples/tree/main/frontend/react/prebuilt/b2b">
        React code example
      </Card>

      <Card title="Web demo" icon="compass" href="https://www.surveyamp.com/login">
        Try out the login flow
      </Card>

      <Card title="SDK reference" icon="book-text" href="/api-reference/b2b/frontend-sdks/react/overview">
        React SDK reference
      </Card>
    </Columns>

    <Steps>
      <Step title="Before you start">
        * Have a `public_token` from your Stytch project & environment.
        * Enable and configure [Frontend SDKs](https://stytch.com/dashboard/sdk-configuration) in your Dashboard.
        * Add your application's domain to your project's [Authorized Domains](https://stytch.com/dashboard/sdk-configuration).
      </Step>

      <Step title="Install the React SDK and configure your API key">
        In your React app, run the command to install the SDK:

        ```bash npm icon=terminal theme={null}
        npm install @stytch/react --save
        ```
      </Step>

      <Step title="Wrap your application in <StytchB2BProvider>">
        1. Initialize the Stytch client through `createStytchB2BClient()`.
        2. Pass the Stytch client to the `<StytchB2BProvider>` component at the root of your application, making it accessible to all child components.

        ```jsx lines theme={null}
        import { createStytchB2BClient, StytchB2BProvider } from '@stytch/react/b2b';

        const stytch = createStytchB2BClient($YOUR_PUBLIC_KEY);

        // Add the component at the root of your application
        export function App() {
          return (
            <StytchB2BProvider stytch={stytch}>
              {/* Your app code */}
            </StytchB2BProvider>
          );
        }
        ```
      </Step>

      <Step title="Add <StytchB2B> UI component">
        1. Create a `<StytchB2B>` component.
        2. Set authentication methods and relevant options in the [config object](/api-reference/b2b/frontend-sdks/react/prebuilt-ui/login/configuration).

        ```jsx lines theme={null}
        import { AuthFlowType, B2BProducts, StytchB2B } from '@stytch/react/b2b';

        const config = {
          authFlowType: AuthFlowType.Discovery,
          products: [B2BProducts.emailMagicLinks, B2BProducts.oauth],
          emailMagicLinksOptions: {
            discoveryRedirectURL: 'https://localhost:3000/authenticate',
          },
          oauthOptions: {
            discoveryRedirectURL: 'https://localhost:3000/authenticate',
            providers: ['google'],
          },
          sessionOptions: { sessionDurationMinutes: 60 },
        };

        const LoginOrSignup = () => {
          return <StytchB2B config={config} />;
        };
        ```
      </Step>

      <Step title="Set redirect URLs, if necessary">
        Point `discoveryRedirectURL` to the URL in your app where users are redirected back to after clicking on their email magic link or after completing OAuth:

        * **Using a single route:** Set the redirect back to the `/login` route if you plan on having one shared experience for both the start (login or signup) and end (MFA, organization discovery) of the authentication flow.
        * **Using separate routes:** Set the redirect to a new route (e.g. `/authenticate`) if you want a different user experience between the start and the end of the authentication flow. For example, a marketing-oriented login page that redirects to a more focused authentication experience for MFA and organization selection.

        <Note>
          For security, add redirect URLs in the [Dashboard](https://stytch.com/dashboard/redirect-urls) before being used.
        </Note>
      </Step>

      <Step title="Add <LoginOrSignup> to your login page(s)">
        1. Add `<LoginOrSignup>` to your `/login` page:

        ```jsx Login.tsx icon=file-code lines theme={null}
        import { useStytchMemberSession } from "@stytch/react/b2b";
        import { Navigate } from "react-router";
        import { LoginOrSignup } from "./LoginOrSignup";

        export const Login = () => {
          const { session } = useStytchMemberSession();

          // Route users to your app once they have fully authenticated (either immediately or upon completing the remainder of the auth flow, like MFA)
          if (session) {
            return <Navigate to="/home" />;
          }

          return <LoginOrSignup />;
        };
        ```

        2. If you're using separate routes, add `<LoginOrSignup>` to your `/authenticate` redirect route as well, e.g. `Authenticate.tsx`.
      </Step>

      <Step title="Handle session and member data" icon="check">
        After a user selects an organization, the `<StytchB2B>` component automatically exchanges their `intermediate_session_token` for a fully minted `session_token` and `session_jwt`, both of which are stored in browser cookies.

        At this point, you can retrieve [Session data](/api-reference/b2b/api/sessions/session-object) and [Member data](/api-reference/b2b/api/members/member-object) via the SDK. For example, [`useStytchMemberSession()`](/api-reference/b2b/frontend-sdks/react/hooks/use-stytch-member-session) lets you easily check for an active session.
      </Step>
    </Steps>
  </Tab>

  <Tab title="Vanilla JS" icon="square-js">
    <Columns cols={3}>
      <Card title="Example app" icon="github" href="https://github.com/stytchauth/stytch-all-examples/tree/main/frontend/vanillajs/prebuilt/b2b">
        Vanilla JS code example
      </Card>

      <Card title="Web demo" icon="compass" href="https://www.surveyamp.com/login">
        Try out the login flow
      </Card>

      <Card title="SDK reference" icon="book-text" href="/api-reference/b2b/frontend-sdks/vanilla-js/overview">
        Vanilla JS SDK reference
      </Card>
    </Columns>

    <Steps>
      <Step title="Before you start">
        * Have a `public_token` from your Stytch project & environment.
        * Enable and configure [Frontend SDKs](https://stytch.com/dashboard/sdk-configuration) in your Dashboard.
        * Add your application's domain to your project's [Authorized Domains](https://stytch.com/dashboard/sdk-configuration).
      </Step>

      <Step title="Install the JS SDK and configure your API key">
        In your project, run the command to install the SDK:

        ```bash npm icon=terminal theme={null}
        npm install @stytch/vanilla-js --save
        ```
      </Step>

      <Step title="Initialize the Stytch client for your app">
        1. Initialize the Stytch client through `createStytchB2BClient()`.
        2. Export the initialized client as `stytch` so it can be used across your app.

        ```js js/stytch-client.js icon=file-code lines theme={null}
        import { createStytchB2BClient } from "@stytch/vanilla-js/b2b";
        export const stytch = createStytchB2BClient($YOUR_PUBLIC_KEY);
        ```
      </Step>

      <Step title="Mount the Stytch UI components">
        1. Create a `login.js` file to initialize and mount `stytch`.
        2. Set authentication methods and relevant options in the [config object](/api-reference/b2b/frontend-sdks/vanilla-js/prebuilt-ui/login/configuration).

        ```js js/login.js icon=file-code lines theme={null}
        import { B2BProducts, StytchB2B } from '@stytch/vanilla-js/b2b'
        import { stytch } from "./stytch-client.js";

        // Stytch SDK method to get the current session synchronously
        const session = stytch.session.getSync();
        if (session) {
          // User already has a session, redirect to your app
          window.location.href = "/home";
          return;
        }

        // Register the stytch-ui custom element
        customElements.define('stytch-ui', StytchB2B);

        // Pass in the Stytch client and configuration
        const login = document.getElementById('stytch-ui');
        login.render({
          client: stytch,
          config: {
            authFlowType: "Discovery",
            products: [B2BProducts.emailMagicLinks, B2BProducts.oauth],
            sessionOptions: { sessionDurationMinutes: 60 },
            emailMagicLinks: {
              discoveryRedirectURL: "https://localhost:3000/authenticate",
            },
            oauthOptions: {
              discoveryRedirectURL: "https://localhost:3000/authenticate",
              providers: [{ type: "google" }],
            },
          },
        });
        ```
      </Step>

      <Step title="Set redirect URLs, if necessary">
        Point `discoveryRedirectURL` to the URL in your app where users are redirected back to after clicking on their email magic link or after completing OAuth:

        * **Using a single route:** Set the redirect back to the `/login` route if you plan on having one shared experience for both the start (login or signup) and end (MFA, organization discovery) of the authentication flow.
        * **Using separate routes:** Set the redirect to a new route (e.g. `/authenticate`) if you want a different user experience between the start and the end of the authentication flow. For example, a marketing-oriented login page that redirects to a more focused authentication experience for MFA and organization selection.

        <Note>
          For security, add redirect URLs in the [Dashboard](https://stytch.com/dashboard/redirect-urls) before being used.
        </Note>
      </Step>

      <Step title="Add Stytch UI on your login page(s)">
        1. Add `<stytch-ui>` on your `/login` page:

        ```html login.html {5,6} icon=file-code lines theme={null}
        <!DOCTYPE html>
        <html lang="en">
          <head>...</head>
          <body>
            <stytch-ui id="stytch-ui" />
            <script type="module" src="js/login.js"></script>
          </body>
        </html>
        ```

        2. If you're using separate routes, add `<stytch-ui>` on your `/authenticate` redirect route as well, e.g. `authenticate.html`.
      </Step>

      <Step title="Handle session and member data" icon="check">
        After a user selects an organization, the Stytch UI component automatically exchanges their `intermediate_session_token` for a fully minted `session_token` and `session_jwt`, both of which are stored in browser cookies.

        At this point, you can retrieve [Session data](/api-reference/b2b/api/sessions/session-object) and [Member data](/api-reference/b2b/api/members/member-object) via the SDK. For example, [`session.getSync()`](/api-reference/b2b/frontend-sdks/vanilla-js/methods/sessions/get-session-sync) lets you retrieve the current session and can be used to determine if a user is already logged in.
      </Step>
    </Steps>
  </Tab>
</Tabs>

## Next steps

* Authentication methods
* Session management
