Skip to content

Instantly share code, notes, and snippets.

@kazi331
Created October 7, 2025 17:24
Show Gist options
  • Select an option

  • Save kazi331/ae5077f116c5d611eaaca84a086d7ee7 to your computer and use it in GitHub Desktop.

Select an option

Save kazi331/ae5077f116c5d611eaaca84a086d7ee7 to your computer and use it in GitHub Desktop.
Setup better-auth in next.js with prisma and sqlite

Minimal Setup: Better Auth + Prisma (SQLite/Postgres)

This guide shows how to set up Better Auth with Prisma and a database (SQLite or Postgres) in a Next.js project.


1. Install dependencies

# Core dependencies
pnpm add better-auth @prisma/client

# Dev dependencies
pnpm add -D prisma

# add auth secret in .env
BETTER_AUTH_SECRET=KfUQ5cyOUARB4x1y9R8Af5QYq1H5ZcCr

# add auth base url in .env
BETTER_AUTH_URL=http://localhost:3000 # Base URL of your app

Init and Generate prisma client

# Initialize Prisma
npx prisma init
npx prisma generate # this will install prisma, @prisma/client and generate Prisma Client

add db into .env

DATABASE_URL="file:./dev.db" for sqlite and DATABASE_URL="postgresql://username:password@localhost:5432/dbname?schema=public" for postgres

2. Add auth config in /lib/auth.ts

import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
// If your Prisma file is located elsewhere, you can change the path
import { PrismaClient } from "@/generated/prisma";
const prisma = new PrismaClient();
export const auth = betterAuth({
    database: prismaAdapter(prisma, {
        provider: "sqlite", // or "mysql", "postgresql", ...etc
    }),
});

Create db tables using better-auth CLI

npx @better-auth/cli generate

Update authentication methods

import { betterAuth } from "better-auth";
export const auth = betterAuth({
  //...other options
  emailAndPassword: { 
    enabled: true, 
  }, 
  socialProviders: { 
    github: { 
      clientId: process.env.GITHUB_CLIENT_ID as string, 
      clientSecret: process.env.GITHUB_CLIENT_SECRET as string, 
    }, 
  }, 
});

Mount Handler in /app/api/auth/[...all]/route.ts

import { auth } from "@/lib/auth"; // path to your auth file
import { toNextJsHandler } from "better-auth/next-js";

export const { POST, GET } = toNextJsHandler(auth);

Create Client instance in lib/auth-client.ts

import { createAuthClient } from "better-auth/react"
export const authClient = createAuthClient({
    /** The base URL of the server (optional if you're using the same domain) */
    baseURL: "http://localhost:3000"
})
export const { signIn, signUp, useSession } = createAuthClient()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment