Skip to content

Full-stack clean architecture, authentication template with Next.js, NodeJs, TypeScript. Features email/OTP, OAuth, RBAC, JWT security, and clean architecture for easy customization and scaling.

License

Notifications You must be signed in to change notification settings

sinanptm/clean-auth-template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Full-Stack Authentication Template

A production-ready authentication system built with clean architecture principles and modern technologies

License: MIT Node.js Version TypeScript Downloads PRs Welcome


πŸ“– Overview

This comprehensive full-stack authentication template is designed with clean architecture principles, providing a solid foundation for building scalable web applications with robust user authentication and authorization systems.

πŸ“š Documentation: https://clean-auth-template.vercel.app
πŸ› οΈ CLI Tool: https://npmjs.com/package/clean-auth

Application Preview Dark Application Preview Light

The template demonstrates modern web development practices with a focus on security, scalability, and maintainability. It includes comprehensive authentication flows, role-based access control, and production-ready deployment configurations.


πŸš€ Quick Start with CLI

The fastest way to get started is using our CLI tool:

Install the CLI

npm install -g clean-auth

Create a New Project

# OR Use npx (Without Installing Globally)
# Run commands without installing the CLI globally
npx clean-auth init my-auth-project --i
cd my-auth-project

Configure Authentication

clean-auth config [options]

Start Development

pnpm dev

Alternative

If you prefer to set up the project manually without using CLI:

Clone the repository

git clone https://github.com/sinanptm/fullstack-clean-auth-template.git
cd fullstack-clean-auth-template

Install dependencies

pnpm install

Start Development

pnpm dev

πŸ’» Prerequisites

  • Node.js v20 or higher
  • pnpm v10.8.1 or higher
  • MongoDB (local installation or MongoDB Atlas)
  • Firebase project with Authentication enabled

πŸ› οΈ CLI Commands

The clean-auth CLI provides powerful commands to scaffold and manage your authentication project:

init - Initialize Project

Create a new full-stack authentication project with clean architecture.

clean-auth init <project-name> [options]

Options:

  • -i, --install - Automatically install dependencies after project creation

Examples:

clean-auth init my-auth-project
clean-auth init my-auth-project --install

config - Configure Authentication

Set up environment variables and authentication configuration interactively.

clean-auth config [options]

Options:

  • -s, --skip - Skip interactive prompts and use default values

Examples:

clean-auth config
clean-auth config --skip

clean - Clean Project Structure

Remove unnecessary parts of your project structure to customize it for your needs.

clean-auth clean [options]

Options:

  • -s, --server - Remove entire server directory and update root configurations
  • -w, --web - Remove entire web directory and update root configurations
  • -o, --opensource - Remove open source files (LICENSE, CONTRIBUTING.md, README.md)

Examples:

clean-auth clean --server
clean-auth clean --web --opensource

help - Show All Commands

Display a list of all available commands.

clean-auth help

πŸ“± Application Screenshots

Authentication Flow

User Registration User Signup Page

Forgot Password Modal Forgot Password Popup

Password Reset Email Forgot Password Email

OTP Verification OTP Verification Page

OTP Email Verification OTP Verification Email

User & Admin Interfaces

User Profile Dashboard User Profile Page

Admin Login Admin Signin Page

Admin Dashboard Admin Dashboard


✨ Key Features

πŸ—οΈ Architecture & Design

  • Clean Architecture - Domain-driven design with clear separation of concerns
  • Modular Structure - Easy to extend and maintain
  • Framework Independence - Core business logic is decoupled from frameworks
  • TypeScript First - Full type safety across the entire stack

πŸ” Authentication & Security

  • Multi-factor Authentication - Email/Password with OTP verification
  • OAuth Integration - Google and GitHub social login
  • Role-based Access Control - User and admin roles with protected routes
  • JWT Token Management - Secure access and refresh token implementation
  • Security Best Practices - Rate limiting, CORS, bcrypt hashing

⚑ Modern Technology Stack

  • Frontend: Next.js 15, React 19, Tailwind CSS, Shadcn UI
  • Backend: Express.js 5, Node.js, TypeScript
  • Database: MongoDB with Mongoose ODM
  • State Management: Zustand + React Query
  • Authentication: Firebase OAuth, JWT, Nodemailer

πŸš€ Production Ready

  • Scalable Architecture - Built for enterprise-level applications
  • Comprehensive Testing - Unit and integration tests included
  • Development Tools - ESLint, Prettier, Hot reload
  • Deployment Ready - Production-optimized builds
  • CI/CD Pipeline - Automated testing, building, and quality checks

πŸ”§ CI/CD Pipeline

πŸ”„ Automated Workflows

  • Continuous Integration - Automated testing and building on every push
  • Quality Assurance - Code formatting, linting, and type checking
  • Security Auditing - Weekly dependency vulnerability scans
  • Dependency Management - Automated dependency updates with PR creation

GitHub Actions Workflows

Workflow Trigger Purpose
CI/CD Pipeline Push to main/develop, PRs Build, test, and quality checks
Security Audit Weekly schedule, Push/PR Vulnerability scanning
Update Dependencies Weekly schedule, Manual Automated dependency updates

Pipeline Features

  • Parallel Execution - Server and web builds run simultaneously
  • Caching Strategy - Optimized build times with dependency caching
  • Artifact Management - Build artifacts stored for deployment
  • Multi-stage Validation - Tests, linting, and type checking

πŸ“š API Documentation
Method Endpoint Description Body
POST /api/auth/signup User registration { email, password, name }
POST /api/auth/signin Email/password login { email, password }
POST /api/auth/verify-otp Verify OTP code { email, otp }
POST /api/auth/oauth-2 OAuth authentication { firebaseToken }
POST /api/auth/forgot-password Request password reset { email }
POST /api/auth/reset-password Reset password with OTP { email, otp, newPassword }
POST /api/auth/refresh Refresh access token { refreshToken }
POST /api/auth/logout User logout -

