Skip to main content
ModernAPI
The ModernAPI Handbook

ModernAPI Template Implementation Guide

Deep dive into our production-ready template architecture. Learn how .NET 9, Clean Architecture, JWT authentication, and React 19 work together in this enterprise-grade solution.

Template Architecture Overview
This template implements enterprise-grade patterns with modern technologies, focusing on maintainability, security, and developer experience.

ModernAPI is a production-ready full-stack template that combines .NET 9 backend with React 19 frontend. It demonstrates real-world implementation of Clean Architecture, JWT authentication, PostgreSQL integration, and modern frontend patterns with TanStack Start.

The template includes comprehensive testing, error handling, security measures, and deployment configurations. You can see it in action through the live demo - sign in and explore the dashboard that fetches real user data from the .NET API backend.

Below you'll find detailed explanations of each architectural component, implementation decisions, and how they work together to create a scalable, maintainable enterprise application.

Implementation Details

Core architectural components and how they're implemented in the ModernAPI template.

I
ModernAPI Architecture Foundation
Our template implements Clean Architecture with 4 distinct layers: API, Application, Infrastructure, and Domain. Each layer has clear responsibilities and dependency rules.

πŸ”§ Implementation

  • ModernAPI.API: Controllers, Middleware, HTTP concerns only
  • ModernAPI.Application: Services, DTOs, Use Cases orchestration
  • ModernAPI.Infrastructure: EF Core, Repositories, External services
  • ModernAPI.Domain: Entities, Value Objects, Business rules

πŸ’‘ Example

User entity extends IdentityUser<Guid> with rich domain methods like UpdateProfile() and ChangeEmail()
II
JWT Authentication & ASP.NET Identity
We integrate ASP.NET Core Identity with JWT tokens for enterprise-grade security. HTTP-only cookies prevent XSS attacks while maintaining seamless user experience.

πŸ”§ Implementation

  • AuthController: Login, Register, Refresh token endpoints
  • JwtTokenService: Access tokens (15min) + Refresh tokens (7 days)
  • RefreshToken entity: Stores refresh tokens with expiry tracking
  • ExceptionMiddleware: Global error handling with RFC 7807 Problem Details

πŸ’‘ Example

User signs in β†’ JWT stored in HTTP-only cookie β†’ Dashboard fetches real user data from API
III
PostgreSQL with Entity Framework Core
PostgreSQL provides robust data storage with EF Core handling migrations, configurations, and queries. All entities use Guid primary keys and snake_case naming.

πŸ”§ Implementation

  • ApplicationDbContext extends IdentityDbContext<User, Role, Guid>
  • Configurations in ModernAPI.Infrastructure/Data/Configurations/
  • Migrations: Code-first with proper Up/Down methods
  • Repository pattern: Generic Repository<T, TId> with specific implementations

πŸ’‘ Example

UserRepository inherits Repository<User, Guid> and adds GetByEmailAsync() method
IV
Modern Frontend with TanStack Start
Our frontend uses TanStack Start with React 19, providing SSR, type safety, and blazing-fast Bun runtime. Server functions handle API communication with proper cookie management.

πŸ”§ Implementation

  • TanStack Router: File-based routing with type-safe navigation
  • Server Functions: BFF layer proxying to .NET API with cookie handling
  • React 19: Latest features with server components
  • Shadcn/ui: Production-ready components with Tailwind CSS

πŸ’‘ Example

loginUser server function handles authentication, sets HTTP-only cookies, then redirects to dashboard
V
Testing Strategy & Implementation
Comprehensive testing across all layers ensures reliability. Domain tests validate business rules, integration tests verify API contracts, and infrastructure tests confirm database operations.

πŸ”§ Implementation

  • ModernAPI.Domain.Tests: Entity behavior and business rule validation
  • ModernAPI.API.Tests: Controller endpoints and middleware testing
  • ModernAPI.Infrastructure.Tests: Repository and database integration tests
  • ModernAPI.IntegrationTests: Full API workflow testing

πŸ’‘ Example

UserTests validates UpdateProfile() domain method, UserRepositoryTests confirms database operations
VI
Configuration & Environment Management
Environment-specific configuration with secure secrets management. PostgreSQL connection strings, JWT settings, and API configurations are externalized and validated at startup.

