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

# Next.js with Better Auth

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

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

    This will guide you through:

    * Creating Better Auth Tables and Schemas
    * Setting up your Next.js app with Better Auth
    * Configuring environment variables
    * Creating `auth.ts`, mounting the handler and client instance
    * Creating login and sign up pages ready to receive new users 🎉

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

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

    ```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"
                   
                }
            })
        ]
    });
    ```

    2. Migrate or generate your database:

    <Tabs>
      <Tab title="Migrate">
        <pre>
          <code className="bash">npx @better-auth/cli migrate</code>
        </pre>
      </Tab>

      <Tab title="Generate">
        <pre>
          <code className="bash">npx @better-auth/cli generate</code>
        </pre>
      </Tab>
    </Tabs>

    > **Note:** Before proceeding, check the [Better Auth CLI Docs](https://www.better-auth.com/docs/concepts/cli) to determine which CLI commands and setup fit your specific use case best.
  </Step>

  <Step title="Create an auth-client.ts" titleSize="h2">
    You need to create an `auth-client.ts` - required for client side JWT functionality

    ```typescript theme={null}
    "use client";

    import { createAuthClient } from "better-auth/react";
    import { jwtClient } from "better-auth/client/plugins";


    export const authClient = createAuthClient({
        basePath: "/api/auth",
      
        plugins: [jwtClient()],
    });
    ```
  </Step>

  <Step title="Create API route handler " titleSize="h2">
    > Create a new `route.ts` file under `/api/[...all]/route.ts` with the following content.

    ```typescript theme={null}
    // Update the path to your auth file as needed
    import { toNextJsHandler } from "better-auth/next-js";
    import { auth } from "../../../../auth";

    export const { POST, GET } = toNextJsHandler(auth);
    ```
  </Step>

  <Step title="Create a use-better-auth.ts for getting JWTs and Deploy your app" titleSize="h2">
    ```typescript theme={null}
    "use client";

    import { authClient } from "./auth-client";


    export function useBetterAuth() {
      const { data: session, isPending } = authClient.useSession();

      const getToken = async () => {
        try {
          const { data, error } = await authClient.token();
          
          if (error) {
            console.error("Failed to get JWT token:", error);
            return null;
          }

          return data?.token || null;
        } catch (error) {
          console.error("Error fetching JWT token:", error);
          return null;
        }
      };

      const userId = session?.user?.id || null;

      return {
        getToken,
        userId,
        session,
        isPending,
        isSignedIn: !!session,
      };
    }
    ```

    2. Deploy your app, then add your deployed application URL to your environment variables:

    ```bash theme={null}
    JWT_ISSUER=https://my-deployed-app-domain.com
    JWT_AUDIENCE=https://my-deployed-app-domain.com
    ```
  </Step>

  <Step title="Install the Chipi SDK" titleSize="h2">
    First, install the required packages:

    ```bash theme={null}
    # Install Chipi Pay SDK
    npm install @chipi-stack/nextjs
    ```
  </Step>

  <Step title="Setup the Chipi SDK Provider" titleSize="h2">
    1. In your [`.env`](https://dashboard.chipipay.com/configure/jwks-endpoint)  file, add your Chipi API keys:

    ```bash theme={null}
    NEXT_PUBLIC_CHIPI_API_KEY=your_chipi_api_public_key
    CHIPI_SECRET_KEY=your_chipi_api_secret_key
    ```

    2. Set up the Chipi Pay provider in your application:

    ```tsx theme={null}
    // app/layout.tsx

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

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

    ```
  </Step>

  <Step title="Add your JWKs Endpoint Url to Chipi 🕺 !" titleSize="h2">
    Visit the [dashboard JWKS and JWT configuration](https://dashboard.chipipay.com/configure/jwks-endpoint), select `Better Auth` as your auth provider and paste your JWKS Endpoint URL.

    ```bash theme={null}
    https://my-deployed-app-domain.com/api/auth/jwks 
    ```

    <Warning>
      <strong>Note:</strong> You do <strong>not</strong> need to manually create this <code>/api/auth/jwks</code> endpoint!\
      It is automatically provided by the Better Auth JWT plugin and handled internally by the catch-all route handler. Remember to
      <strong>replace `https://my-deployed-app-domain.com` </strong> with the actual URL of where your app is deployed.
    </Warning>
  </Step>

  <Step title="Using Better Auth with Chipi hooks 🕺 !" titleSize="h2">
    Below you will see a simple example of how you can get and pass your tokens to the different Chipi hooks:

    ```typescript theme={null}
    "use client";

    import { useGetWallet } from "@chipi-stack/nextjs";
    import { useBetterAuth } from "@/hooks/use-better-auth";

    export default function Home() {
      const { getToken, userId, isPending: authPending } = useBetterAuth();

      const { data: wallet, isLoading } = useGetWallet({
        getBearerToken: async () => {
          const token = await getToken();
          if (!token) {
            throw new Error("User not authenticated");
          }
          return token;
        },
        params: {
          externalUserId: userId || "",
        },
      });

      if (authPending) {
        return <div>Loading authentication...</div>;
      }

      return (
        <div className="flex min-h-screen items-center justify-center bg-zinc-50 font-sans dark:bg-black">
          <h1>Home page</h1>
          {isLoading && <p>Loading wallet...</p>}
          {wallet && <pre>{JSON.stringify(wallet, null, 2)}</pre>}
        </div>
      );
    }
    ```

    <Warning>
      <strong>Note:</strong> If you have not yet created a wallet, you may see an error with a message like:

      message:"Wallet not found for externalUserId: user\_id, apiPublicKey: pk\_prod\_something"

      This error is expected and shows that your app is correctly contacting Chipi, but there is not yet a wallet for this user. Once you create a wallet, this error will disappear.
    </Warning>
  </Step>

  <Step title="Celebrate & Learn More!" titleSize="h2">
    That's it! You should now have an initial working version of Chipi Pay integrated into your application. You can now start implementing various features like:

    * Wallet Creations
    * Sending tokens
    * Signing transactions
    * and more!
  </Step>
</Steps>

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