> ## 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 Server SDK — Backend Token Verification

> Verify SocketFi access tokens on your backend with @socketfi/server. Protect authenticated routes in Express, Fastify, NestJS, or serverless functions.

The `@socketfi/server` SDK gives your backend a single, reliable way to confirm that a request comes from a user who has already authenticated through SocketFi. It never performs authentication itself — that responsibility belongs to the client SDK. Your server's only job is to verify the signed token that the client forwards, extract the user and wallet information embedded in it, and decide whether to fulfil the request.

## Installation

Install the package with your preferred package manager:

<CodeGroup>
  ```bash npm theme={null}
  npm install @socketfi/server
  ```

  ```bash yarn theme={null}
  yarn add @socketfi/server
  ```

  ```bash pnpm theme={null}
  pnpm add @socketfi/server
  ```
</CodeGroup>

## Requirements

| Requirement   | Minimum           |
| ------------- | ----------------- |
| Node.js       | 20+               |
| Module system | ESM or TypeScript |

Supported frameworks and runtimes include **Express**, **Fastify**, **NestJS**, and **Serverless Functions** (AWS Lambda, Vercel, Cloudflare Workers, etc.).

## Key principle: verify, don't authenticate

SocketFi follows a clean separation of concerns. The client SDK handles the full passkey authentication flow and receives a signed access token from SocketFi's servers. Your backend then calls `verifyAuth()` to cryptographically confirm that token is genuine before granting access to any protected resource.

Never trust authentication state that originates on the client. Always verify the token on every protected request.

## Quick start

Import `verifyAuth` and call it with the token extracted from the `Authorization` header:

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

const app = express();

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

  if (!token) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  const auth = await verifyAuth(token);

  if (!auth.valid) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  return res.json({
    user: auth.user,
    wallet: auth.wallet,
  });
});

app.listen(3000);
```

A successful call to `verifyAuth()` returns the verified user ID and the user's Stellar wallet address — everything you need to authorize the request and associate it with the right account.

## How token verification works

The SDK handles all cryptographic complexity automatically:

1. **Downloads signing keys** — fetches SocketFi's public JWKS endpoint on first use.
2. **Verifies the signature** — confirms the token was signed by SocketFi and has not been tampered with.
3. **Validates claims** — checks expiry, issuer, and audience fields.
4. **Returns a trusted result** — your code receives a plain, typed object with no raw JWT handling required.

Signing keys are cached in memory after the first download to reduce latency and eliminate redundant network requests. You can clear the cache at any time by calling `clearKeyCache()` — useful during development or key-rotation testing.

## When to use the Server SDK

Use `verifyAuth()` on **every route or handler that requires a logged-in user**. Typical use cases include:

* Reading or writing user-specific data
* Initiating blockchain transactions on behalf of a user
* Associating a wallet address with a database record
* Enforcing per-user authorization rules after confirming identity

<Note>
  Authentication confirms *who* the user is. Authorization — deciding *what* they are allowed to do — is your application's responsibility. After `verifyAuth()` succeeds, apply any additional permission checks your business logic requires.
</Note>

## Available exports

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

| Export          | Type                                           | Description                                                                     |
| --------------- | ---------------------------------------------- | ------------------------------------------------------------------------------- |
| `verifyAuth`    | `(token: string) => Promise<VerifyAuthResult>` | Verifies a SocketFi access token and returns user and wallet info.              |
| `clearKeyCache` | `() => void`                                   | Clears the in-memory JWKS key cache. Intended for development and testing only. |

## Clearing the key cache

`clearKeyCache()` wipes the in-memory JWKS signing-key cache so that the next `verifyAuth()` call re-fetches fresh keys from SocketFi. Most production applications never need this — the SDK manages key caching automatically. Call it only in specific scenarios:

* **Local development** — force a key refresh without restarting the server.
* **Integration tests** — reset key state between test runs to ensure isolation.
* **Key-rotation drills** — validate that your server picks up rotated keys correctly.

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

// Force a fresh key download before the next verification —
// useful in test setup or after a manual key rotation.
clearKeyCache();

const auth = await verifyAuth(token);
```

<Warning>
  Do not call `clearKeyCache()` on every request. Clearing the cache triggers a network round-trip to re-fetch the JWKS on the next `verifyAuth()` call, which adds latency. Reserve it for development, testing, and key-rotation workflows only.
</Warning>

## Authentication flow

```
React / Mobile App
       ↓
  SocketFi Client SDK  →  Passkey authentication
       ↓
  Access Token Issued
       ↓
  API Request  (Authorization: Bearer <token>)
       ↓
  verifyAuth()  ←  @socketfi/server
       ↓
  Protected Resource
```
