Skip to main content

Backend Only Package

The Backend Package is a robust NestJS backend providing secure authentication, user management, email services, and comprehensive APIs for full-stack applications.

Tech Stack

CategoryTechnology
FrameworkNestJS 11
LanguageTypeScript 5
DatabasePostgreSQL 14+
ORMPrisma
CacheRedis 7+
EmailNodemailer + Handlebars
TestingJest
ContainerizationDocker

Module Architecture

Key Modules

Auth Module

Complete authentication system with enterprise-grade security:

// Example: User registration with email verification
@Post('register')
async register(@Body() dto: RegisterDto) {
return this.authService.register(dto);
}

Features:

  • User registration with email verification
  • JWT-based login with access/refresh tokens
  • Multi-Factor Authentication (MFA/TOTP)
  • Password reset and recovery
  • Session management with Redis
  • Rate limiting for brute-force protection

User Module

User profile management with comprehensive CRUD operations:

Endpoints:

  • GET /user/profile - Get user profile
  • PUT /user/profile - Update profile
  • POST /user/change-password - Change password
  • POST /user/delete-account - Request account deletion

Admin Module

Administrative capabilities for system management:

Features:

  • User management (list, update, disable, delete)
  • Session management (view, revoke, revoke all)
  • User impersonation (admin can impersonate users)
  • Audit logging and monitoring
  • Email log viewing

Email Module

Queue-based email processing with Bull:

Features:

  • Queue-based email processing with Bull
  • Handlebars templates for customization
  • Retry logic with exponential backoff
  • Email delivery logging

CAPTCHA Module

Bot protection with multiple providers:

  • Google reCAPTCHA v2 support
  • Cloudflare Turnstile support
  • hCaptcha support
  • Per-provider configuration

AI Module

Multi-provider AI integration — fully optional, zero-config by default:

  • Providers: Anthropic (Claude), OpenAI, Google Gemini, Groq
  • Auto-detected from .env API keys — missing keys disable that provider gracefully
  • REST endpoints: GET /ai/providers, POST /ai/chat, POST /ai/stream (SSE)
  • Extensible via the IAIProvider interface — add any provider in 5 steps
  • Use AIService from other NestJS modules by importing AIModule
// Inject AI into your own service
import { AIModule } from '../ai/ai.module';
import { AIService } from '../ai/ai.service';

@Module({ imports: [AIModule] })
export class YourModule {}

// In your service
const result = await this.aiService.chat('anthropic', messages, { maxTokens: 512 });

See AI Integrations Guide for full documentation.

Health Module

System monitoring with health checks:

  • Application health checks
  • Database connectivity verification
  • Redis connectivity verification
  • Readiness and liveness probes

Project Structure

backend/
├── src/
│ ├── modules/
│ │ ├── auth/ # Authentication module
│ │ │ ├── controllers/ # Auth endpoints
│ │ │ ├── services/ # Auth business logic
│ │ │ ├── guards/ # Auth guards
│ │ │ └── dto/ # Data transfer objects
│ │ ├── user/ # User management
│ │ ├── admin/ # Admin panel module
│ │ ├── ai/ # AI module (multi-provider)
│ │ │ ├── ai.controller.ts
│ │ │ ├── ai.service.ts
│ │ │ ├── ai.module.ts
│ │ │ ├── interfaces/ # IAIProvider, AIMessage types
│ │ │ └── providers/ # anthropic, openai, gemini, groq services
│ │ ├── email/ # Email service
│ │ ├── captcha/ # CAPTCHA verification
│ │ └── health/ # Health checks
│ ├── common/
│ │ └── prisma.service.ts # Prisma client
│ ├── config/ # Configuration module
│ ├── templates/
│ │ └── emails/ # Email templates
│ └── main.ts # Application entry
├── prisma/
│ ├── schema.prisma # Database schema
│ └── migrations/ # Database migrations
├── vibe-templates/
│ └── feature-module/ # NestJS CRUD module scaffold
│ └── GUIDE.md # Step-by-step instructions
├── .context/ # AI agent context docs
│ ├── README.md
│ ├── OVERVIEW.md
│ ├── ARCHITECTURE.md
│ ├── MODULES.md
│ ├── CONVENTIONS.md
│ └── AI-INTEGRATIONS.md
├── scripts/ # Utility scripts
├── certs/ # SSL certificates
├── nginx/ # NGINX configuration
└── docker-compose.yml # Docker orchestration

