Next.jsReactSaaSStarter

nextjs-better-auth — Next.js SaaS Template

By rogenecarl

An authentication starter template built on Next.js and Better Auth, integrating Prisma, PostgreSQL, and role-based access control, with sign-in/sign-up, Google OAuth, and dashboard pages.

Explore the design

Compare the page layouts and mobile experience. Open any screenshot for a closer look.

2 previews
Desktop homepage1 / 2
Desktop captureTop of page

Actual screenshot captured by the server browser.

All pages & views 2

Screenshots show visual appearance; interactive behavior may differ.

Recorded 2026-10-01View source

What stands out

A quick read of the recorded project description.

01

Implements email/password sign-in and Google OAuth with Better Auth, and provides sign-in, sign-up, and provider registration pages

02

Includes three built-in roles—USER, ADMIN, and PROVIDER—with corresponding protected dashboard routes

03

Connects to PostgreSQL via Prisma, with README connection string examples for Neon, Supabase, Railway, Render, and self-hosted databases

04

Provides server helpers such as requireAuth, requireRole, and getServerSession, plus client guards like useAuth and AuthGuard

05

Authentication endpoints include rate limiting, along with session cookie caching and cross-tab sign-out synchronization

06

Uses Tailwind CSS and shadcn/ui components, with forms combining React Hook Form and Zod validation

Template Details

This is a Next.js authentication starter template for SaaS scenarios; the repository is MIT-licensed. Authentication uses Better Auth and supports email/password sign-in and Google OAuth; the data layer uses Prisma to connect to PostgreSQL, and the README explains database access through a driver adapter. The template includes three built-in roles—USER, ADMIN, and PROVIDER—with protected pages at /dashboard, /admin/dashboard, and /provider/dashboard respectively; role redirects are centrally configured in src/config/auth.ts.

The project structure is organized by feature: src/app contains route groups such as (auth), (landing), (user), admin, and provider, plus the api/auth endpoint; src/actions/auth holds server actions for sign-in, sign-up, and provider registration; src/components is split into auth and ui; src/lib centralizes the Better Auth server configuration, React client, server helpers, and the Prisma singleton; src/schema stores Zod validation rules. The README also provides usage examples for server helpers such as requireAuth, requireRole, and getServerSession, as well as the useAuth hook and client guard components including AuthGuard, AdminOnly, ProviderOnly, and UserOnly.

The template includes route protection (the README describes it as based on Next.js's optimistic proxy), rate limiting for authentication endpoints (e.g., 5 attempts per 5 minutes for sign-in and sign-up, 3 per 5 minutes for password reset), session cookie caching, and cross-tab sign-out synchronization. Styling uses Tailwind CSS and shadcn/ui components, forms combine React Hook Form with Zod, and client-side data fetching uses TanStack Query.

Before use, you need Node.js 18+, a package manager, and a PostgreSQL database, and you must configure DATABASE_URL, BETTER_AUTH_SECRET, BETTER_AUTH_URL, and NEXT_PUBLIC_APP_URL; Google sign-in also requires GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET. The README lists connection string examples for Neon, Supabase, Railway, Render, and self-hosted Docker, and recommends deploying on Vercel. The repository has few stars and is a personally maintained starter template; the licensing and costs of third-party assets and external services (database, hosting, OAuth) must be verified independently.

Next.jsReactSaaSStarter

Is it right for your project?

Use Cases

  • Setting up role-differentiated sign-in/sign-up and admin entry points for a SaaS project
  • Starting a Next.js application that needs both email/password and Google OAuth sign-in
  • Projects using Prisma and PostgreSQL that want predefined user roles and permission-based routes
  • A template starting point that needs basic security configuration such as authentication endpoint rate limiting and session caching

Suitable For

  • Developers familiar with Next.js App Router and TypeScript
  • Teams planning to use PostgreSQL and accepting Prisma as the ORM
  • SaaS projects that need a multi-role (regular user, admin, provider) permission structure
  • Users who want to modify and distribute based on MIT-licensed code

Getting started & customization

Use these recorded setup notes alongside the repository instructions for your chosen version.

  1. 1

    Requires Node.js 18+ and pnpm/npm/yarn, plus a PostgreSQL database

  2. 2

    Copy .env.example to .env and fill in DATABASE_URL, BETTER_AUTH_SECRET (at least 32 characters), BETTER_AUTH_URL, and NEXT_PUBLIC_APP_URL

  3. 3

    Google sign-in requires creating an OAuth client in Google Cloud Console with the callback URL {APP_URL}/api/auth/callback/google

  4. 4

    Run npx prisma generate, then create tables with npx prisma db push or prisma migrate dev, then run pnpm dev

  5. 5

    When deploying to platforms such as Vercel, set production environment variables separately; database, hosting, and OAuth services may incur additional costs

Read repository instructions

License & source material

Usage conditions & limitations

Free to use · keep license notice

This entry covers the free version in a public repository under the MIT license; the free scope is the code of that version and does not mean external services or third-party assets are free.

Must comply with when using

  • You may use, modify, commercialize, and distribute the code of this version for free.
  • When distributing copies or substantial portions of the code, retain the original author's copyright notice and the full MIT license notice.
  • The code is provided as is; warranties and limitations of liability are governed by the original license and applicable law.

Additional costs & items to verify

  • Using this template requires preparing and running your own PostgreSQL database; the template itself does not include a database service, and you bear database hosting or self-hosting costs.
  • Google sign-in is optional; to enable it, you must create an OAuth client in Google Cloud Console and provide GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET.
  • You must generate and configure a BETTER_AUTH_SECRET of at least 32 characters yourself; otherwise authentication cannot run securely.
  • When deploying to platforms such as Vercel, you must configure production environment variables yourself; hosting, database, and OAuth services may incur additional costs.
  • Demo images, fonts, icons, and other third-party assets must be checked against their respective licenses and cannot be judged solely by the code's MIT license.
  • External services such as domains, hosting, databases, payments, or AI may charge separately.
View Original Text Basis

Permission is hereby granted, free of charge

Original License Text

PostgreSQL database (see [Database Providers](#database-providers))

Original README

Google OAuth (optional)

Original README

BETTER_AUTH_SECRET="generate-a-strong-secret-at-least-32-characters"

Original README

Add environment variables in Vercel dashboard

Original README
https://github.com/rogenecarl/nextjs-better-auth/blob/main/LICENSEhttps://github.com/rogenecarl/nextjs-better-auth/blob/main/README.md

Compiled by DeepSeek based on repository license and README ·2026-10-01. Results only cover the materials read; dependencies, images, fonts, and subsequent term changes are subject to their respective original texts.

Project checks & description sources

Template Information

Source platforms
GitHub
Documentation and maintenance reference score
More documented · 88 / 100
Technologies
Next.js · React
Website type
SaaS · Starter
How this score is calculated

Our heuristic uses license records (up to 30), a demo link (12), a preview (10), stars (15), recorded maintenance (15), description completeness (8), feature records (5) and classification data (5). It is not a code, security or performance test, or a Google score. A link does not establish tested functionality.

What to verify for this project

Repository update recorded
2026-07-15
Screenshot last checked
2026-10-01

A demo link is listed. Check it with your own content and viewport sizes; its presence does not confirm that forms, authentication or payments work.

The catalog identifies Next.js as the primary stack. Check the actual dependency manifest and lockfile for versions and hosting requirements. These notes use recorded metadata, not a code audit or a deployment test.

Use a selection guide →

How this description was prepared

AI-assisted description based on catalog records and repository material. Repository authors are not automatically the reviewers of this description.

Automatically checked against source and license rules; no manual editorial review.

Inspect the recorded source material

SHA-256: 38cbdf7b1442092f72e2d20c768ffa65d49aaf175b67919ec187dabcf751a64c

2026-10-01T01:23:35.629Z

Source file / repository
# Next.js 16 + Better Auth + Prisma 7 Starter Kit

A production-ready authentication starter kit built with the latest Next.js 16, Better Auth, and Prisma 7. Features role-based access control, Google OAuth, and a clean, scalable architecture.

**[Live Demo](https://nextjs16-betterauth-prisma-starterk.vercel.app/)**

---

## Features

- **Next.js 16** with App Router and React 19
- **Better Auth** for authentication (email/password + Google OAuth)
- **Prisma 7** with PostgreSQL (using driver adapters)
- **Role-Based Access Control** (USER, ADMIN, PROVIDER)
- **Route Protection** with optimistic proxy (Next.js 16+ feature)
- **TanStack Query** for client-side data fetching
- **Zod 4** for form validation
- **Tailwind CSS 4** with shadcn/ui components
- **Rate Limiting** built-in for auth endpoints
- **Session Cookie Caching** for reduced database calls
- **Cross-Tab Sign Out Sync**
- **TypeScript** throughout

---

## Tech Stack

| Category | Technology |
|----------|------------|
| Framework | Next.js 16 |
| Authentication | Better Auth |
| Database ORM | Prisma 7 |
| Database | PostgreSQL |
| Styling | Tailwind CSS 4 + shadcn/ui |
| Forms | React Hook Form + Zod 4 |
| Data Fetching | TanStack Query |
| Language | TypeScript |

---

## Getting Started

### Prerequisites

- Node.js 18+
- pnpm (recommended) or npm/yarn
- PostgreSQL database (see [Database Providers](#database-providers))

### 1. Clone the Repository

```bash
git clone https://github.com/rogenecarl/nextjs16-betterauth-prisma-starterkit.git
cd nextjs16-betterauth-prisma-starterkit
```

### 2. Install Dependencies

```bash
pnpm install
```

### 3. Set Up Environment Variables

Copy the example environment file:

```bash
cp .env.example .env
```

Edit `.env` with your values:

```env
# Database (PostgreSQL connection string)
DATABASE_URL="postgresql://user:password@host:5432/database?sslmode=require"

# Better Auth
BETTER_AUTH_SECRET="generate-a-strong-secret-at-least-32-characters"
BETTER_AUTH_URL="http://localhost:3000"

# Google OAuth (optional)
GOOGLE_CLIENT_ID="your-google-client-id"
GOOGLE_CLIENT_SECRET="your-google-client-secret"

# App URL
NEXT_PUBLIC_APP_URL="http://localhost:3000"
```

Generate a secure secret:

```bash
openssl rand -base64 32
```

### 4. Set Up the Database

Generate the Prisma client and push the schema to your database:

```bash
# Generate Prisma client
npx prisma generate

# Push schema to database (creates tables)
npx prisma db push
```

Or create a migration for version control:

```bash
npx prisma migrate dev --name init
```

### 5. Run the Development Server

```bash
pnpm dev
```

Open [http://localhost:3000](http://localhost:3000) in your browser.

---

## Database Providers

This starter kit supports multiple PostgreSQL providers. Update your `DATABASE_URL` accordingly:

### Neon (Recommended for Vercel)

```env
DATABASE_URL="postgresql://user:[email protected]/dbname?sslmode=require"
```

### Supabase

```env
DATABASE_URL="postgresql://postgres.[project-ref]:[password]@aws-0-[region].pooler.supabase.com:6543/postgres"
```

### Railway

```env
DATABASE_URL="postgresql://postgres:[password]@[host].railway.app:5432/railway"
```

### Render

```env
DATABASE_URL="postgresql://user:pass@[host].render.com:5432/dbname?sslmode=require"
```

### Self-Hosted / Docker

```env
DATABASE_URL="postgresql://postgres:password@localhost:5432/mydb"
```

---

## Project Structure

```
src/
├── actions/auth/         # Server actions (signIn, signUp, signUpProvider)
├── app/
│   ├── (auth)/           # Auth pages (login, register, register-provider)
│   ├── (landing)/        # Landing page
│   ├── (user)/           # User dashboard (protected)
│   ├── admin/            # Admin dashboard (protected)
│   ├── provider/         # Provider dashboard (protected)
│   └── api/auth/         # Better Auth API routes
├── components/
│   ├── auth/             # Auth components (forms, guards)
│   └── ui/               # shadcn/ui components
├── config/
│   └── auth.ts           # Centralized auth config (role redirects)
├── context/              # React Query provider
├── hooks/                # Custom hooks (useAuth, useRequireAuth)
├── lib/
│   ├── generated/prisma/ # Prisma client (auto-generated)
│   ├── auth.ts           # Better Auth server config
│   ├── auth-client.ts    # Better Auth React client
│   ├── auth-server.ts    # Server-side auth helpers
│   └── db.ts             # Prisma singleton
├── schema/               # Zod validation schemas
├── types/                # TypeScript types
└── proxy.ts              # Route protection (optimistic)
```

---

## Authentication

### User Roles

Three roles are available out of the box:

| Role | Dashboard | Description |
|------|-----------|-------------|
| `USER` | `/dashboard` | Default role for regular users |
| `ADMIN` | `/admin/dashboard` | Administrative access |
| `PROVIDER` | `/provider/dashboard` | Service provider access |

### Auth Pages

- `/login` - Sign in with email/password or Google
- `/register` - User registration
- `/register-provider` - Provider registration
- `/choose-role` - Role selection (if applicable)

### Server-Side Helpers

```typescript
// In Server Components
import { requireAuth, requireRole, getServerSession } from "@/lib/auth-server"

// Require authentication
export default async function ProtectedPage() {
  const session = await requireAuth()
  return <div>Hello {session.user.name}</div>
}

// Require specific role
export default async function AdminPage() {
  const session = await requireRole("ADMIN")
  return <div>Admin Panel</div>
}
```

### Client-Side Hooks

```typescript
// In Client Components
import { useAuth } from "@/hooks"

export function MyComponent() {
  const { user, isAuthenticated, isAdmin, signOut, isPending } = useAuth()

  if (isPending) return <Loading />
  if (!isAuthenticated) return <LoginPrompt />

  return <div>Hello {user.name}</div>
}
```

### Auth Guard Components

```tsx
import { AuthGuard, AdminOnly, ProviderOnly, UserOnly } from "@/components/auth/auth-guard"

// Basic authentication guard
<AuthGuard fallback={<Loading />}>
  <ProtectedContent />
</AuthGuard>

// Role-specific guards
<AdminOnly>
  <AdminPanel />
</AdminOnly>

<ProviderOnly>
  <ProviderDashboard />
</ProviderOnly>
```

---

## Google OAuth Setup

1. Go to [Google Cloud Console](https://console.cloud.google.com/apis/credentials)
2. Create a new OAuth 2.0 Client ID
3. Add authorized redirect URI: `{YOUR_APP_URL}/api/auth/callback/google`
4. Copy the Client ID and Client Secret to your `.env` file

---

## Available Scripts

```bash
pnpm dev          # Start development server
pnpm build        # Production build
pnpm start        # Start production server
pnpm lint         # Run ESLint

# Database
npx prisma generate              # Regenerate Prisma client
npx prisma migrate dev --name    # Create migration
npx prisma db push               # Push schema changes
npx prisma studio                # Open Prisma Studio GUI
```

---

## Deployment

### Vercel (Recommended)

1. Push your code to GitHub
2. Import the repository in [Vercel](https://vercel.com)
3. Add environment variables in Vercel dashboard
4. Deploy

The `postinstall` script automatically runs `prisma generate` during deployment.

### Environment Variables for Production

Make sure to set these in your deployment platform:

- `DATABASE_URL` - Your production PostgreSQL connection string
- `BETTER_AUTH_SECRET` - A strong, unique secret (different from development)
- `BETTER_AUTH_URL` - Your production URL (e.g., `https://yourdomain.com`)
- `NEXT_PUBLIC_APP_URL` - Same as `BETTER_AUTH_URL`
- `GOOGLE_CLIENT_ID` - Google OAuth client ID
- `GOOGLE_CLIENT_SECRET` - Google OAuth client secret

---

## Customization

### Adding a New Role

1. Update the `UserRole` enum in `prisma/schema.prisma`:

```prisma
enum UserRole {
  USER
  ADMIN
  PROVIDER
  MODERATOR  // Add new role
}
```

2. Run `npx prisma db push` or create a migration

3. Add the role redirect in `src/config/auth.ts`:

```typescript
export const ROLE_REDIRECTS: Record<Role, string> = {
  ADMIN: "/admin/dashboard",
  PROVIDER: "/provider/dashboard",
  USER: "/dashboard",
  MODERATOR: "/moderator/dashboard",  // Add redirect
}
```

4. Update `src/proxy.ts` if needed for route protection

### Adding Social Providers

Better Auth supports multiple OAuth providers. Add them in `src/lib/auth.ts`:

```typescript
socialProviders: {
  google: { ... },
  github: {
    clientId: process.env.GITHUB_CLIENT_ID!,
    clientSecret: process.env.GITHUB_CLIENT_SECRET!,
  },
}
```

---

## Rate Limiting

Built-in rate limiting protects auth endpoints:

| Endpoint | Window | Max Requests |
|----------|--------|--------------|
| `/sign-in/email` | 5 min | 5 |
| `/sign-up/email` | 5 min | 5 |
| `/forget-password` | 5 min | 3 |
| `/reset-password` | 5 min | 5 |
| `/get-session` | 1 min | 20 |

Configure in `src/lib/auth.ts`.

---

## Author

**Rogene Carl**
- GitHub: [@rogenecarl](https://github.com/rogenecarl)

---

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

---

## License

This project is open source and available under the [MIT License](LICENSE).

---

## Acknowledgments

- [Next.js](https://nextjs.org/)
- [Better Auth](https://better-auth.com/)
- [Prisma](https://prisma.io/)
- [shadcn/ui](https://ui.shadcn.com/)
- [TanStack Query](https://tanstack.com/query)
Report a correction

Explore similar templates

Compare previews and descriptions within the same stack and category.