πŸ”§ Implementation

  • appsettings.json hierarchy: Base β†’ Environment β†’ User secrets
  • JwtSettings with validation: Secret, Issuer, Audience, Expiry times
  • Environment variables: POSTGRES_CONNECTION_STRING, ASPNETCORE_ENVIRONMENT
  • Frontend environment: VITE_API_URL, VITE_ENABLE_DOCS configuration

πŸ’‘ Example

JWT secret minimum 32 characters, validated at startup with clear error messages
VII
Backend-for-Frontend (BFF) Architecture
Our frontend doesn't call the .NET API directly. Instead, TanStack Start server functions act as a BFF layer, handling authentication, cookie management, and API proxying with type safety.

πŸ”§ Implementation

  • TanStack Start Server Functions: Proxy API calls with authentication
  • Cookie Management: Set/extract JWT tokens in HTTP-only cookies
  • Type-Safe API Layer: TypeScript types shared between frontend and BFF
  • Request/Response Transformation: Handle API contracts and error formatting

πŸ’‘ Example

loginUser server function: receives credentials β†’ calls .NET API β†’ sets secure cookies β†’ returns user data
VIII
Domain-Driven Design Implementation
Rich domain entities with business logic, domain events for decoupling, and value objects for data integrity. The User entity demonstrates DDD principles with ASP.NET Identity integration.

πŸ”§ Implementation

  • User Entity: Extends IdentityUser<Guid> with domain methods (UpdateProfile, Deactivate)
  • Domain Events: UserCreatedEvent, UserEmailChangedEvent using record types
  • Business Rules: Validation in domain layer (email format, display name requirements)
  • Repository Interfaces: Domain defines contracts, Infrastructure implements

πŸ’‘ Example

User.UpdateProfile() validates business rules, updates entity state, and raises UserProfileUpdatedEvent
IX
Containerization & Multi-Stage Builds
Docker multi-stage builds for optimized production images. Separate containers for API, PostgreSQL, and Redis with proper networking, health checks, and security configuration.

πŸ”§ Implementation

  • Multi-stage Dockerfile: Build stage (full SDK) β†’ Runtime stage (minimal ASP.NET)
  • Container Security: Non-root user, minimal attack surface, health checks
  • Docker Compose: PostgreSQL 16, Redis 7, with persistent volumes and networking
  • Production Optimized: Self-contained false, diagnostic disabled, proper logging

πŸ’‘ Example

Build: Tests run in container β†’ Publish β†’ Runtime image: 150MB vs 1GB+ with SDK
X
Kubernetes Deployment & Orchestration
Production-ready Kubernetes manifests with ConfigMaps, Secrets, persistent storage, and monitoring. Automated deployment scripts handle rollouts, health checks, and rollbacks.

πŸ”§ Implementation

  • K8s Manifests: Namespace isolation, ConfigMaps for settings, Secrets for credentials
  • Persistent Storage: PostgreSQL StatefulSet with persistent volumes
  • Service Discovery: Internal DNS, load balancing, health check endpoints
  • Deployment Automation: Bash scripts for validation, rollout, and rollback

πŸ’‘ Example

./scripts/deploy-k8s.sh validates cluster β†’ applies manifests β†’ monitors rollout β†’ runs smoke tests
XI
Exception Handling & Observability
Global exception middleware with RFC 7807 Problem Details standard, structured logging with Serilog, and comprehensive monitoring setup for production observability.

πŸ”§ Implementation

  • ExceptionMiddleware: Catches all exceptions β†’ structured logging β†’ RFC 7807 responses
  • Serilog Configuration: Structured JSON logs with correlation IDs and context
  • Health Checks: Database connectivity, external services, custom health endpoints
  • Monitoring Stack: Prometheus metrics, Grafana dashboards, log aggregation

πŸ’‘ Example

Unhandled exception β†’ logged with request ID β†’ client gets consistent error format β†’ monitoring alerts fired
XII
Development Workflow & CI/CD
Automated deployment pipeline with testing, containerization, and progressive rollouts. Development environment matches production using Docker Compose for consistency.

πŸ”§ Implementation

  • Local Development: Docker Compose with hot reload, database migrations, Redis caching
  • CI Pipeline: Build β†’ Test β†’ Security Scan β†’ Container Build β†’ Push to Registry
  • CD Pipeline: Deploy to staging β†’ run integration tests β†’ promote to production
  • Infrastructure as Code: Kubernetes manifests, Terraform for cloud resources

πŸ’‘ Example

git push β†’ GitHub Actions β†’ tests pass β†’ Docker build β†’ K8s deploy β†’ health check β†’ rollout complete

