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

# Next.js application

> A complete Next.js App Router app: connect a wallet, open a private balance, shield and send

A minimal but complete Next.js (App Router) application. The user connects Phantom, Solflare,
Backpack or any Wallet Standard wallet, opens their private balance, shields USDC and sends it
privately. Every file below was built with `next build` against `@cloak.dev/sdk` 0.2.20 and loaded
in a browser without errors.

## Prerequisites

* Node 22 or later.
* A mainnet RPC URL. See [Network and RPC](https://docs.cloak.ag/resources/network-and-rpc.md).
* A wallet with a few USDC and a little SOL, to try a shield.

## 1. Create the app and install

```bash theme={null}
npx create-next-app@15 cloak-next --ts --app --no-tailwind --no-eslint --no-src-dir --import-alias "@/*"
cd cloak-next
npm install @cloak.dev/sdk@^0.2.20 @solana/kit @solana/web3.js@^1.99 \
  @solana/wallet-adapter-react @solana/wallet-adapter-react-ui @solana/wallet-adapter-base
```

> [!NOTE]
>
> Pin `@solana/web3.js@^1.99`. The wallet adapter packages require web3.js 1.x, and an unpinned install
> now resolves to a newer major that conflicts with them.

```bash .env.local theme={null}
NEXT_PUBLIC_SOLANA_RPC_URL=https://your-mainnet-rpc
```

No `next.config` changes are needed. The build prints a `Critical dependency` warning from the
prover's worker library; it is harmless.

## 2. Wallet providers

```tsx title="app/providers.tsx" theme={null}
"use client";

import { ConnectionProvider, WalletProvider } from "@solana/wallet-adapter-react";
import { WalletModalProvider } from "@solana/wallet-adapter-react-ui";
import "@solana/wallet-adapter-react-ui/styles.css";
import type { ReactNode } from "react";

const RPC_URL = process.env.NEXT_PUBLIC_SOLANA_RPC_URL ?? "https://api.mainnet-beta.solana.com";

export function Providers({ children }: { children: ReactNode }) {
  // An empty list: Phantom, Solflare, Backpack and every Wallet Standard wallet register themselves.
  return (
    <ConnectionProvider endpoint={RPC_URL}>
      <WalletProvider wallets={[]} autoConnect>
        <WalletModalProvider>{children}</WalletModalProvider>
      </WalletProvider>
    </ConnectionProvider>
  );
}
```

```tsx title="app/layout.tsx" theme={null}
import type { ReactNode } from "react";
import { Providers } from "./providers";

export const metadata = { title: "Cloak private balance" };

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}
```

## 3. The Cloak hook

Opens the account on an explicit click, because it asks the wallet to sign. It also starts the
circuit download when the page mounts, so the first shield does not wait for it.

```ts title="hooks/use-cloak.ts" theme={null}
"use client";

import { useWallet } from "@solana/wallet-adapter-react";
import { createCloak, getCircuitsPath, isCloakCallError, verifyAllCircuits, type Cloak } from "@cloak.dev/sdk";
import { useCallback, useEffect, useState } from "react";

export function useCloak() {
  const wallet = useWallet();
  const [cloak, setCloak] = useState<Cloak | null>(null);
  const [opening, setOpening] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Start the ~23 MB circuit download now, not on the first click.
  useEffect(() => {
    void verifyAllCircuits(getCircuitsPath()).catch(() => undefined);
  }, []);

  // A different wallet is a different account.
  useEffect(() => {
    setCloak(null);
  }, [wallet.publicKey]);

  const open = useCallback(async () => {
    if (!wallet.connected) return;
    setOpening(true);
    setError(null);
    try {
      setCloak(await createCloak({ wallet, rpc: process.env.NEXT_PUBLIC_SOLANA_RPC_URL }));
    } catch (e) {
      setError(isCloakCallError(e) ? `${e.code}: ${e.message}` : String(e));
    } finally {
      setOpening(false);
    }
  }, [wallet]);

  return { cloak, open, opening, error, connected: wallet.connected };
}
```

## 4. The UI

```tsx title="components/private-balance.tsx" theme={null}
"use client";

import { isCloakCallError, type CloakReceipt } from "@cloak.dev/sdk";
import { WalletMultiButton } from "@solana/wallet-adapter-react-ui";
import { useEffect, useState } from "react";
import { useCloak } from "../hooks/use-cloak";

export function PrivateBalance() {
  const { cloak, open, opening, error, connected } = useCloak();
  const [balance, setBalance] = useState<Record<string, string> | null>(null);
  const [status, setStatus] = useState("");
  const [busy, setBusy] = useState(false);
  const [to, setTo] = useState("");
  const [amount, setAmount] = useState("1");

  useEffect(() => {
    if (cloak) void cloak.balance().then(setBalance);
  }, [cloak]);

  async function run(action: () => Promise<CloakReceipt>) {
    if (!cloak) return;
    setBusy(true);
    try {
      const receipt = await action();
      setStatus(`${receipt.status}: ${receipt.amount} ${receipt.token} (fee ${receipt.fee})`);
      setBalance(await cloak.balance());
    } catch (e) {
      setStatus(isCloakCallError(e) ? `${e.code}: ${e.message}` : String(e));
    } finally {
      setBusy(false);
    }
  }

  return (
    <section style={{ display: "grid", gap: 12, maxWidth: 480 }}>
      <WalletMultiButton />
      {connected && !cloak && (
        <button onClick={open} disabled={opening}>
          {opening ? "Check your wallet…" : "Open private balance"}
        </button>
      )}
      {error && <p role="alert">{error}</p>}
      {cloak && (
        <>
          <p>
            Your Cloak address: <code>{cloak.address}</code>
          </p>
          <p>Private USDC: {balance?.USDC ?? "…"}</p>
          <input value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="Amount (USDC)" />
          <button disabled={busy} onClick={() => run(() => cloak.shield({ from: "solana", token: "USDC", amount, onProgress: setStatus }))}>
            Shield {amount} USDC
          </button>
          <input value={to} onChange={(e) => setTo(e.target.value)} placeholder="cloak_… or a Solana address" />
          <button disabled={busy || !to} onClick={() => run(() => cloak.send({ to, token: "USDC", amount, onProgress: setStatus }))}>
            Send {amount} USDC
          </button>
          <p aria-live="polite">{status}</p>
        </>
      )}
    </section>
  );
}
```

```tsx title="app/page.tsx" theme={null}
import { PrivateBalance } from "../components/private-balance";

export default function Home() {
  return (
    <main style={{ padding: 32 }}>
      <h1>Private balance</h1>
      <PrivateBalance />
    </main>
  );
}
```

## 5. Run it

```bash theme={null}
npm run dev
```

Open `http://localhost:3000`, connect a wallet, and click **Open private balance**.

| Step | What you see |
| - | - |
| Open private balance | The wallet asks to sign the Cloak account message: twice the first time on this device. Then your `cloak_…` address and `Private USDC: 0` |
| Shield 1 USDC | Status text while the proof runs, one wallet approval for the transaction, then `shielded: 1 USDC (fee 0)` |
| Send to a `cloak_` address | No wallet prompt. `sent: 1 USDC (fee 0)` |
| Send to a Solana address | No wallet prompt. `withdrawn: 1 USDC (fee 0.45…)`: the fee is added on top |

## Notes for production

* **Bundle size.** The SDK and the prover add about 1.6 MB to the page that imports them. Load the
  private balance UI with `next/dynamic` on the routes that need it.
* **RPC key.** `NEXT_PUBLIC_` values ship to the browser. Use a domain-restricted RPC key, or proxy RPC
  through a route of your own.
* **Content-Security-Policy.** Allow your RPC, `https://api.cloak.ag` and
  `https://storage.googleapis.com` in `connect-src`, and `'wasm-unsafe-eval'` in `script-src`.
* **Storage.** In the browser, `createCloak` keeps its records in `localStorage`. Offer users an
  encrypted notes backup. See [Balances](https://docs.cloak.ag/guides/balances.md#back-up-the-notes).

## Related

* [React (Vite)](https://docs.cloak.ag/examples/react.md): the same components without Next.js.
* [Privy](https://docs.cloak.ag/examples/privy.md): the same app with email and social login.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.