Skip to content

Full-stack clean 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/fullstack-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 npm version 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://full-stack-clean-auth-template.vercel.app/
πŸ“š CLI Package: https://www.npmjs.com/package/clean-auth

Application Preview

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

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

Configure Authentication

clean-auth auth-config

Start Development

pnpm dev

Alternative

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

πŸ“₯ Installation Guide

  1. Clone the repository
git clone https://github.com/sinanptm/fullstack-clean-auth-template.git
cd fullstack-clean-auth-template
  1. Install dependencies
pnpm install
  1. Environment Configuration
    Create .env files in both server/ and web/ directories with the required environment variables. You can refer to the .env.example files in each directory for the complete list of required variables.

Start Development

pnpm dev

πŸ› οΈ 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

auth-config - Configure Authentication

Set up environment variables and authentication configuration interactively.

clean-auth auth-config [options]

Options:

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

Examples:

clean-auth auth-config
clean-auth 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
clean-auth --help
clean-auth init --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


πŸ”„ 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

✨ 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

πŸ’» Prerequisites

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

πŸ›οΈ Architecture

Clean Architecture Benefits

  • Separation of Concerns: Each layer has a single responsibility
  • Dependency Inversion: Abstractions don't depend on concrete implementations
  • Testability: Business logic is framework-independent
  • Maintainability: Easy to modify and extend features

πŸ”§ 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

πŸ” Authentication Endpoints
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

πŸ’» 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

We welcome contributions from the community! Here's how you can help:

How to Contribute

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Follow the existing code style and architecture patterns
  4. Add tests for new functionality
  5. Commit your changes (git commit -m 'Add some amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

Development Guidelines

  • Follow the clean architecture principles
  • Write comprehensive tests for new features
  • Update documentation for API changes
  • Use TypeScript for type safety
  • Follow the existing code formatting standards

Reporting Issues

If you find a bug or have a feature request, please open an issue with:

  • Clear description of the problem
  • Steps to reproduce (for bugs)
  • Expected vs actual behavior
  • System information (OS, Node.js version, etc.)

πŸ“„ License

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

What this means:

  • βœ… Commercial Use: Use this code in commercial projects
  • βœ… Modification: Modify the code as needed
  • βœ… Distribution: Share and distribute the code
  • βœ… Private Use: Use for private projects
  • ❗ License Notice: Keep the original license notice

πŸ“ž Support


⭐ Star this repository if it helped you!

GitHub stars

Built with ❀️ for the developer community

About

Full-stack clean 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