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

# React Hooks Reference

> API reference for the @hyperauth/react package — HyperAuthProvider, useHyperAuth, useRegistration hooks, and the CSP manifest helpers for Next.js and Vite.

Package: `@hyperauth/react`

***

## `HyperAuthProvider`

```ts theme={null}
import { HyperAuthProvider } from '@hyperauth/react'
```

Context provider that initializes `HyperAuthClient` and makes it available to the component tree via `useHyperAuth`.

### Props

```ts theme={null}
interface HyperAuthProviderProps {
  projectId?: string;
  chain?: SupportedChain;
  config?: ClientConfig;
  enclaveOrigin?: string;
  maxRestartAttempts?: number;
  autoRestart?: boolean;
  children: React.ReactNode;
}

type SupportedChain = 'base' | 'base-sepolia' | 'monad' | 'ethereum';
```

| Prop                 | Type              | Default  | Description                                                                                                                                                         |
| -------------------- | ----------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `projectId`          | `string`          | —        | UCAN policy token issued by HyperAuth for your app. Required in production; the provider boots without it but RPC calls will return `401`.                          |
| `chain`              | `SupportedChain`  | `'base'` | Default chain for embedded wallets. The provider forwards the matching contract addresses to the signer worker and re-syncs the store when the prop changes.        |
| `config`             | `ClientConfig`    | —        | Override the underlying SDK client config. `projectId` and `chain` still take precedence. See [Configuration Reference](/sdk-reference/configuration#clientconfig). |
| `enclaveOrigin`      | `string`          | —        | If set and not equal to `window.location.origin`, the enclave is hosted inside a hidden iframe at this origin. This is the COOP/COEP-free deployment path.          |
| `maxRestartAttempts` | `number`          | `3`      | Maximum silent restart attempts after a worker crash.                                                                                                               |
| `autoRestart`        | `boolean`         | `true`   | Disable auto-restart entirely. Useful in tests.                                                                                                                     |
| `children`           | `React.ReactNode` | —        | Component subtree.                                                                                                                                                  |

### Behavior

* Calls `createClient(config)` once on mount inside a `useEffect`.
* Sets `status` to `'initializing'` during setup, `'ready'` on success, `'error'` on failure.
* Parses `projectId` as a UCAN policy and exposes it as `policy` on the context.
* Reacts to `chain` prop changes without restarting the worker.
* Calls `client.close()` on unmount.
* Uses a `useRef` guard to prevent double-initialization in React Strict Mode.

<Note>
  The provider spawns browser workers at mount, so it must render on the client. In server-rendered frameworks such as Next.js App Router, import it through `next/dynamic` with `ssr: false`. See [Next.js App Router](/guides/nextjs-app-router) for a full example.
</Note>

***

## `useHyperAuth`

```ts theme={null}
import { useHyperAuth } from '@hyperauth/react'
```

Returns the current `HyperAuthContext` value. Throws `ClientStateError` if called outside `HyperAuthProvider`.

### Signature

```ts theme={null}
function useHyperAuth(): HyperAuthContextValue
```

### Return type

```ts theme={null}
interface HyperAuthContextValue {
  client: HyperAuthClient | null;
  status: HyperAuthStatus;
  error: Error | null;
  isReady: boolean;
  user: User | null;
  address: `0x${string}` | null;
  authStatus: AuthStatus;
  session: SessionKey | null;
  provider: ProviderKind;
  policy: UcanPolicy | null;
  chain: SupportedChain;
}
```

| Field        | Type                        | Description                                                                |
| ------------ | --------------------------- | -------------------------------------------------------------------------- |
| `client`     | `HyperAuthClient \| null`   | Initialized client instance. `null` while initializing or on error.        |
| `status`     | `HyperAuthStatus`           | Current initialization state                                               |
| `error`      | `Error \| null`             | Error object if `status === 'error'`, otherwise `null`                     |
| `isReady`    | `boolean`                   | `true` when `status === 'ready'` and `client !== null`                     |
| `user`       | `User \| null`              | Authenticated user, if any.                                                |
| `address`    | `` `0x${string}` \| null `` | Smart account address (counterfactual; available before deployment).       |
| `authStatus` | `AuthStatus`                | Auth status independent of the worker lifecycle.                           |
| `session`    | `SessionKey \| null`        | Active session key, if one has been delegated.                             |
| `provider`   | `ProviderKind`              | Provider that produced the current authenticated state (e.g. `'passkey'`). |
| `policy`     | `UcanPolicy \| null`        | Project policy parsed from the `projectId` prop.                           |
| `chain`      | `SupportedChain`            | Currently configured chain.                                                |

### `HyperAuthStatus`

```ts theme={null}
type HyperAuthStatus = 'initializing' | 'ready' | 'error'
```

| Value            | Description                     |
| ---------------- | ------------------------------- |
| `'initializing'` | `createClient` is running       |
| `'ready'`        | Client initialized successfully |
| `'error'`        | Client initialization failed    |

***

## `useRegistration`

```ts theme={null}
import { useRegistration } from '@hyperauth/react'
```

Manages the full 12-step registration pipeline: alias availability check, passkey creation, identity generation, account prediction, fee sponsorship, UserOp signing, submission, and session persistence.

### Signature

```ts theme={null}
function useRegistration(): UseRegistrationReturn
```

### Return type

```ts theme={null}
interface UseRegistrationReturn {
  phase: RegistrationPhase;
  steps: RegistrationStep[];
  identity: IdentityState | null;
  result: RegistrationOutcome | null;
  error: string | null;
  isRegistering: boolean;
  register: (alias: string) => Promise<void>;
  reset: () => void;
}
```

| Field           | Type                               | Description                                                                            |
| --------------- | ---------------------------------- | -------------------------------------------------------------------------------------- |
| `phase`         | `RegistrationPhase`                | Current phase of the registration pipeline                                             |
| `steps`         | `RegistrationStep[]`               | Array of 12 step objects with status                                                   |
| `identity`      | `IdentityState \| null`            | Populated after identity generation (step 2). Available before registration completes. |
| `result`        | `RegistrationOutcome \| null`      | Populated on successful completion                                                     |
| `error`         | `string \| null`                   | Error message if `phase === 'error'`, otherwise `null`                                 |
| `isRegistering` | `boolean`                          | `true` while `register` is running                                                     |
| `register`      | `(alias: string) => Promise<void>` | Starts the registration pipeline. No-ops if already registering.                       |
| `reset`         | `() => void`                       | Resets all state to initial values                                                     |

***

### `RegistrationPhase`

```ts theme={null}
type RegistrationPhase =
  | 'idle'
  | 'checking-alias'
  | 'creating-passkey'
  | 'generating-identity'
  | 'predicting-account'
  | 'fetching-account-state'
  | 'creating-registration'
  | 'sponsoring'
  | 'authorizing'
  | 'signing'
  | 'submitting'
  | 'confirming'
  | 'storing-session'
  | 'complete'
  | 'error'
```

| Value                      | Corresponding step                       |
| -------------------------- | ---------------------------------------- |
| `'idle'`                   | No registration in progress              |
| `'checking-alias'`         | Step 0: alias availability               |
| `'creating-passkey'`       | Step 1: WebAuthn ceremony                |
| `'generating-identity'`    | Step 2: MPC key generation               |
| `'predicting-account'`     | Step 3: smart account address derivation |
| `'fetching-account-state'` | Step 4: on-chain nonce and active status |
| `'creating-registration'`  | Step 5: UserOp construction              |
| `'sponsoring'`             | Step 6: paymaster sponsorship            |
| `'authorizing'`            | Step 7: authorization gate               |
| `'signing'`                | Step 8: UserOp signature                 |
| `'submitting'`             | Step 9: bundler submission               |
| `'confirming'`             | Step 10: receipt polling                 |
| `'storing-session'`        | Step 11: session persistence             |
| `'complete'`               | Pipeline finished successfully           |
| `'error'`                  | Pipeline failed                          |

***

### `RegistrationStep`

```ts theme={null}
interface RegistrationStep {
  label: string;
  status: 'pending' | 'active' | 'done' | 'error';
  detail?: string;
}
```

| Field    | Type                                         | Description                                                |
| -------- | -------------------------------------------- | ---------------------------------------------------------- |
| `label`  | `string`                                     | Human-readable step description                            |
| `status` | `'pending' \| 'active' \| 'done' \| 'error'` | Current step state                                         |
| `detail` | `string`                                     | Optional status detail (e.g. `'Available'`, `'Confirmed'`) |

The 12 step labels, in order:

| Index | Label                        |
| ----- | ---------------------------- |
| 0     | `'Checking availability'`    |
| 1     | `'Creating passkey'`         |
| 2     | `'Generating identity'`      |
| 3     | `'Predicting account'`       |
| 4     | `'Checking account state'`   |
| 5     | `'Preparing registration'`   |
| 6     | `'Covering fees'`            |
| 7     | `'Granting permissions'`     |
| 8     | `'Signing securely'`         |
| 9     | `'Submitting registration'`  |
| 10    | `'Waiting for confirmation'` |
| 11    | `'Saving session'`           |

***

### `IdentityState`

Populated after step 2 (`'generating-identity'`). Available via `identity` before `result` is set.

```ts theme={null}
interface IdentityState {
  did: string;
  enclaveId: string;
  publicKey: string;
  publicKeyHex?: string;
  pubkeyX: string;
  pubkeyY: string;
  ethAddress: string;
  smartAccountAddress: string;
  credentialId: string;
  encryptedShares?: EncryptedShares;
}
```

| Field                 | Type              | Description                              |
| --------------------- | ----------------- | ---------------------------------------- |
| `did`                 | `string`          | Decentralized identifier string          |
| `enclaveId`           | `string`          | MPC enclave instance ID                  |
| `publicKey`           | `string`          | Base64 public key                        |
| `publicKeyHex`        | `string`          | Hex-encoded public key                   |
| `pubkeyX`             | `string`          | P-256 public key X coordinate (hex)      |
| `pubkeyY`             | `string`          | P-256 public key Y coordinate (hex)      |
| `ethAddress`          | `string`          | Derived Ethereum address                 |
| `smartAccountAddress` | `string`          | Predicted ERC-4337 smart account address |
| `credentialId`        | `string`          | WebAuthn credential ID                   |
| `encryptedShares`     | `EncryptedShares` | MPC encrypted key shares from `generate` |

***

### `RegistrationOutcome`

Populated on successful completion (`phase === 'complete'`).

```ts theme={null}
interface RegistrationOutcome {
  did: string;
  txHash: string;
  blockNumber: number | null;
  smartAccount: string;
}
```

| Field          | Type             | Description                                           |
| -------------- | ---------------- | ----------------------------------------------------- |
| `did`          | `string`         | Registered DID string                                 |
| `txHash`       | `string`         | Transaction hash of the confirmed UserOperation       |
| `blockNumber`  | `number \| null` | Block number of confirmation; `null` if not parseable |
| `smartAccount` | `string`         | Deployed smart account address                        |

***

## `cspManifest`

```ts theme={null}
import { cspManifest } from '@hyperauth/react'
```

Object describing the Content Security Policy directives the SDK requires to boot. Merge these into your app's CSP — otherwise the workers fail to start, OPFS writes are blocked, or the bundler ALPN handshake silently drops.

### Shape

```ts theme={null}
const cspManifest = {
  'worker-src': ["'self'", 'blob:'],
  'script-src': ["'self'", "'wasm-unsafe-eval'"],
  'connect-src': [
    "'self'",
    'https://*.hyperauth.io',
    'https://*.hyperauth.dev',
    'https://*.pimlico.io',
    'wss://*.hyperauth.io',
    'https://api.transak.com',
    'https://api.sardine.ai',
  ],
  'frame-src': ["'self'", 'https://*.hyperauth.io'],
  'img-src': ["'self'", 'data:', 'blob:'],
} as const;
```

***

## `cspManifestString`

```ts theme={null}
import { cspManifestString } from '@hyperauth/react'
```

Returns `cspManifest` serialized as a single CSP header value. Use this when you compose the CSP at request time, for example from a Next.js proxy or middleware.

### Signature

```ts theme={null}
function cspManifestString(): string
```

### Example

```ts theme={null}
import { cspManifestString } from '@hyperauth/react';

const csp = `default-src 'self'; ${cspManifestString()}; style-src 'self' 'unsafe-inline'`;
response.headers.set('Content-Security-Policy', csp);
```

<Note>
  `cspManifest` does not include `style-src`. Next.js Server Components, `next-themes`, and `framer-motion` inject inline `<style>` tags; the standard workaround is to add `style-src 'self' 'unsafe-inline'` alongside the SDK directives.
</Note>
