# WorkOS
URL: /guides/add-authentication/workos

WorkOS is an enterprise-grade authentication and user management platform that provides features like SSO, SCIM provisioning, and directory sync. This guide shows how to integrate it with Tambo in a Next.js application.

<Callout type="info" title="Prerequisites">
  This guide assumes you've already set up WorkOS in your Next.js application,
  including the callback route for handling authentication responses. If you
  haven't, follow the [WorkOS Next.js Quick
  Start](https://workos.com/docs/user-management/nextjs) first.
</Callout>

## Installation

Install the required packages:

```bash
npm install @workos-inc/node @tambo-ai/react
```

## Integration Options

### Server-Side Token Retrieval (Recommended)

Use this approach for better security and performance, especially when you don't need real-time authentication state changes.

```tsx title="app/layout.tsx"
import { getSession } from "@workos-inc/node/middleware";
import ClientLayout from "./client-layout";

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const session = await getSession({
    cookiePassword: process.env.WORKOS_COOKIE_PASSWORD!,
  });

  return (
    <html lang="en">
      <body>
        <ClientLayout userToken={session?.accessToken}>{children}</ClientLayout>
      </body>
    </html>
  );
}
```

```tsx title="app/client-layout.tsx"
"use client";

import { TamboProvider } from "@tambo-ai/react";
import { ReactNode } from "react";

interface ClientLayoutProps {
  children: ReactNode;
  userToken?: string;
}

export default function ClientLayout({
  children,
  userToken,
}: ClientLayoutProps) {
  return <TamboProvider userToken={userToken}>{children}</TamboProvider>;
}
```

### Client-Side Token Retrieval

Use this approach when you need real-time authentication state management or client-side routing with authentication guards.

First, create a custom hook for WorkOS authentication:

```tsx title="hooks/use-workos-auth.ts"
import { useEffect, useState } from "react";

interface UseWorkOSAuthReturn {
  accessToken: string | null;
  user: any | null;
  loading: boolean;
}

export function useWorkOSAuth(): UseWorkOSAuthReturn {
  const [accessToken, setAccessToken] = useState<string | null>(null);
  const [user, setUser] = useState<any | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchSession = async () => {
      try {
        const response = await fetch("/api/auth/session");
        if (response.ok) {
          const data = await response.json();
          setAccessToken(data.accessToken);
          setUser(data.user);
        }
      } catch (error) {
        console.error("Error fetching session:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchSession();
  }, []);

  return { accessToken, user, loading };
}
```

Create a session API endpoint:

```tsx title="app/api/auth/session/route.ts"
import { NextRequest, NextResponse } from "next/server";
import { getSession } from "@workos-inc/node/middleware";

export async function GET(request: NextRequest) {
  try {
    const session = await getSession({
      cookiePassword: process.env.WORKOS_COOKIE_PASSWORD!,
    });

    if (!session?.accessToken) {
      return NextResponse.json({ error: "No access token" }, { status: 401 });
    }

    return NextResponse.json({
      accessToken: session.accessToken,
      user: session.user,
    });
  } catch (error) {
    return NextResponse.json({ error: "Invalid session" }, { status: 401 });
  }
}
```

Use the hook in your client layout:

```tsx title="app/client-layout.tsx"
"use client";

import { TamboProvider } from "@tambo-ai/react";
import { useWorkOSAuth } from "@/hooks/use-workos-auth";
import { ReactNode } from "react";

interface ClientLayoutProps {
  children: ReactNode;
}

export default function ClientLayout({ children }: ClientLayoutProps) {
  const { accessToken, loading } = useWorkOSAuth();

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <TamboProvider userToken={accessToken || undefined}>
      {children}
    </TamboProvider>
  );
}
```

## Usage

Once configured, you can use Tambo components throughout your application:

```tsx title="app/dashboard/page.tsx"
import { MessageThreadFull } from "@components/tambo/message-thread-full";

export default function Dashboard() {
  return (
    <div>
      <h1>Dashboard</h1>
      <MessageThreadFull />
    </div>
  );
}
```

## WorkOS Enterprise Features

WorkOS provides several enterprise-grade features that work seamlessly with Tambo:

### Single Sign-On (SSO)

* **SAML 2.0 & OpenID Connect**: Support for enterprise identity providers
* **Directory Sync**: Automatic user provisioning and deprovisioning
* **Domain Verification**: Restrict access to verified domains

### User Management

* **SCIM Provisioning**: Automated user lifecycle management
* **Multi-factor Authentication**: Built-in MFA support
* **Audit Logs**: Complete authentication and authorization tracking

<Callout type="info" title="Enterprise Token Security">
  WorkOS access tokens include enterprise-specific claims and are designed for
  high-security environments. The token automatically includes the necessary
  user identification and organizational context that Tambo needs.
</Callout>
