Skip to content

rogenecarl/better-auth-nextjs-authentication-boilerplater-with-userRoles

Repository files navigation

BetterAuth - Next.js Authentication Solution

Better Auth Logo

Next.js TypeScript Prisma Tailwind CSS License: MIT

A modern authentication solution built with Next.js 15, Prisma, and better-auth. This project provides a secure and customizable authentication system for web applications with form validation using Zod and TanStack React Query.

πŸš€ Features

  • πŸ” Secure authentication using better-auth
  • πŸ“¦ PostgreSQL database integration with Prisma
  • 🧩 Form validation with Zod
  • πŸ”„ API state management with TanStack React Query
  • πŸš€ Built with Next.js 15 and TurboCache for optimal performance
  • 🎨 UI components with Tailwind CSS and Shadcn/UI
  • πŸŒ™ Dark mode support with next-themes
  • πŸ”” Toast notifications with Sonner

πŸ“‹ Prerequisites

  • Node.js 18.x or higher
  • PostgreSQL database
  • npm or yarn

πŸ› οΈ Installation

1. Clone the repository

git clone https://github.com/Rogenecarl/better-auth-nextjs-authentication-boilerplater-with-userRoles.git
cd betterauth

2. Install dependencies

npm install
# or
yarn install

3. Set up environment variables

Copy the example.env file to .env:

cp example.env .env

Fill in the required environment variables:

BETTER_AUTH_SECRET= Your better auth secret || generate from better auth
BETTER_AUTH_URL=http://localhost:3000

# from server to client
NEXT_PUBLIC_API_URL=http://localhost:3000

# Connect to PostgreSQL via connection pooling
DATABASE_URL=postgresql://username:password@host:port/database
# Direct connection to the database. Used for migrations
DIRECT_URL=postgresql://username:password@host:port/database

GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=

NODEMAILER_USER=
NODEMAILER_APP_PASSWORD=

4. Initialize the database

npx prisma db push
npx prisma generate

πŸƒβ€β™‚οΈ Development

Start the development server:

npm run dev
# or
yarn dev

Open http://localhost:3000 with your browser to see the application.

🧰 NPM Dependencies

External Dependencies Installation

Then install the external dependencies:

# Authentication and database
npm install better-auth @prisma/client

# Form validation and data fetching
npm install zod @tanstack/react-query

# UI components
npm install sonner next-themes

# Install shadcn components (CLI)
npx shadcn-ui@latest init

# for password hashing
npm install @node-rs/argon2

# for email verification
npm install nodemailer

npm install @types/nodemailer -D

πŸ“Š Database Schema

The application uses the following data models:

  • User: Core user data (name, email, etc.)
  • Session: User sessions with expiration
  • Account: Provider accounts (OAuth, password)
  • Verification: For email verification
  • Post: Example model for user content

Database Diagram

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚    User     β”‚       β”‚  Session  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€       β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ id          β”‚       β”‚ id        β”‚
β”‚ createdAt   β”‚       β”‚ createdAt β”‚
β”‚ updatedAt   β”‚       β”‚ updatedAt β”‚
β”‚ name        β”‚       β”‚ expiresAt β”‚
β”‚ email       │◄─────── userId    β”‚
β”‚ emailVerified       β”‚ token     β”‚
β”‚ image       β”‚       β”‚ ipAddress β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜       β”‚ userAgent β”‚
       β–²              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚
       β”‚              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
       β”‚              β”‚   Verification  β”‚
       β”‚              β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
       β”‚              β”‚ id             β”‚
       β”‚              β”‚ createdAt      β”‚
       β”‚              β”‚ updatedAt      β”‚
       β”‚              β”‚ identifier     β”‚
       β”‚              β”‚ value          β”‚
       β”‚              β”‚ expiresAt      β”‚
       β”‚              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Account     β”‚       β”‚   Post    β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€       β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ id            β”‚       β”‚ id        β”‚
β”‚ createdAt     β”‚       β”‚ createdAt β”‚
β”‚ updatedAt     β”‚       β”‚ updatedAt β”‚
β”‚ accountId     β”‚       β”‚ title     β”‚
β”‚ providerId    β”‚       β”‚ content   β”‚
β”‚ accessToken   │◄─────── userId    β”‚
β”‚ refreshToken  β”‚       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚ idToken       β”‚
β”‚ password      β”‚
β”‚ userId        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ” Authentication Setup

The project uses better-auth for authentication:

  1. Authentication is configured in src/lib/auth.ts
  2. Client-side authentication hooks are available in src/lib/auth-client.ts
  3. API routes are set up in src/app/api/auth/[...all]/route.ts

Authentication Flow

  1. Registration: Users can register with email/password or OAuth providers
  2. Login: Secure login with email/password or OAuth
  3. Session Management: Sessions are stored in the database with expiration
  4. Profile Management: Users can update their profile information

πŸ“ Form Validation

Forms are validated using Zod schemas with a custom useZodForm hook that:

  1. Defines validation rules for form fields
  2. Provides real-time validation feedback
  3. Integrates with TanStack React Query for API calls
  4. Handles error states and displays user-friendly messages

πŸ—οΈ Project Structure

src/
β”œβ”€β”€ app/                   # Next.js App Router
β”‚   β”œβ”€β”€ api/               # API Routes
β”‚   β”‚   └── auth/          # Auth API Routes
β”‚   β”‚   β”œβ”€β”€ login/         # Login Page
β”‚   β”‚   └── register/      # Registration Page
β”‚   β”œβ”€β”€ profile/           # User Profile Page
β”‚   └── layout.tsx         # Root Layout
β”œβ”€β”€ components/            # React Components
β”‚   β”œβ”€β”€ hooks/             # Custom Hooks
β”‚   β”œβ”€β”€ providers/         # Context Providers
β”‚   β”œβ”€β”€ ui/                # UI Components
β”‚   β”œβ”€β”€ login-form.tsx     # Login Form Component
β”‚   └── register-form.tsx  # Registration Form Component
β”œβ”€β”€ generated/             # Generated Prisma Client
β”œβ”€β”€ lib/                   # Utility Functions
β”‚   β”œβ”€β”€ auth.ts            # Auth Configuration
β”‚   β”œβ”€β”€ auth-client.ts     # Client-side Auth Hooks
β”‚   β”œβ”€β”€ prisma.ts          # Prisma Client
β”‚   └── utils.ts           # Utility Functions

πŸ”¨ Building for Production

Build the application:

npm run build
# or
yarn build

Start the production server:

npm run start
# or
yarn start

🌱 Extending the Project

Adding OAuth Providers

To add OAuth providers like Google, GitHub, etc., modify src/lib/auth.ts:

export const auth = betterAuth({
  // Existing config...
  
  // Add OAuth providers
  oauth: {
    providers: [
      {
        id: "google",
        name: "Google",
        clientId: process.env.GOOGLE_CLIENT_ID!,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
      },
      // Add more providers as needed
    ],
  },
});

Adding New Pages

Create new pages in the src/app directory following Next.js App Router conventions.

πŸ“„ License

MIT

πŸ‘₯ Contributing

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

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors