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

# React with Better Auth

> Learn how to integrate Chipi Pay with your React application using Better Auth for authentication and secure wallet storage.

<Steps>
  <Step title="Setup Better Auth with React" titleSize="h2">
    First, follow the complete [Better Auth Installation Guide](https://www.better-auth.com/docs/installation) to set up authentication in your React app.
    Then proceed to [Better Auth Basic Usage](https://www.better-auth.com/docs/basic-usage) to create login and sign-up pages.

    This will guide you through:

    * Creating Better Auth tables and schemas
    * Setting up your React app with Better Auth
    * Configuring environment variables
    * Creating `auth.ts`, mounting the handler, and client instance

    **Come back here once you've completed the Better Auth setup!**
  </Step>

  <Step title="Setup the Better Auth JWT Plugin" titleSize="h2">
    In your `auth.ts` file, add the JWT plugin:

    ```typescript theme={null}
    import { betterAuth } from "better-auth";
    import { Pool } from "pg";
    import { jwt } from "better-auth/plugins";

    export const auth = betterAuth({
        database: new Pool({
            connectionString: process.env.DATABASE_URL
        }),
        emailAndPassword: {
            enabled: true,
        },
        plugins: [
            jwt({
                jwks: {
                    keyPairConfig: {
                        alg: "RS256",
                        modulusLength: 2048,
                    }
                },
                jwt: {
                    issuer: process.env.JWT_ISSUER,
                    audience: process.env.JWT_AUDIENCE,
                    expirationTime: "15m"
                }
            })
        ]
    });
    ```

    Then migrate or generate your database to add the JWT tables.
  </Step>

  <Step title="Install the Chipi SDK" titleSize="h2">
    Install the Chipi Pay SDK for React:

    ```bash theme={null}
    npm install @chipi-stack/chipi-react
    ```
  </Step>

  <Step title="Add Environment Variables" titleSize="h2">
    Add your API keys to your `.env` file:

    ```bash theme={null}
    # Your existing Better Auth variables
    DATABASE_URL=your_database_url
    JWT_ISSUER=your_jwt_issuer
    JWT_AUDIENCE=your_jwt_audience

    # Add the Chipi Variables
    VITE_CHIPI_API_KEY=your_chipi_api_public_key
    ```

    You can get your Chipi API keys from the [Chipi Dashboard](https://dashboard.chipipay.com/configure/api-keys).
  </Step>

  <Step title="Setup the Chipi SDK Provider" titleSize="h2">
    ```tsx theme={null}
    // App.tsx

    import { ChipiProvider } from "@chipi-stack/chipi-react";

    export default function App() {
      return (
        <ChipiProvider config={{ apiPublicKey: import.meta.env.VITE_CHIPI_API_KEY }}>
          {/* Your app components */}
        </ChipiProvider>
      );
    }
    ```
  </Step>

  <Step title="Creating a Wallet" titleSize="h2">
    Create a wallet using Better Auth's JWT token:

    ```typescript theme={null}
    // components/CreateWallet.tsx

    import { useState } from "react";
    import { useCreateWallet } from "@chipi-stack/chipi-react";
    import { authClient } from "../lib/auth-client";

    export default function CreateWallet() {
      const { createWalletAsync, isLoading } = useCreateWallet();
      const [encryptKey, setEncryptKey] = useState("");

      const handleCreateWallet = async () => {
        // Get JWT from Better Auth (returned in set-auth-jwt header)
        const { data, response: sessionResponse } = await authClient.getSession({
          fetchOptions: { onSuccess: (ctx) => ctx },
        });
        const bearerToken = sessionResponse?.headers?.get("set-auth-jwt") ?? data?.session?.token;
        const userId = data?.user?.id;

        if (!bearerToken || !userId) {
          console.error("Please sign in first");
          return;
        }

        const walletResponse = await createWalletAsync({
          params: {
            encryptKey,
            externalUserId: userId,
          },
          bearerToken,
        });

        console.log("Wallet created:", walletResponse.publicKey);
      };

      return (
        <div>
          <input
            type="password"
            placeholder="Enter encryption key"
            value={encryptKey}
            onChange={(e) => setEncryptKey(e.target.value)}
          />
          <button onClick={handleCreateWallet} disabled={isLoading}>
            {isLoading ? "Creating..." : "Create Wallet"}
          </button>
        </div>
      );
    }
    ```
  </Step>

  <Step title="Register JWKS in Chipi Dashboard" titleSize="h2">
    Register your Better Auth JWKS endpoint in the [Chipi Dashboard](https://dashboard.chipipay.com/configure/jwks-endpoint):

    1. Go to Configure > Auth Provider
    2. Select **Better Auth** as your provider
    3. Enter your application URL (the dashboard will auto-detect `/api/auth/jwks`)
    4. Click **Verify & Save**
  </Step>
</Steps>

<Tip>
  Need help? Check out our [Telegram Community](https://t.me/+e2qjHEOwImkyZDVh) for
  support and to connect with other developers.
</Tip>
