# How Supermemory Handles User Authentication: Better-Auth Implementation Guide

> Discover how Supermemory implements robust user authentication using the Better-Auth framework. Learn about its plugin-based architecture for secure logins.

- Repository: [supermemory/supermemory](https://github.com/supermemoryai/supermemory)
- Tags: how-to-guide
- Published: 2026-03-25

---

**Supermemory builds its entire authentication layer on the Better-Auth framework, unifying username/password, magic links, email OTP, API keys, and anonymous sessions through a plugin-based client-server architecture.**

The `supermemoryai/supermemory` repository implements a comprehensive identity management system that spans browser-based UI, server-side API protection, and programmatic access. This architecture leverages Better-Auth's modular design to support seven distinct authentication methods while maintaining a consistent developer experience across the Next.js frontend and backend services.

## Authentication Architecture Overview

Supermemory's authentication stack operates through three primary layers:

- **Client SDK** ([`packages/lib/auth.ts`](https://github.com/supermemoryai/supermemory/blob/main/packages/lib/auth.ts)): Browser-side authentication with cookie-based sessions
- **Middleware Client** ([`packages/lib/auth.middleware.ts`](https://github.com/supermemoryai/supermemory/blob/main/packages/lib/auth.middleware.ts)): Server-side request validation without cookie handling
- **React Context** ([`packages/lib/auth-context.tsx`](https://github.com/supermemoryai/supermemory/blob/main/packages/lib/auth-context.tsx)): UI state management and organization scoping

The system supports **username/password** credentials, **magic links**, **email OTP**, **API keys**, **admin tokens**, **organization tokens**, and **anonymous sessions**—all configured through Better-Auth plugins in the central client configuration.

## Client-Side Authentication Configuration

### The Auth Client Setup

The primary authentication client lives in [`/packages/lib/auth.ts`](https://github.com/supermemoryai/supermemory/blob/main//packages/lib/auth.ts) and instantiates Better-Auth with multiple plugins:

```typescript
export const authClient = createAuthClient({
  baseURL: process.env.NEXT_PUBLIC_BACKEND_URL ?? "https://api.supermemory.ai",
  fetchOptions: { credentials: "include", throw: true },
  plugins: [
    usernameClient(),
    magicLinkClient(),
    emailOTPClient(),
    apiKeyClient(),
    adminClient(),
    organizationClient(),
    anonymousClient(),
  ],
});

```

**Key implementation details:**
- The `baseURL` defaults to `https://api.supermemory.ai` but can be overridden via `NEXT_PUBLIC_BACKEND_URL`
- `credentials: "include"` enables secure cookie-based session transmission for browser flows
- `throw: true` ensures authentication errors propagate immediately rather than failing silently

### Exported Helper Functions

Supermemory exports thin wrappers around the Better-Auth client for consistent import patterns:

```typescript
export const signIn = authClient.signIn;
export const signOut = authClient.signOut;
export const useSession = authClient.useSession;
export const getSession = authClient.getSession;

```

These exports allow components to import `signIn` directly from `@/packages/lib/auth` rather than referencing the full client object.

### Supported Authentication Methods

The client configuration enables seven authentication strategies:

- **Username/Password**: Traditional credential flow via `usernameClient()`
- **Magic Link**: Email-based one-time links via `magicLinkClient()`
- **Email OTP**: Time-limited codes sent to email via `emailOTPClient()`
- **API Key**: Bearer tokens for programmatic access via `apiKeyClient()`
- **Admin Token**: Privileged internal operations via `adminClient()`
- **Organization Token**: Scoped organizational access via `organizationClient()`
- **Anonymous**: Guest sessions for trial users via `anonymousClient()`

## Server-Side Authentication Middleware

For API routes and backend services like the MCP (Model Context Protocol) server, Supermemory uses a separate middleware client that validates requests without browser cookie handling:

```typescript
// packages/lib/auth.middleware.ts
export const middlewareAuthClient = createAuthClient({
  baseURL: process.env.NEXT_PUBLIC_BACKEND_URL ?? "https://api.supermemory.ai",
  fetchOptions: { throw: true },
  plugins: [ /* same plugin list as client */ ],
});

```

### Protecting Server Routes

The middleware client validates incoming requests in server environments. In [`/apps/mcp/src/auth.ts`](https://github.com/supermemoryai/supermemory/blob/main//apps/mcp/src/auth.ts), the implementation guards endpoints by extracting the session from the request object:

```typescript
import { middlewareAuthClient } from "@/packages/lib/auth.middleware";

export async function onRequest({ request }: { request: Request }) {
  const session = await middlewareAuthClient.getSession(request);
  if (!session?.user) {
    return new Response("Unauthorized", { status: 401 });
  }
  // Authorized logic continues...
}

```

Unlike the browser client, this middleware variant does not set `credentials: "include"`, as server-to-server communication relies on explicit token passing rather than cookie sharing.

## React Context and Session Management

### AuthProvider Implementation

The [`/packages/lib/auth-context.tsx`](https://github.com/supermemoryai/supermemory/blob/main//packages/lib/auth-context.tsx) file wraps the application in an `AuthProvider` component that distributes authentication state throughout the React tree. The context exposes:

- `session`: Raw Better-Auth session object (cookie-based)
- `user`: User profile data including name and email
- `org`: Currently active organization (set via `authClient.organization.setActive`)
- `organizations`: Array of organizations the user belongs to
- `isRestoring`: Boolean flag indicating hydration state during session recovery

The context uses the exported `useSession` hook to maintain synchronization with the backend authentication state.

### Organization Handling

Supermemory implements organization-scoped authentication with client-side persistence. When users switch organizations, the system stores the selection in `localStorage` under the key `supermemory-consumer-last-org-slug`, enabling persistent multi-tenant navigation across sessions.

Access the current user and organization in any component:

```tsx
import { useAuth } from "@/packages/lib/auth-context";

export function UserInfo() {
  const { user, org } = useAuth();
  return (
    <div>
      <span>Hello, {user?.name ?? "Guest"}</span>
      <span>Organization: {org?.name ?? "Personal"}</span>
    </div>
  );
}

```

## API Key and Bearer Token Authentication

### Public API Access

All public REST endpoints in Supermemory require Bearer token authentication. According to `/apps/docs/authentication.mdx`, requests must include the header:

```http
Authorization: Bearer <YOUR_API_KEY>

```

Example curl request searching the API:

```bash
curl https://api.supermemory.ai/v3/search \
  -H "Authorization: Bearer sm_org123_abcdef..." \
  -H "Content-Type: application/json" \
  -d '{"q":"machine learning"}'

```

### Scoped API Keys

Supermemory supports **scoped API keys** that restrict access to specific containers or resources. These keys follow the same Bearer format but embed additional restrictions validated at the middleware layer. The scoped key creation and revocation flows are documented in the authentication MDX file, allowing fine-grained access control for multi-tenant deployments.

## Summary

- **Better-Auth Foundation**: Supermemory uses Better-Auth's plugin architecture in [`/packages/lib/auth.ts`](https://github.com/supermemoryai/supermemory/blob/main//packages/lib/auth.ts) to unify seven authentication methods under a single client configuration.
- **Dual Client Strategy**: Separate clients handle browser sessions (with cookies) and server middleware (without cookies) to optimize for each environment's security model.
- **React Integration**: The `AuthProvider` context in [`/packages/lib/auth-context.tsx`](https://github.com/supermemoryai/supermemory/blob/main//packages/lib/auth-context.tsx) manages user state, organization scoping, and localStorage persistence for seamless UI synchronization.
- **API Security**: REST endpoints require Bearer tokens via the `Authorization` header, with support for scoped keys that restrict access to specific organizational contexts.
- **File Locations**: Core logic resides in [`packages/lib/auth.ts`](https://github.com/supermemoryai/supermemory/blob/main/packages/lib/auth.ts), [`packages/lib/auth.middleware.ts`](https://github.com/supermemoryai/supermemory/blob/main/packages/lib/auth.middleware.ts), and [`packages/lib/auth-context.tsx`](https://github.com/supermemoryai/supermemory/blob/main/packages/lib/auth-context.tsx), with implementation examples in [`apps/mcp/src/auth.ts`](https://github.com/supermemoryai/supermemory/blob/main/apps/mcp/src/auth.ts).

## Frequently Asked Questions

### How does Supermemory store session data?

Supermemory relies on Better-Auth's cookie-based session management for browser clients. The `authClient` configuration sets `credentials: "include"` in fetch options, allowing the browser to automatically transmit HTTP-only cookies with each request. Server-side middleware uses the same client library but extracts session data directly from request headers rather than cookies.

### What authentication methods does Supermemory support?

Supermemory supports seven authentication methods through Better-Auth plugins: username/password, magic links, email OTP, API keys, admin tokens, organization tokens, and anonymous sessions. These are all registered in the `authClient` configuration array in [`/packages/lib/auth.ts`](https://github.com/supermemoryai/supermemory/blob/main//packages/lib/auth.ts).

### How do I authenticate API requests to Supermemory?

All public API endpoints require a Bearer token in the `Authorization` header. Format your requests as `Authorization: Bearer <YOUR_API_KEY>`. The MCP server and other backends validate these tokens using the `middlewareAuthClient` from [`/packages/lib/auth.middleware.ts`](https://github.com/supermemoryai/supermemory/blob/main//packages/lib/auth.middleware.ts), which checks token validity without establishing cookie sessions.

### Can I use organization-specific authentication in Supermemory?

Yes. The `organizationClient()` plugin enables organization-scoped sessions, and the React context exposes an `org` property representing the active organization. Users can switch organizations via `authClient.organization.setActive()`, and the selection persists in `localStorage` under the key `supermemory-consumer-last-org-slug`.