πŸ‘€ User Endpoints

Method Endpoint Description Auth Required
GET /api/user/profile Get user profile βœ… User
PUT /api/user/profile Update user profile βœ… User

πŸ‘‘ Admin Endpoints

Method Endpoint Description Auth Required
POST /api/admin/signin Admin login -
GET /api/admin/users List all users βœ… Admin
GET /api/admin/users/:id Get specific user βœ… Admin
PUT /api/admin/users/:id Update user βœ… Admin
DELETE /api/admin/users/:id Delete user βœ… Admin
GET /api/admin/analytics System analytics βœ… Admin

πŸ”’ Security Features

πŸ” Authentication Security

  • JWT Tokens: Secure access and refresh token implementation
  • HTTP-Only Cookies: Protection against XSS attacks
  • Password Hashing: bcrypt with 10 salt rounds
  • OTP Verification: Time-limited one-time passwords

πŸ›‘οΈ Authorization & Access Control

  • Role-Based Access Control (RBAC): User and admin roles
  • Protected Routes: Middleware-based route protection
  • Token Validation: Server-side Firebase token verification

🚫 Attack Prevention

  • Rate Limiting: Request throttling to prevent abuse
  • CORS Configuration: Cross-origin request security
  • Input Validation: Comprehensive Joi schema validation
  • SQL Injection Prevention: Parameterized database queries

πŸ” Monitoring & Logging

  • Request Logging: Detailed API request logging
  • Error Tracking: Comprehensive error handling
  • Security Headers: Helmet.js security headers

πŸ”„ Authentication Flow Diagram
graph TB
    %% Entry Point
    A["πŸ”‘ Sign In/Up Page"] --> B{"Authentication Method"}

    %% Email/Password Flow
    B -->|"πŸ“§ Email/Password"| C["πŸ“ Enter Credentials"]
    C --> D{"Valid Credentials?"}
    D -->|"❌"| E["❌ Error Message"]
    E --> C
    D -->|"βœ…"| F["πŸ”’ Generate OTP"]
    F --> G["πŸ“§ Send OTP Email"]
    G --> H["πŸ”’ OTP Verification Page"]
    H --> I["Enter OTP Code"]
    I --> J{"Valid & Fresh OTP?"}
    J -->|"❌"| K["Try Again"]
    K --> I
    J -->|"βœ…"| L["🎯 Generate JWT"]

    %% OAuth Flow
    B -->|"πŸ”₯ OAuth (Google/GitHub)"| M["πŸ”₯ Firebase OAuth Popup"]
    M --> N["πŸ‘€ Select Provider"]
    N --> O["πŸ” Provider Authentication"]
    O --> P{"Auth Success?"}
    P -->|"❌"| Q["❌ OAuth Error"]
    Q --> A
    P -->|"βœ…"| R["🎯 Get Firebase Token"]
    R --> S["πŸ“§ Extract User Info"]
    S --> T["πŸ”— Send Token to Backend"]
    T --> U["πŸ” Validate Firebase Token"]
    U --> V{"Token Valid?"}
    V -->|"❌"| W["❌ Token Invalid"]
    W --> A
    V -->|"βœ…"| X{"User Exists?"}
    X -->|"❌"| Y["πŸ‘€ Create New User"]
    X -->|"βœ…"| Z["πŸ“ Update User Info"]
    Y --> L
    Z --> L

    %% Common Final Steps
    L --> AA["πŸͺ Set HTTP-Only Cookies"]
    AA --> BB["✨ Authenticated User"]
    BB --> CC["πŸ›‘οΈ User Dashboard Access"]

    %% Additional Flows
    DD["πŸ”„ Token Expiry"] --> EE["πŸ”„ Auto Refresh"]
    EE --> BB

    FF["πŸ”’ Forgot Password"] --> GG["πŸ“§ Reset Email with OTP"]
    GG --> HH["πŸ”’ OTP Verification"]
    HH --> II["πŸ”‘ New Password"]
    II --> A

    %% Admin Flow (Separate)
    JJ["πŸ”’ Admin Login"] --> KK["πŸ“§ Admin Credentials"]
    KK --> LL["πŸ” Validate with .env"]
    LL --> MM{"Match Admin Config?"}
    MM -->|"❌"| NN["❌ Access Denied"]
    NN --> JJ
    MM -->|"βœ…"| OO["🎯 Generate Admin JWT"]
    OO --> PP["🏷️ Set Admin Role"]
    PP --> QQ["πŸͺ Set Admin Cookies"]
    QQ --> RR["✨ Authenticated Admin"]
    RR --> SS["πŸ‘‘ Admin Panel Access"]
Loading

πŸ’» Development

Available Scripts

Root Level

pnpm dev          # Start both frontend and backend
pnpm format       # Format code using Prettier
pnpm lint         # Lint entire project

Backend (server/)

pnpm dev          # Start development server with hot reload
pnpm build        # Build for production
pnpm start        # Start production server
pnpm test         # Run test suite

Frontend (web/)

pnpm dev          # Start Next.js development server
pnpm build        # Build for production
pnpm start        # Start production server
pnpm lint         # Lint frontend code

🀝 Contributing

Contributing Guidelines

πŸ“„ License

This project is licensed under the MIT License – see the LICENSE file for details.

⭐ Star this repository if it helped you!

GitHub stars

Built with ❀️ for the developer community

About

Full-stack clean architecture, authentication template with Next.js, NodeJs, TypeScript. Features email/OTP, OAuth, RBAC, JWT security, and clean architecture for easy customization and scaling.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published