> ## 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.

# SocketFi Error Reference — Client and Server Codes

> Complete reference for all SocketFi client and server error codes, their meanings, and recommended handling patterns for production applications.

SocketFi surfaces errors through a consistent `SocketFiError` interface on the client side and through the `error.code` field of a failed `VerifyAuthResult` on the server side. Understanding each error code lets you write precise error-handling logic — distinguishing between user-initiated cancellations, expired sessions, configuration mistakes, and genuine failures — rather than treating all errors the same way.

## SocketFiError interface

All client-side errors conform to the following interface:

```typescript theme={null}
interface SocketFiError {
  code: string;    // Machine-readable error identifier
  message: string; // Human-readable description
}
```

When a client SDK method throws, catch it and inspect `error.code` to determine the appropriate response:

```typescript theme={null}
try {
  const session = await socketfi.authenticate();
} catch (err) {
  const error = err as SocketFiError;
  console.error(`[${error.code}] ${error.message}`);
}
```

## Comprehensive error handling pattern

The following example shows how to handle every possible error code from both `authenticate()` and `requestTransaction()` in a production TypeScript application:

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

async function signInAndTransfer(recipient: string, amount: string) {
  // --- Authentication ---
  let session;
  try {
    session = await socketfi.authenticate();
  } catch (err) {
    const error = err as SocketFiError;

    switch (error.code) {
      case 'USER_CANCELLED':
        // User closed the popup intentionally — not an error
        showToast('Sign-in cancelled.');
        return;

      case 'POPUP_BLOCKED':
        showToast('Please allow popups for this site and try again.');
        return;

      case 'AUTHENTICATION_FAILED':
        showToast('Passkey verification failed. Please try again.');
        return;

      case 'INVALID_CLIENT_ID':
        // Configuration error — surface to developers, not end users
        console.error('SocketFi client ID is invalid. Check your config.');
        return;

      default:
        console.error(`Unexpected auth error: [${error.code}] ${error.message}`);
        showToast('Something went wrong. Please try again.');
        return;
    }
  }

  // --- Transaction ---
  try {
    const result = await socketfi.requestTransaction({
      contractId: process.env.NEXT_PUBLIC_TOKEN_CONTRACT!,
      method: 'transfer',
      args: [recipient, amount],
    });

    if (result.success) {
      showToast(`Transfer confirmed! Tx: ${result.transactionHash}`);
    }
  } catch (err) {
    const error = err as SocketFiError;

    switch (error.code) {
      case 'USER_CANCELLED':
      case 'TRANSACTION_REJECTED':
        // User chose not to proceed — update the UI, don't show an error
        showToast('Transaction cancelled.');
        break;

      case 'TOKEN_EXPIRED':
        // Session expired mid-flow — re-authenticate transparently
        showToast('Your session expired. Please sign in again.');
        await socketfi.authenticate();
        break;

      case 'INVALID_TOKEN':
      case 'INVALID_SIGNATURE':
        // Token is corrupt or forged — force a fresh sign-in
        showToast('Session invalid. Please sign in again.');
        await socketfi.authenticate();
        break;

      default:
        console.error(`Transaction error: [${error.code}] ${error.message}`);
        showToast('Transaction failed. Please try again.');
    }
  }
}
```

## Client SDK error codes

These errors are thrown by `authenticate()`, `requestTransaction()`, and other client SDK methods.

| Code                    | Trigger                                                                                                                            | Recommended handling                                                                                                         |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `INVALID_CLIENT_ID`     | The `clientId` in your `SocketFiConfig` is not recognized by SocketFi.                                                             | Verify your `clientId` in the Developer Portal. This is a configuration error — fix it at development time, not at runtime.  |
| `AUTHENTICATION_FAILED` | Passkey verification failed on SocketFi's servers during `authenticate()`.                                                         | Display an error message and offer the user a retry.                                                                         |
| `USER_CANCELLED`        | The user closed the authentication or transaction popup without completing the flow.                                               | **Not a failure** — handle gracefully. Reset the UI to a neutral state without showing an error message.                     |
| `TRANSACTION_REJECTED`  | The user reviewed the transaction details in the approval popup and chose to reject it.                                            | **Not a failure** — the user made an intentional choice. Update the UI without showing an error.                             |
| `POPUP_BLOCKED`         | The browser blocked the popup opened by `authenticate()` or `requestTransaction()`.                                                | Ask the user to allow popups for your domain and retry. Always call these methods from a direct user gesture (button click). |
| `TOKEN_EXPIRED`         | The user's access token has expired. This can be thrown by transaction methods when a session obtained earlier is no longer valid. | Prompt the user to re-authenticate by calling `authenticate()` again.                                                        |
| `INVALID_TOKEN`         | The access token failed validation — it may be malformed or from a different environment.                                          | Force a fresh sign-in by calling `authenticate()`.                                                                           |
| `INVALID_SIGNATURE`     | The token's cryptographic signature could not be verified by the client.                                                           | Force a fresh sign-in. This may indicate a tampered or forged token.                                                         |

## Server SDK error codes

These codes appear in the `error.code` field of a `VerifyAuthResult` when `verifyAuth()` returns `{ valid: false }`. Respond to all of them with an HTTP `401 Unauthorized`.

| Code                | Meaning                                                                                                                             | Recommended handling                                                                                                                                              |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `TOKEN_REQUIRED`    | `verifyAuth()` was called with an empty, `null`, or `undefined` token value.                                                        | Check that your client is sending the `Authorization: Bearer <token>` header and that your middleware correctly extracts the token before calling `verifyAuth()`. |
| `INVALID_SIGNATURE` | The token's cryptographic signature did not pass verification. The token may have been tampered with or was not issued by SocketFi. | Reject the request immediately. Log the failure for security monitoring.                                                                                          |
| `TOKEN_EXPIRED`     | The token's expiry claim (`exp`) is in the past.                                                                                    | Return a `401` and instruct the client to re-authenticate by calling `authenticate()`.                                                                            |
| `INVALID_ISSUER`    | The token's issuer claim (`iss`) does not match SocketFi's expected value. The token was not issued by SocketFi.                    | Reject the request. This may indicate a token from a different service being used against your API.                                                               |

### Server-side error handling example

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

app.use(async (req, res, next) => {
  const token = req.headers.authorization?.replace('Bearer ', '');

  if (!token) {
    // TOKEN_REQUIRED would be returned by verifyAuth(), but we short-circuit here
    return res.status(401).json({ error: 'TOKEN_REQUIRED' });
  }

  const auth = await verifyAuth(token);

  if (!auth.valid) {
    // Log expiry and signature failures for monitoring
    if (auth.error.code === 'INVALID_SIGNATURE') {
      console.warn('Signature verification failed — possible token forgery');
    }

    return res.status(401).json({ error: auth.error.code });
  }

  req.auth = auth;
  next();
});
```

<Tip>
  `USER_CANCELLED` and `TRANSACTION_REJECTED` are **intentional user actions**, not application errors. Do not log them as errors, do not display error modals, and do not retry automatically. Simply return your UI to a neutral state and let the user decide what to do next.
</Tip>
