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

## 1. Setup Better Auth with Next.js

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!**

## 2. Setup the Better Auth JWT Plugin

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:

**Migrate**

<pre>
  `npx @better-auth/cli migrate`
</pre>

**Generate**

<pre>
  `npx @better-auth/cli generate`
</pre>

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

## 3. Create an auth-client.ts

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

## 4. Create API route handler

> 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);
```

## 5. Create a use-better-auth.ts for getting JWTs and Deploy your app

```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
```

## 6. Install the Chipi SDK

First, install the required packages:

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

## 7. Setup the Chipi SDK Provider

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>
  );
}

```

## 8. Add your JWKs Endpoint Url to Chipi 🕺 !

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

## 9. Using Better Auth with Chipi hooks 🕺 !

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]
>
> **Note:** 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.

## 10. Celebrate & Learn More!

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!

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


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