Skip to content

Repository files navigation

Better Auth - Next.js Authentication Template

A modern, full-stack authentication starter built with Next.js, featuring email/password authentication, email verification, and password reset functionality powered by Better Auth.

Tech Stack

Frontend

Backend & Authentication

Form & Validation

Developer Tools

Features

  • ✅ Email/password authentication
  • ✅ Email verification
  • ✅ Password reset functionality
  • Two-Factor Authentication (2FA/OTP)
    • TOTP-based authentication (Google Authenticator, Authy, etc.)
    • QR code generation for easy setup
    • Backup codes for account recovery
    • Secure verification flow
  • ✅ Protected routes
  • ✅ Type-safe forms with validation
  • ✅ Dark mode support
  • ✅ Responsive design
  • ✅ Modern UI components

Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js (v20 or higher)
  • PostgreSQL (v14 or higher)
  • npm, yarn, pnpm, or bun package manager

Setup Instructions

1. Clone the Repository

git clone <repository-url>
cd better-auth

2. Install Dependencies

npm install
# or
yarn install
# or
pnpm install
# or
bun install

3. Configure Environment Variables

Create a .env file in the root directory by copying the example:

cp .env.example .env

Update the .env file with your configuration:

# Generate a random secret key (at least 32 characters)
BETTER_AUTH_SECRET=your-random-secret-key-here

# Base URL of your application
BETTER_AUTH_URL=http://localhost:3000

# PostgreSQL database connection string
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/better_auth

# SMTP Configuration (for email functionality)
SMTP_HOST=localhost
SMTP_PORT=1025
SMTP_FROM_EMAIL=noreply@betterauth.app
SMTP_FROM_NAME="Better Auth App"

Note: For development, you can use Mailpit or MailHog as a local SMTP server to test emails.

4. Set Up PostgreSQL Database

Create a new PostgreSQL database:

# Using psql
psql -U postgres
CREATE DATABASE better_auth;

Or use your preferred PostgreSQL client/tool.

5. Run Database Migrations

Generate and run database migrations using Drizzle:

# Generate migration files
npx drizzle-kit generate

# Push schema to database
npx drizzle-kit push

6. Start the Development Server

npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev

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

Project Structure

better-auth/
├── src/
│   ├── app/                    # Next.js App Router
│   │   ├── (auth)/            # Protected routes (dashboard)
│   │   ├── (public)/        # Public routes (login, signup)
│   │   └── api/auth/          # Better Auth API routes
│   ├── components/            # React components
│   │   ├── auth/              # Authentication forms
│   │   └── ui/                # Reusable UI components
│   ├── db/                    # Database configuration
│   │   ├── index.ts           # Drizzle instance
│   │   └── auth-schema.ts     # Database schema
│   ├── lib/                   # Utility libraries
│   │   ├── auth.ts            # Better Auth server config
│   │   ├── auth-client.ts     # Better Auth client config
│   │   ├── email.ts           # Email service
│   │   └── utils.ts           # Helper functions
│   └── schema/                # Validation schemas
├── drizzle/                   # Generated migration files
├── .env.example               # Environment variables template
├── drizzle.config.ts          # Drizzle ORM configuration
├── next.config.ts             # Next.js configuration
├── tailwind.config.ts         # TailwindCSS configuration
└── package.json               # Dependencies and scripts

Available Scripts

# Development
npm run dev          # Start development server

# Production
npm run build        # Build for production
npm run start        # Start production server

# Code Quality
npm run lint         # Run ESLint

Authentication Flow

  1. Sign Up - Users create an account with email/password
  2. Email Verification - Verification email sent to user
  3. Sign In - Users authenticate with verified credentials
  4. Password Reset - Users can request password reset via email
  5. Two-Factor Authentication (Optional) - Enhanced security with TOTP
  6. Protected Routes - Dashboard and other protected pages require authentication

Two-Factor Authentication (2FA)

This application includes a complete Two-Factor Authentication implementation using Time-based One-Time Passwords (TOTP).

How It Works

  1. Setup Process:

    • Users navigate to the dashboard after signing in
    • Click "Enable 2FA" and confirm with their password
    • Scan the QR code with an authenticator app (Google Authenticator, Authy, 1Password, etc.)
    • Save the provided backup codes securely
    • Enter a 6-digit code from the authenticator app to verify setup
  2. Sign-In with 2FA:

    • Enter email and password as usual
    • Get redirected to the 2FA verification page
    • Enter the 6-digit code from your authenticator app
    • Access your account after successful verification
  3. Account Recovery:

    • Use backup codes if you lose access to your authenticator app
    • Each backup code can be used once
    • Generate new backup codes after using them

Supported Authenticator Apps

  • Google Authenticator
  • Microsoft Authenticator
  • Authy
  • 1Password
  • Bitwarden
  • Any TOTP-compatible authenticator app

Security Features

  • QR Code Setup: Easy enrollment with any authenticator app
  • Backup Codes: 10 unique codes for account recovery
  • Time-Based Codes: Codes expire every 30 seconds
  • Secure Storage: All secrets are encrypted in the database
  • Graceful Fallback: Backup codes ensure you never lose access

Learn More

Next.js Resources

Better Auth Resources

Database Resources

Deployment

Vercel (Recommended)

The easiest way to deploy your Next.js app is to use the Vercel Platform:

  1. Push your code to a Git repository (GitHub, GitLab, Bitbucket)
  2. Import your repository to Vercel
  3. Add your environment variables in the Vercel dashboard
  4. Deploy!

Check out the Next.js deployment documentation for more details.

Database Hosting

For production, consider using managed PostgreSQL services:

  • Neon - Serverless PostgreSQL
  • Supabase - PostgreSQL with additional features
  • Railway - PostgreSQL and app hosting
  • Render - PostgreSQL and web services

License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages