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

# authenticate() — SocketFi Client SDK Auth Method

> Open the SocketFi hosted auth flow, register or sign in with a passkey, and receive a Session with an access token and user profile.

`authenticate()` starts the SocketFi authentication flow by opening a hosted popup where the user signs in or registers using a passkey. The method returns a `Promise<Session>` that resolves once the user has completed authentication and SocketFi has loaded or created their embedded Stellar wallet. The resolved `Session` contains the user's profile and a signed access token you can forward to your backend for server-side verification.

## Method signature

```typescript theme={null}
authenticate(): Promise<Session>
```

## Parameters

`authenticate()` takes no parameters. All configuration — including branding, network, and callbacks — is set when you construct the `SocketFi` instance.

## Return value

`authenticate()` returns `Promise<Session>`.

<ResponseField name="userProfile" type="UserProfile" required>
  The authenticated user's profile.

  <Expandable title="userProfile fields">
    <ResponseField name="userProfile.id" type="string" required>
      The user's unique SocketFi identifier (e.g. `"usr_01hx..."`). Use this as the stable key when storing user records in your database.
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="socketfiAccessToken" type="string" required>
  A signed JWT issued by SocketFi for this session. Forward this token to your backend in the `Authorization: Bearer` header. Your server verifies it with `verifyAuth()` from `@socketfi/server`. The token encodes the user ID and wallet address and is cryptographically signed — never decode it client-side and trust the contents without server verification.
</ResponseField>

## What happens during authentication

When you call `authenticate()`, the SDK opens a SocketFi-hosted popup window that guides the user through the following steps:

```
authenticate() called
       ↓
  Hosted popup opens
       ↓
  User signs in or registers with a passkey
       ↓
  Passkey verified by SocketFi
       ↓
  Embedded Stellar wallet loaded or created
       ↓
  Session returned to your application
```

If the user already has a SocketFi account, their existing wallet is loaded. If this is their first time, a new Stellar smart wallet is created automatically and secured by their passkey.

## Usage example

```typescript theme={null}
import { socketfi } from '@/lib/socketfi';

async function handleSignIn() {
  try {
    const session = await socketfi.authenticate();

    console.log('User ID:', session.userProfile.id);
    console.log('Access token:', session.socketfiAccessToken);

    // Forward the token to your backend
    await fetch('/api/session', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${session.socketfiAccessToken}`,
        'Content-Type': 'application/json',
      },
    });
  } catch (error) {
    if (error.code === 'USER_CANCELLED') {
      // User closed the popup — not an error, just reset the UI
      console.log('User cancelled sign-in');
    } else {
      console.error('Authentication failed:', error.code, error.message);
    }
  }
}
```

## React button integration

```typescript theme={null}
import { useState } from 'react';
import { socketfi } from '@/lib/socketfi';
import type { Session } from '@socketfi/react';

export function SignInButton() {
  const [session, setSession] = useState<Session | null>(null);
  const [loading, setLoading] = useState(false);

  async function handleClick() {
    setLoading(true);
    try {
      const result = await socketfi.authenticate();
      setSession(result);
    } catch (error) {
      if (error.code !== 'USER_CANCELLED') {
        console.error(error.message);
      }
    } finally {
      setLoading(false);
    }
  }

  if (session) {
    return <p>Signed in as {session.userProfile.id}</p>;
  }

  return (
    <button onClick={handleClick} disabled={loading}>
      {loading ? 'Signing in…' : 'Sign in with passkey'}
    </button>
  );
}
```

## Storing the access token

After authentication, store the `socketfiAccessToken` somewhere your application can access it for subsequent API calls. Common patterns include React state, a context provider, or a lightweight store like Zustand:

```typescript theme={null}
// Example: storing the token in React context
const { setToken } = useAuthContext();
const session = await socketfi.authenticate();
setToken(session.socketfiAccessToken);
```

<Tip>
  Always call `authenticate()` from a direct user gesture — such as a button's `onClick` handler. Browsers block popups that are opened programmatically without a user interaction. If the popup is blocked, the SDK surfaces a `POPUP_BLOCKED` error. See the [Errors reference](/api-reference/errors) for handling details.
</Tip>

## Error handling

| Error code              | When it occurs                                             | How to handle                                                 |
| ----------------------- | ---------------------------------------------------------- | ------------------------------------------------------------- |
| `USER_CANCELLED`        | User closed the popup without completing sign-in.          | Not an error — reset the UI to a signed-out state.            |
| `POPUP_BLOCKED`         | The browser blocked the authentication popup.              | Inform the user and ask them to allow popups for your domain. |
| `AUTHENTICATION_FAILED` | Passkey verification failed on SocketFi's servers.         | Display an error message and offer a retry.                   |
| `INVALID_CLIENT_ID`     | The `clientId` in your `SocketFiConfig` is not recognized. | Check your configuration and the Developer Portal.            |
