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.
- 🔐 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
- 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
This guide will help you set up the project from scratch. Follow these steps carefully to get the application running locally.
- 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.)
git clone <repository-url>
cd better-auth-mongodbnpm install-
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)
-
Start MySQL:
# Windows (as Administrator) net start MySQL # macOS with Homebrew brew services start mysql # Linux sudo systemctl start mysql
-
Create a database:
mysql -u root -p CREATE DATABASE better_auth; EXIT;
-
Verify MySQL is running:
mysql --version
- Create an account with your preferred MySQL provider
- Create a new database instance
- Get your connection details (host, user, password, database name)
-
Copy the example file:
cp .env.example .env.local
-
Edit
.env.localwith 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
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 32Option 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.
- Go to GitHub Settings > Developer settings > OAuth Apps
- Click "New OAuth App"
- 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
- Click "Register application"
- Copy the Client ID and Client Secret to your
.env.localfile
npm run devOpen http://localhost:3000 in your browser.
- Visit the homepage - you should see the welcome page
- Click "Sign Up" and create an account
- Try logging in with email/password or GitHub
- Access the todos page to test CRUD operations
- MySQL connection issues: Ensure MySQL is running and the credentials are correct
- Auth errors: Double-check your
BETTER_AUTH_SECRETand 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)
- Explore the code structure in the Project Structure section
- Learn about the Authentication Flow
- Check out the API Routes and MongoDB schema
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
- Landing Page: Welcome screen that redirects authenticated users to todos
- Registration/Login: Forms with validation and error handling
- Todo Dashboard: Protected route at
/todoswith user profile and todo management - Session Management: Automatic session handling with Better Auth and middleware protection
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 todoscreateTodo()- Create new todoupdateTodo()- Update tododeleteTodo()- Delete todo
The app uses Better Auth's automatic table creation for users and sessions, plus custom tables for todos with proper user relationships.
npm run dev- Start development server with Turbopacknpm run build- Build for productionnpm run start- Start production servernpm run lint- Run ESLint
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.
-
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' }, ], }, ], }
-
Environment Variables:
- Use different secrets for each environment
- Store secrets in secure vaults (AWS Secrets Manager, etc.)
- Never commit
.envfiles
-
Rate Limiting:
- Implement rate limiting for auth endpoints
- Consider using services like Cloudflare or AWS WAF
-
Database:
- Use managed MySQL (AWS RDS, PlanetScale, Google Cloud SQL)
- Set up automated backups
- Configure connection pooling properly
- Enable SSL connections
-
Deployment:
- Use platforms like Vercel, Netlify, or AWS
- Set up CI/CD pipelines
- Implement health checks
- Configure monitoring
-
Monitoring & Logging:
- Add error tracking (Sentry, LogRocket)
- Set up application monitoring
- Implement audit logging for auth events
-
Caching:
- Implement Redis for session storage
- Cache static assets
- Use CDN for global distribution
-
Database Optimization:
- Add database indexes
- Implement query optimization
- Set up read replicas if needed
-
Data Protection:
- Implement GDPR compliance features
- Add data encryption at rest
- Set up proper data retention policies
-
Regular Maintenance:
- Keep dependencies updated
- Regular security audits
- Monitor for vulnerabilities
- 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.