Skip to content

Setifier/nextjs-better-auth-starter

Repository files navigation

Next.js Better Auth Starter

A complete authentication starter template built with Next.js 15, Better Auth, Prisma ORM, PostgreSQL, and Nodemailer. This template provides all the essential authentication features you need to get started quickly with your next project.

πŸš€ Features

πŸ” Authentication Methods

  • Email & Password - Traditional signup/login with email verification
  • Magic Link - Passwordless authentication via email
  • OAuth - Social login with Google and GitHub
  • Admin Panel - User management with role-based access

πŸ“§ Email Features

  • Email Verification - Verify email addresses on signup
  • Password Reset - Secure password reset flow
  • Magic Link Login - One-click login via email
  • Custom Email Templates - Beautiful HTML email templates

πŸ‘€ User Management

  • User Profiles - Update name, email, and password
  • Role-based Access - User and Admin roles with permissions
  • Account Linking - Link multiple OAuth accounts
  • Session Management - Secure session handling with cookies

πŸ›‘οΈ Security Features

  • Password Hashing - Argon2 encryption for passwords
  • CSRF Protection - Built-in CSRF protection
  • Secure Cookies - HTTP-only, secure cookies
  • Email Validation - Domain-based email validation
  • Name Validation - Custom name validation rules

🎨 UI Components

  • Responsive Design - Mobile-first responsive design
  • Modern UI - Built with Tailwind CSS and Radix UI
  • Toast Notifications - User feedback with Sonner
  • Loading States - Proper loading indicators
  • Form Validation - Client-side and server-side validation

πŸ› οΈ Tech Stack

  • Framework: Next.js 15 (App Router)
  • Authentication: Better Auth
  • Database: PostgreSQL with Prisma ORM
  • Styling: Tailwind CSS + Radix UI
  • Email: Nodemailer
  • TypeScript: Full type safety
  • Icons: Lucide React

πŸ“¦ Quick Start

Prerequisites

  • Node.js 18+
  • PostgreSQL database
  • SMTP email service (Gmail, SendGrid, etc.)

Installation

  1. Clone the repository
git clone https://github.com/yourusername/nextjs-better-auth-starter.git
cd nextjs-better-auth-starter
  1. Install dependencies
npm install
  1. Environment Setup Create a .env.local file in the root directory:
# Database
DATABASE_URL="postgresql://username:password@localhost:5432/your_db_name"

# Better Auth
BETTER_AUTH_SECRET="your-secret-key-here"
NEXT_PUBLIC_API_URL="http://localhost:3000"

# OAuth Providers
GOOGLE_CLIENT_ID="your-google-client-id"
GOOGLE_CLIENT_SECRET="your-google-client-secret"
GITHUB_CLIENT_ID="your-github-client-id"
GITHUB_CLIENT_SECRET="your-github-client-secret"

# Email (Nodemailer)
NODEMAILER_HOST="smtp.gmail.com"
NODEMAILER_PORT="587"
NODEMAILER_USER="your-email@gmail.com"
NODEMAILER_PASS="your-app-password"

# Admin Emails (semicolon separated)
ADMIN_EMAILS="admin@example.com;admin2@example.com"
  1. Database Setup
# Generate Prisma client
npx prisma generate

# Push database schema
npx prisma db push
  1. Run the development server
npm run dev

Open http://localhost:3000 in your browser.

πŸ“ Project Structure

src/
β”œβ”€β”€ app/                    # Next.js app router
β”‚   β”œβ”€β”€ auth/              # Authentication pages
β”‚   β”œβ”€β”€ admin/             # Admin dashboard
β”‚   β”œβ”€β”€ profile/           # User profile
β”‚   └── api/auth/          # Better Auth API routes
β”œβ”€β”€ components/            # Reusable components
β”‚   β”œβ”€β”€ ui/               # UI components (shadcn/ui)
β”‚   β”œβ”€β”€ *-form.tsx        # Authentication forms
β”‚   └── *.tsx             # Other components
β”œβ”€β”€ actions/               # Server actions
β”œβ”€β”€ lib/                   # Utility functions
β”‚   β”œβ”€β”€ auth.ts           # Better Auth configuration
β”‚   β”œβ”€β”€ auth-client.ts    # Client-side auth
β”‚   └── prisma.ts         # Prisma client
└── middleware.ts          # Route protection

πŸ”§ Configuration

OAuth Setup

Google OAuth

  1. Go to Google Cloud Console
  2. Create a new project or select existing
  3. Enable Google+ API
  4. Create OAuth 2.0 credentials
  5. Add authorized redirect URI: http://localhost:3000/api/auth/callback/google

GitHub OAuth

  1. Go to GitHub Settings > Developer settings > OAuth Apps
  2. Create a new OAuth App
  3. Set Authorization callback URL: http://localhost:3000/api/auth/callback/github

Email Configuration

The template supports any SMTP provider. For Gmail:

  1. Enable 2-Factor Authentication
  2. Generate an App Password
  3. Use the app password in NODEMAILER_PASS

πŸš€ Deployment

Database

Deploy your PostgreSQL database (recommended: Neon, Supabase, or PlanetScale)

Application

Deploy to Vercel, Netlify, or any platform supporting Next.js:

npm run build
npm start

Update your environment variables with production values.

πŸ“– Usage Examples

Protecting Routes

// middleware.ts
import { auth } from "@/lib/auth";

export default auth((request) => {
  if (!request.auth && request.nextUrl.pathname.startsWith("/profile")) {
    return Response.redirect(new URL("/auth/login", request.url));
  }
});

Using Session Data

"use client";
import { useSession } from "@/lib/auth-client";

export function ProfileComponent() {
  const { data: session } = useSession();

  if (!session) return <div>Not logged in</div>;

  return <div>Welcome, {session.user.name}!</div>;
}

Server-side Authentication

import { auth } from "@/lib/auth";

export default async function ProtectedPage() {
  const session = await auth.api.getSession({ headers: headers() });

  if (!session) redirect("/auth/login");

  return <div>Protected content</div>;
}

🀝 Contributing

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

πŸ“„ License

This project is licensed under the MIT License.

πŸ™ Thanks & Acknowledgements

  • Special thanks to Khurram Ali (GiraffeReactor) for his amazing tutorial that helped build this project. His detailed walkthrough and guidance were invaluable.

About

Complete Next.js authentication starter with Better Auth, Prisma, PostgreSQL & Nodemailer

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published