Skip to content

backend-bits/better-auth-mysql

Repository files navigation

Better Auth MySQL Demo

A modern authentication template built with Next.js, Better Auth, and MySQL. Features user registration, authentication, and a full-featured todo application demonstrating CRUD operations with MySQL.

Features

  • 🔐 Authentication: Complete auth system with Better Auth
    • Email/password registration and login
    • GitHub OAuth support (configurable)
    • Session management with middleware protection
  • 🐬 MySQL Integration: Full MySQL adapter for Better Auth
    • User and session storage
    • Todo CRUD operations
  • 🎨 Modern UI: Built with shadcn/ui components
    • Responsive design
    • Dark/light theme support
    • Beautiful, accessible components
  • Todo Management: Complete todo application
    • Create, read, update, delete todos
    • Toggle completion status
    • User-specific todos with authentication

Tech Stack

  • Framework: Next.js 15 with App Router
  • Authentication: Better Auth with MongoDB adapter
  • Database: MySQL
  • Styling: TailwindCSS + shadcn/ui
  • TypeScript: Full type safety
  • UI Components: Radix UI + Lucide icons

Getting Started

This guide will help you set up the project from scratch. Follow these steps carefully to get the application running locally.

Prerequisites

  • Node.js 18 or higher - Download from nodejs.org
  • MySQL database - Choose one of the options below:
    • Local MySQL installation
    • Cloud MySQL service (AWS RDS, PlanetScale, etc.)

Step 1: Clone the Repository

git clone <repository-url>
cd better-auth-mongodb

Step 2: Install Dependencies

npm install

Step 3: Set Up MySQL

Option A: Local MySQL (Recommended for Development)

  1. Install MySQL:

    • Windows: Download from mysql.com
    • macOS: Use Homebrew: brew install mysql
    • Linux: Use your package manager: sudo apt install mysql-server (Ubuntu/Debian)
  2. Start MySQL:

    # Windows (as Administrator)
    net start MySQL
    
    # macOS with Homebrew
    brew services start mysql
    
    # Linux
    sudo systemctl start mysql
  3. Create a database:

    mysql -u root -p
    CREATE DATABASE better_auth;
    EXIT;
  4. Verify MySQL is running:

    mysql --version

Option B: Cloud MySQL (PlanetScale, AWS RDS, etc.)

  1. Create an account with your preferred MySQL provider
  2. Create a new database instance
  3. Get your connection details (host, user, password, database name)

Step 4: Configure Environment Variables

  1. Copy the example file:

    cp .env.example .env.local
  2. Edit .env.local with your actual values:

    # MySQL Configuration
    MYSQL_HOST=localhost
    MYSQL_USER=root
    MYSQL_PASSWORD=your-mysql-password
    MYSQL_DATABASE=better_auth
    
    # Better Auth Configuration
    NEXT_PUBLIC_AUTH_URL=http://localhost:3000
    BETTER_AUTH_SECRET=your-secure-secret-key-here-minimum-32-characters
    
    # GitHub OAuth (required for social login)
    GITHUB_CLIENT_ID=your-github-client-id
    GITHUB_CLIENT_SECRET=your-github-client-secret

Generating BETTER_AUTH_SECRET

You need a secure random string of at least 32 characters. Generate it using one of these methods:

Option 1: Using OpenSSL (Recommended)

openssl rand -base64 32

Option 2: Using Node.js

node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"

Option 3: Online Generator Use a secure password generator like passwordsgenerator.net with 32+ characters.

Setting Up GitHub OAuth

  1. Go to GitHub Settings > Developer settings > OAuth Apps
  2. Click "New OAuth App"
  3. Fill in the form:
    • Application name: Better Auth Demo (or any name)
    • Homepage URL: http://localhost:3000
    • Authorization callback URL: http://localhost:3000/api/auth/callback/github
  4. Click "Register application"
  5. Copy the Client ID and Client Secret to your .env.local file

Step 5: Run the Application

npm run dev

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

Step 6: Verify Setup

  1. Visit the homepage - you should see the welcome page
  2. Click "Sign Up" and create an account
  3. Try logging in with email/password or GitHub
  4. Access the todos page to test CRUD operations

