Skip to main content

Authentication Architecture

This document outlines the authentication and authorization architecture for the BuildAppsWith platform, including system design, authentication flows, and implementation details.

Overview

The authentication system for BuildAppsWith uses Clerk as the primary identity provider with standardized middleware patterns for secure, type-safe authentication across the platform. Following comprehensive infrastructure standardization in Session 8 (May 2025), the architecture achieves:

Session 8 Achievement: Complete Infrastructure Standardization

  • AuthObject Pattern: Unified across all authentication middleware
  • Type Safety: 100% TypeScript coverage in authentication layer
  • Middleware Infrastructure: Production-ready and fully standardized
  • API Route Protection: Consistent patterns across entire platform

Architectural Principles

  1. Standardized Authentication Patterns - AuthObject consistency across all middleware
  2. Complete Type Safety - Strong TypeScript typing with zero authentication errors
  3. Infrastructure-First Design - Proven middleware foundation supporting all components
  4. Performance Optimization - Efficient authentication flows with minimal overhead
  5. Security by Design - Industry best practices with comprehensive role-based access control

System Components

The authentication architecture consists of the following components:

1. Authentication Provider

Clerk serves as the authentication provider, handling:
  • User identity management
  • OAuth integrations (Google, GitHub, etc.)
  • Password management and security
  • MFA (Multi-Factor Authentication)
  • Session management

2. Express SDK Integration

The Express SDK provides an abstraction layer over Clerk:
  • Consistent API for auth operations
  • Optimized performance and caching
  • Type-safe interface for authentication
  • Server and client integration

3. Auth API Layer

The auth API layer provides a unified interface for interacting with Clerk through Express SDK:
  • Client-side authentication functions in express/client-auth.ts
  • Server-side authentication checks in express/server-auth.ts
  • Role and permission validation in express/role-hooks.ts
  • Session management in express/middleware.ts

4. Auth Hooks Layer

Custom React hooks provide authentication state and functionality to components:
  • useAuth - Core auth state and user details
  • useAuthStatus - Simple authentication status checks
  • useIsAdmin, useIsBuilder, useIsClient - Role-specific checks
  • useHasRole, useHasAllRoles, useHasAnyRole - Role validation
  • useSignOut - Authentication action hooks
  • useAuthToken - Token management

5. Auth Components Layer

Reusable UI components for authentication flows:
  • ExpressAuthProvider - Auth provider component
  • ProtectedRoute - Component wrapper for protected routes
  • RoleProtected - Component for role-based access control
  • Form components for auth flows

Authentication Flows

Sign-In Flow

Protected Route Flow

Role-Based Access Control

BuildAppsWith implements a role-based access control (RBAC) system with the following roles:
RoleDescriptionCapabilities
USERStandard userAccess personal dashboard, participate in sessions
BUILDERVerified builderCreate builder profile, receive job requests
ADMINPlatform administratorAccess admin dashboard, manage users, view analytics
SUPER_ADMINSuper administratorConfigure platform settings, manage all data

Permission Model

Permissions are derived from roles and implemented through the hasPermission function:
// Check if the current user has a specific permission
const canModerateContent = auth.hasPermission(Permission.MODERATE_CONTENT);

// Require specific permission for an API route
export const POST = requirePermission(
  Permission.MANAGE_USERS,
  async (req, auth) => {
    // Handle user management
  }
);

Authentication for Non-Authenticated Routes

Some routes in BuildAppsWith are designed to work for both authenticated and non-authenticated users. These routes use the getOptionalServerAuth function to provide a seamless experience:
// In a server component or API route
const auth = getOptionalServerAuth();

// Check if user is authenticated without redirecting
if (auth.isAuthenticated) {
  // Show personalized content
} else {
  // Show generic content
}

Implementation Details

Session Storage

Auth sessions are stored using a combination of:
  • HTTP-only cookies for server authentication
  • In-memory state for client-side auth status
  • Local storage for non-sensitive session data

Token Management

Authentication tokens are managed with these considerations:
  • Access tokens have short lifespans (15 minutes)
  • Refresh tokens are used for session persistence
  • Token rotation is implemented for security
  • Tokens are validated on every protected request

Security Measures

The authentication system implements these security measures:
  • CSRF protection on all auth endpoints
  • Rate limiting for authentication attempts
  • Password strength requirements
  • Session timeout and inactivity detection
  • IP-based anomaly detection

Authentication Error Handling

Authentication errors are handled using standardized error codes:
Error CodeDescriptionUser Action
AUTH_REQUIREDAuthentication requiredRedirect to login
INVALID_CREDENTIALSInvalid username/passwordShow error message
SESSION_EXPIREDUser session expiredRe-authenticate
PERMISSION_DENIEDUser lacks permissionShow access denied
ACCOUNT_LOCKEDAccount temporarily lockedContact support

Diagram: Auth System Architecture

Best Practices

When interacting with the auth system, follow these best practices:
  1. Always use typed auth functions - Never create manual auth checks
  2. Handle loading states - Auth checks may be asynchronous
  3. Implement proper error handling - Display user-friendly auth errors
  4. Use the highest-level abstraction available - Prefer hooks over direct API calls
  5. Test with different user roles - Verify permissions work correctly

See Also