Skip to main content
1

Setup Better Auth with Next.js

First, follow the complete Better Auth Next.js Quickstart Guide to set up your Better Auth project and Next.js integration. Then proceed to Better Auth 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:
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"
               
            }
        })
    ]
});
  1. Migrate or generate your database:
  • Migrate
  • Generate
npx @better-auth/cli migrate
Note: Before proceeding, check the Better Auth CLI Docs 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
"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.
// 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

"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,
  };
}
  1. Deploy your app, then add your deployed application URL to your environment variables:
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:
# Install Chipi Pay SDK
npm install @chipi-stack/nextjs
7

Setup the Chipi SDK Provider

  1. In your .env file, add your Chipi API keys:
NEXT_PUBLIC_CHIPI_API_KEY=your_chipi_api_public_key
CHIPI_SECRET_KEY=your_chipi_api_secret_key
  1. Set up the Chipi Pay provider in your application:
// 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, select Better Auth as your auth provider and paste your JWKS Endpoint URL.
https://my-deployed-app-domain.com/api/auth/jwks 
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:
"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>
  );
}
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!
Need help? Check out our Telegram Community for support and to connect with other developers.