Troubleshooting

  • MySQL connection issues: Ensure MySQL is running and the credentials are correct
  • Auth errors: Double-check your BETTER_AUTH_SECRET and GitHub OAuth credentials
  • Port conflicts: If port 3000 is busy, Next.js will suggest an alternative port
  • Environment variables not loading: Ensure the file is named .env.local (not .env)

Next Steps

Project Structure

src/
├── app/                    # Next.js App Router
│   ├── api/auth/          # Better Auth API routes
│   ├── auth/              # Authentication pages (login/signup)
│   ├── todos/             # Todo management page
│   └── page.tsx           # Landing page
├── components/            # React components
│   ├── auth/              # Authentication components
│   └── ui/                # shadcn/ui components
├── hooks/                 # Custom React hooks
├── lib/                   # Core utilities and configuration
│   ├── auth.ts           # Better Auth configuration
│   ├── auth-client.ts    # Client-side auth hooks
│   ├── auth-server.ts    # Server-side auth utilities
│   ├── actions.ts        # Server actions with auth checks
│   ├── mysql.ts          # MySQL client setup
│   ├── env.ts            # Environment variable validation
│   ├── types.ts          # TypeScript definitions
│   └── utils.ts          # Utility functions (cn, etc.)
└── middleware.ts          # Route protection middleware
components.json            # shadcn/ui configuration
.env.example              # Environment variables template

Authentication Flow

  1. Landing Page: Welcome screen that redirects authenticated users to todos
  2. Registration/Login: Forms with validation and error handling
  3. Todo Dashboard: Protected route at /todos with user profile and todo management
  4. Session Management: Automatic session handling with Better Auth and middleware protection

API Routes

  • POST /api/auth/* - Better Auth endpoints (handled automatically)

Todo operations are handled via server actions in src/lib/actions.ts instead of API routes:

  • getTodos() - Fetch user's todos
  • createTodo() - Create new todo
  • updateTodo() - Update todo
  • deleteTodo() - Delete todo

MySQL Schema

The app uses Better Auth's automatic table creation for users and sessions, plus custom tables for todos with proper user relationships.

Commands

  • npm run dev - Start development server with Turbopack
  • npm run build - Build for production
  • npm run start - Start production server
  • npm run lint - Run ESLint

Production Deployment

This template is development-ready and secure for initial use, but production deployment requires additional configuration. The template provides a solid foundation, but making it production-ready is the responsibility of the developer.

Security Enhancements

  1. HTTPS Enforcement:

    // In next.config.ts
    export default {
      // ... other config
      headers: [
        {
          source: '/(.*)',
          headers: [
            { key: 'X-Frame-Options', value: 'DENY' },
            { key: 'X-Content-Type-Options', value: 'nosniff' },
            { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
          ],
        },
      ],
    }
  2. Environment Variables:

    • Use different secrets for each environment
    • Store secrets in secure vaults (AWS Secrets Manager, etc.)
    • Never commit .env files
  3. Rate Limiting:

    • Implement rate limiting for auth endpoints
    • Consider using services like Cloudflare or AWS WAF

Infrastructure Setup

  1. Database:

    • Use managed MySQL (AWS RDS, PlanetScale, Google Cloud SQL)
    • Set up automated backups
    • Configure connection pooling properly
    • Enable SSL connections
  2. Deployment:

    • Use platforms like Vercel, Netlify, or AWS
    • Set up CI/CD pipelines
    • Implement health checks
    • Configure monitoring
  3. Monitoring & Logging:

    • Add error tracking (Sentry, LogRocket)
    • Set up application monitoring
    • Implement audit logging for auth events

Performance Optimization

  1. Caching:

    • Implement Redis for session storage
    • Cache static assets
    • Use CDN for global distribution
  2. Database Optimization:

    • Add database indexes
    • Implement query optimization
    • Set up read replicas if needed

Compliance & Security

  1. Data Protection:

    • Implement GDPR compliance features
    • Add data encryption at rest
    • Set up proper data retention policies
  2. Regular Maintenance:

    • Keep dependencies updated
    • Regular security audits
    • Monitor for vulnerabilities

Additional Recommendations

  • Load Testing: Test your application under load before production
  • Backup Strategy: Implement automated backups and disaster recovery
  • Documentation: Maintain deployment and maintenance docs
  • Team Training: Ensure your team understands the security measures

Remember: Security is an ongoing process. Regularly review and update your security measures as new threats emerge.

Learn More

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published