API Endpoints

Authentication

EndpointMethodDescription
/auth/registerPOSTRegister new user
/auth/loginPOSTUser login
/auth/verify-emailPOSTVerify email
/auth/forgot-passwordPOSTRequest password reset
/auth/reset-passwordPOSTReset password
/auth/setup-totpPOSTSetup TOTP MFA
/auth/verify-mfaPOSTVerify MFA code
/auth/refreshPOSTRefresh access token
/auth/logoutPOSTUser logout

User Management

EndpointMethodDescription
/user/profileGETGet user profile
/user/profilePUTUpdate profile
/user/change-passwordPOSTChange password
/user/delete-accountPOSTRequest account deletion

Admin Panel

EndpointMethodDescription
/admin/usersGETList users with pagination
/admin/users/:idPUTUpdate user
/admin/users/:idDELETEDelete user
/admin/users/:id/sessionsGETList user sessions
/admin/users/:id/sessionsDELETERevoke all sessions
/admin/audit-logsGETList audit logs
/admin/email-logsGETList email logs
/admin/impersonate/:userIdPOSTStart impersonation

AI

EndpointMethodAuthDescription
/ai/providersGETRequiredList configured providers
/ai/chatPOSTRequiredFull AI completion
/ai/streamPOSTRequiredSSE streaming completion

Quick Start

Installation

# Navigate to backend directory
cd projects/fss/backend

# Install dependencies
npm install

# Set up environment variables
cp .env.example .env

# Configure your .env file

# Run database migrations
npx prisma migrate dev

# Generate Prisma client
npx prisma generate

# Start development server
npm run start:dev

Docker Deployment

# Build and start containers
docker-compose up -d

# View logs
docker-compose logs -f backend

Configuration

Environment Variables

# Database
DATABASE_URL="postgresql://user:password@localhost:5432/fss"

# Redis
REDIS_HOST="localhost"
REDIS_PORT=6379

# JWT
JWT_SECRET="your-secret-key"
JWT_EXPIRES_IN="15m"
JWT_REFRESH_SECRET="your-refresh-secret"
JWT_REFRESH_EXPIRES_IN="7d"

# Email
SMTP_HOST="smtp.example.com"
SMTP_PORT=587
SMTP_USER="your-email"
SMTP_PASSWORD="your-password"

# CAPTCHA
RECAPTCHA_SECRET_KEY="your-secret"
RECAPTCHA_SITE_KEY="your-site-key"

Security Features

✅ JWT token management with automatic refresh ✅ Multi-Factor Authentication (MFA) with TOTP ✅ Rate limiting on all endpoints ✅ Input validation with class-validator ✅ SQL injection prevention with Prisma ✅ XSS protection with Helmet ✅ CSRF protection ✅ Content Security Policy (CSP) ✅ Audit logging for all security events

Vibe Templates

The backend ships with a vibe-templates/feature-module/ directory containing a complete, working NestJS CRUD module (Notes as the example). Use it to scaffold any new feature in minutes:

# 1. Copy the template
cp -r vibe-templates/feature-module src/modules/tasks

# 2. Rename: notes → tasks, Notes → Tasks, Note → Task, note → task

# 3. Add the Prisma model and run migration
npx prisma migrate dev --name add_tasks

# 4. Register in app.module.ts
# import { TasksModule } from './modules/tasks/tasks.module';
# imports: [..., TasksModule]

See Vibe Templates Guide for full details.

.context Directory

The backend includes a .context/ folder that gives AI coding agents (Claude Code, Cursor, Copilot Workspace) an instant overview of the codebase:

FileContents
OVERVIEW.mdTech stack, ports, how to run
ARCHITECTURE.mdModule map, DB schema, auth flow
MODULES.mdEvery module — purpose and patterns
AI-INTEGRATIONS.mdAI module endpoints and extension guide
CONVENTIONS.mdNaming, patterns, code style rules

Next Steps