Technology Stack

Carefully chosen technologies that embody our principles and enable rapid, reliable development.

Backend Foundation
.NET 9
Latest LTS runtime with performance improvements
ASP.NET Core
High-performance web framework
Entity Framework Core
Modern ORM with LINQ support
PostgreSQL
Robust, standards-compliant database
Architecture Patterns
Clean Architecture
Domain-centric design with clear boundaries
Domain-Driven Design
Rich domain models with business logic
CQRS Inspiration
Separate read and write concerns
Repository Pattern
Abstract data access behind interfaces
Security & Auth
JWT Tokens
Stateless authentication with claims
HTTP-only Cookies
Secure refresh token storage
ASP.NET Identity
User management with extensible User entity
Rate Limiting
Prevent abuse and ensure fair usage
Testing Strategy
Domain Tests
Verify business logic and rules
Integration Tests
Test API endpoints with real database
FluentAssertions
Readable test assertions
Test Data Builders
Create realistic test scenarios
Developer Experience
Scalar UI
Modern OpenAPI documentation
Serilog
Structured logging with rich context
AutoMapper
Object mapping between layers
FluentValidation
Expressive input validation
Frontend Modern Stack
TanStack Start
Full-stack React with SSR and Server Functions (BFF)
React 19
Latest React with Server Components
Bun Runtime
Fast JavaScript runtime and bundler
Shadcn/ui
Beautiful, accessible component library
Containerization & Deployment
Docker Multi-stage
Optimized production container builds
PostgreSQL 16
Robust database with persistent storage
Redis 7
Caching and session storage
Kubernetes
Container orchestration and scaling
Observability & Monitoring
Serilog
Structured logging with rich context
Health Checks
Application and infrastructure monitoring
RFC 7807
Standardized API error responses
Correlation IDs
Request tracing across services

Container Architecture & Deployment

How our containers interact and the automated deployment pipeline from development to production.

Container Interaction
How our multi-container architecture communicates
πŸš€ ModernAPI (.NET 9)
β€’ Port 8080 (internal), exposed via load balancer
β€’ Connects to PostgreSQL on port 5432
β€’ Uses Redis for caching on port 6379
β€’ Health check: /health endpoint
πŸ—„οΈ PostgreSQL 16
β€’ Persistent volume for data storage
β€’ StatefulSet for ordered deployment
β€’ Automated backups and migrations
β€’ Connection pooling and monitoring
⚑ Redis 7
β€’ Session storage and API response caching
β€’ LRU eviction policy, 256MB memory limit
β€’ Persistent storage for session continuity
β€’ Password authentication enabled
Deployment Pipeline
Automated deployment from git push to production
1
Code Push & CI
git push β†’ GitHub Actions β†’ run tests
2
Container Build
Multi-stage Docker build β†’ push to registry
3
K8s Deployment
deploy-k8s.sh β†’ rolling update β†’ health checks
4
Validation
Smoke tests β†’ monitoring β†’ auto-rollback if needed
Backend-for-Frontend (BFF) Data Flow
How TanStack Start Server Functions bridge the frontend and .NET API
React 19 UI
Dashboard, Forms
TanStack Start
Server Functions (BFF)
.NET 9 API
Clean Architecture
Example: User Authentication Flow
1. React form calls loginUser() server function
2. Server function validates input, calls .NET /api/auth/login
3. .NET API validates credentials, returns JWT tokens
4. Server function sets HTTP-only cookies, returns user data
5. React redirects to dashboard, subsequent calls use cookies
Putting Principles into Practice
How to apply these principles in your daily development work

Start Here

  • Write domain tests to understand business requirements
  • Model your domain entities with rich behavior
  • Create repository interfaces in the domain layer
  • Implement infrastructure that adapts to domain needs

As You Scale

  • Add comprehensive logging and monitoring
  • Implement proper caching and performance optimization
  • Set up automated deployment pipelines
  • Document architectural decisions with ADRs

Remember: Principles Over Practices

These principles are more important than any specific technology or framework. They should guide your decisions whether you're building with .NET, Node.js, or any other platform. The ModernAPI template is one implementationβ€”the principles are universal.

The Journey Continues

These twelve principles are not a destinationβ€”they're a compass for the journey of continuous improvement. Every codebase, every team, and every project will find its own path guided by these fundamental truths.

"The best architectures, requirements, and designs emerge from self-organizing teams that understand and apply sound principles."

β€” Adapted from the Agile Manifesto