Package Exports
- @voilajsx/appkit
- @voilajsx/appkit/auth
- @voilajsx/appkit/cache
- @voilajsx/appkit/config
- @voilajsx/appkit/database
- @voilajsx/appkit/email
- @voilajsx/appkit/error
- @voilajsx/appkit/logger
- @voilajsx/appkit/queue
- @voilajsx/appkit/security
- @voilajsx/appkit/storage
- @voilajsx/appkit/util
Readme
VoilaJSX AppKit ๐
Minimal and framework agnostic Node.js toolkit designed for AI agentic backend development
Zero configuration. Enterprise features by default. Optimized for both human developers and AI code generation.
๐ What VoilaJSX AppKit Really Is
VoilaJSX AppKit is a complete Node.js development toolkit that eliminates the complexity of building production-ready applications. Instead of juggling dozens of libraries and configuration files, you get 12 integrated modules that work together seamlessly.
How Developers Can Leverage AppKit
๐ฏ For Rapid Development
- One function per module:
authClass.get()
,databaseClass.get()
,securityClass.get()
- Instant setup: No configuration files, just environment variables
- Production patterns: Enterprise-grade security and scalability built-in
๐๏ธ For Maintainable Architecture
- Consistent APIs: Same
{moduleClass}.get()
pattern across all modules - Progressive complexity: Start simple, scale to enterprise automatically
- Type-safe: Full TypeScript support with intelligent IntelliSense
โก For Performance
- Smart defaults: Memory caching, connection pooling, resource management
- Auto-scaling: Modules automatically upgrade (Memory โ Redis โ Database)
- Optimized: Battle-tested patterns for high-throughput applications
๐ค Enhanced for AI-Driven Development
While perfectly designed for human developers, AppKit excels in AI-assisted development:
- ๐ฏ Predictable Code Generation: AI agents generate consistent, working applications
- ๐ LLM-Optimized Documentation: Every function includes clear usage patterns
- ๐ Built-in Best Practices: Security, scalability, and maintainability by default
- โ๏ธ Non-Ambiguous APIs: Clear function signatures prevent common mistakes
Why This Matters for Developers
Traditional Approach | VoilaJSX AppKit Approach |
---|---|
Research โ Configure โ Integrate โ Secure | Import โ Use โ Deploy |
Multiple libraries, version conflicts | Integrated modules, tested together |
Manual scaling decisions | Environment-driven auto-scaling |
Security implemented later | Security enabled by default |
Inconsistent error handling | Unified error patterns |
๐ข Enterprise Benefits
Progressive Complexity
// Day 1: Simple development
const auth = authClass.get();
const token = auth.signToken({ userId: 123, role: 'user', level: 'basic' });
// Month 6: Multi-tenant (just add environment variable)
// VOILA_DB_TENANT=auto
const database = await databaseClass.get(); // Now auto-filtered by tenant
// Year 1: Multi-organization enterprise (same code)
// ORG_ACME=postgresql://acme.aws.com/prod
const acmeDatabase = await databaseClass.org('acme').get(); // Enterprise scaling
๐ Quick Start
Two Ways to Use AppKit:
๐ฆ As a Library - Install AppKit modules into your existing Node.js/Express projects (NestJS, Fastify, Koa, etc.):
npm install @voilajsx/appkit
Import modules directly: import { authClass, databaseClass } from '@voilajsx/appkit'
๐ Complete Microservice Scaffolding - Use AppKit CLI to generate enterprise-ready backend applications:
# Step 1: Install AppKit CLI globally
npm install -g @voilajsx/appkit
# Check if you have the latest version
npm list -g @voilajsx/appkit
# Step 2: Create your app
appkit generate app myproject
cd myproject && npm run dev:api
Done. Your API is running with authentication, database, and enterprise features ready at http://localhost:3000/api
Add Features Instantly
# Add custom feature
appkit generate feature product
# Add complete authentication system
appkit generate feature user
# Add database-enabled feature
appkit generate feature order --db
Library Integration Example
# For library usage in existing projects
npm install @voilajsx/appkit
import { authClass } from '@voilajsx/appkit/auth';
import { databaseClass } from '@voilajsx/appkit/database';
import { errorClass } from '@voilajsx/appkit/error';
import { loggerClass } from '@voilajsx/appkit/logger';
const auth = authClass.get();
const database = await databaseClass.get();
const error = errorClass.get();
const logger = loggerClass.get('api');
// Protected API endpoint
app.post(
'/api/users',
auth.requireRole('admin.tenant'),
error.asyncRoute(async (req, res) => {
const user = auth.user(req);
if (!req.body.email) {
throw error.badRequest('Email required');
}
const newUser = await database.user.create({ data: req.body });
logger.info('User created', { userId: newUser.id });
res.json({ user: newUser });
})
);
// Error handling middleware (must be last)
app.use(error.handleErrors());
Result: Production-ready API with authentication, database, error handling, and logging. Zero configuration needed.
๐ ๏ธ AppKit CLI
Project Generation
# Create complete backend application
appkit generate app [name]
# What you get:
# โ
TypeScript setup with proper configuration
# โ
Express server with auto-discovery routing
# โ
Environment variables with secure random keys
# โ
Database integration ready
# โ
Complete documentation included
# โ
Production-ready npm scripts
Feature Generation
# Basic feature (route + service + types)
appkit generate feature product
# Database-enabled feature (+ model + HTTP tests)
appkit generate feature order --db
# Complete authentication system (9-role hierarchy)
appkit generate feature user
Generated Project Structure
myproject/
โโโ docs/ # Complete documentation
โ โโโ APPKIT_CLI.md # CLI reference
โ โโโ APPKIT_LLM_GUIDE.md # AI integration guide
โ โโโ APPKIT_COMMENTS_GUIDELINES.md # Code standards
โโโ src/api/
โ โโโ server.ts # Main server
โ โโโ lib/api-router.ts # Auto-discovery routing
โ โโโ features/ # Feature-based architecture
โ โโโ welcome/ # Default endpoints
โ โโโ [your-features]/ # Generated features
โโโ .env # Secure environment variables
โโโ package.json # With backend scripts
โโโ README.md # Project-specific guide
๐ญ Complete Module Ecosystem
# | Module | Category | Purpose | Details |
---|---|---|---|---|
1 | Auth | ๐ง Infrastructure | JWT tokens, dual token system, role-level permissions | authClass.get() - Login tokens (users) + API tokens (services), role.level hierarchy (user.basic โ admin.system), automatic inheritance |
2 | Database | ๐ง Infrastructure | Multi-tenant, progressive scaling | databaseClass.get() - Auto-tenant filtering, org management (.org()), mandatory future-proofing with tenant_id |
3 | Security | ๐ง Infrastructure | CSRF, rate limiting, encryption | securityClass.get() - Enterprise-grade by default, AES-256-GCM encryption, input sanitization |
4 | Error | ๐ง Infrastructure | HTTP status codes, semantic errors | errorClass.get() - Framework-agnostic middleware, semantic error types (badRequest, unauthorized) |
5 | Cache | ๐ Data & Communication | Memory โ Redis auto-scaling | cacheClass.get('namespace') - Namespace isolation, TTL management, getOrSet pattern |
6 | Storage | ๐ Data & Communication | Local โ S3/R2 auto-scaling | storageClass.get() - CDN integration, signed URLs, automatic provider detection |
7 | Queue | ๐ Data & Communication | Memory โ Redis โ DB scaling | queueClass.get() - Background jobs, scheduling, retry logic with exponential backoff |
8 | ๐ Data & Communication | Console โ SMTP โ Resend | emailClass.get() - Templates, multi-provider, automatic strategy selection |
|
9 | Event | ๐ Data & Communication | Memory โ Redis distribution | eventClass.get('namespace') - Real-time, pub/sub, wildcard patterns (user.*) |
10 | Util | ๐ ๏ธ Developer Experience | 12 essential utilities | utilClass.get() - Safe property access (get), performance helpers (debounce, chunk) |
11 | Config | ๐ ๏ธ Developer Experience | Environment variables | configClass.get() - Type-safe, UPPER_SNAKE_CASE convention, validation included |
12 | Logger | ๐ ๏ธ Developer Experience | Structured logging | loggerClass.get('component') - Multi-transport, auto-scaling (Console โ File โ HTTP) |
Category Summary
- ๐ง Infrastructure (4 modules): Core application foundation - auth, database, security, error handling
- ๐ Data & Communication (5 modules): Data flow and external interactions - cache, storage, queue, email, events
- ๐ ๏ธ Developer Experience (3 modules): Development productivity - utilities, configuration, logging
๐ Environment-Driven Progressive Scaling
Development (Zero Configuration)
npm start # Memory cache, local storage, console logs
Production (Auto-Detection)
# Set these environment variables - everything scales automatically
DATABASE_URL=postgresql://prod-db/app # โ Database persistence
REDIS_URL=redis://prod-cache:6379 # โ Distributed cache/queue
AWS_S3_BUCKET=prod-assets # โ Cloud storage + CDN
RESEND_API_KEY=re_production_key # โ Professional email
VOILA_DB_TENANT=auto # โ Multi-tenant mode
Same code. Different environment. Enterprise features automatically enabled.
๐ข Enterprise-Ready Examples
Multi-Tenant SaaS API
import { authClass } from '@voilajsx/appkit/auth';
import { databaseClass } from '@voilajsx/appkit/database';
import { securityClass } from '@voilajsx/appkit/security';
import { cacheClass } from '@voilajsx/appkit/cache';
const auth = authClass.get();
const database = await databaseClass.get(); // Auto-filtered by tenant
const security = securityClass.get();
const cache = cacheClass.get('api');
// User endpoint (tenant-isolated)
app.get(
'/api/users',
auth.requireLogin(),
security.requests(100, 900000), // Rate limiting
async (req, res) => {
const users = await cache.getOrSet(
'users',
async () => {
return await database.user.findMany(); // Only current tenant
},
300
);
res.json(users);
}
);
// Admin endpoint (cross-tenant access)
app.get(
'/api/admin/analytics',
auth.requireRole('admin.system'),
async (req, res) => {
const dbTenants = await databaseClass.getTenants(); // All tenants
const stats = await dbTenants.user.groupBy({
by: ['tenant_id'],
_count: true,
});
res.json(stats);
}
);
Real-Time Chat Application
import { eventClass } from '@voilajsx/appkit/event';
import { authClass } from '@voilajsx/appkit/auth';
import { databaseClass } from '@voilajsx/appkit/database';
const events = eventClass.get();
const auth = authClass.get();
const database = await databaseClass.get();
// Handle user connections
events.on('user.connected', async (data) => {
const { userId, socketId } = data;
// Join user to their rooms
await events.emit('socket.join', {
socketId,
rooms: [`user:${userId}`, `tenant:${data.tenantId}`],
});
});
// Handle chat messages
events.on('message.send', async (data) => {
const message = await database.message.create({
data: {
content: data.content,
userId: data.userId,
roomId: data.roomId,
},
});
// Broadcast to room (tenant-isolated)
await events.emit('message.broadcast', {
roomId: data.roomId,
message: {
id: message.id,
content: message.content,
user: { name: data.userName },
timestamp: message.createdAt,
},
});
});
// REST API integration
app.post('/api/notifications', auth.requireLogin(), async (req, res) => {
const user = auth.user(req);
// Send real-time notification
await events.emit('notification.send', {
userId: user.userId,
type: 'info',
message: req.body.message,
timestamp: new Date(),
});
res.json({ sent: true });
});
File Upload with Background Processing
import { storageClass } from '@voilajsx/appkit/storage';
import { queueClass } from '@voilajsx/appkit/queue';
import { loggerClass } from '@voilajsx/appkit/logger';
import { securityClass } from '@voilajsx/appkit/security';
const storage = storageClass.get();
const queue = queueClass.get();
const logger = loggerClass.get('upload');
const security = securityClass.get();
// File upload with background processing
app.post(
'/upload',
security.requests(10, 60000), // 10 uploads per minute
async (req, res) => {
// Sanitize filename
const safeName = security.input(req.file.originalname);
const key = `uploads/${Date.now()}-${safeName}`;
// Store file (auto-detects Local/S3/R2)
await storage.put(key, req.file.buffer, {
contentType: req.file.mimetype,
});
// Queue background processing
await queue.add('process-image', {
key,
userId: req.user.id,
originalName: req.file.originalname,
});
logger.info('File uploaded', { key, userId: req.user.id });
res.json({
url: storage.url(key),
key,
processing: true,
});
}
);
// Background processing
queue.process('process-image', async (data) => {
const logger = loggerClass.get('processor');
try {
const buffer = await storage.get(data.key);
// Process image (resize, optimize, etc.)
const processed = await processImage(buffer);
// Store processed version
const processedKey = data.key.replace('.', '-processed.');
await storage.put(processedKey, processed);
logger.info('Image processed', {
original: data.key,
processed: processedKey,
});
return { processedKey };
} catch (error) {
logger.error('Processing failed', {
key: data.key,
error: error.message,
});
throw error;
}
});
๐ค AI Agent Integration Examples
Prompt for Complete Auth System
Create a Node.js API with user authentication, role-based access control,
and protected admin routes using VoilaJSX AppKit.
AI Agent Output (guaranteed to work):
import { authClass } from '@voilajsx/appkit/auth';
import { errorClass } from '@voilajsx/appkit/error';
import { databaseClass } from '@voilajsx/appkit/database';
import { loggerClass } from '@voilajsx/appkit/logger';
const auth = authClass.get();
const error = errorClass.get();
const database = await databaseClass.get();
const logger = loggerClass.get('auth');
// Login endpoint
app.post(
'/auth/login',
error.asyncRoute(async (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
throw error.badRequest('Email and password required');
}
const user = await database.user.findUnique({ where: { email } });
if (!user) {
throw error.unauthorized('Invalid credentials');
}
const isValid = await auth.comparePassword(password, user.password);
if (!isValid) {
throw error.unauthorized('Invalid credentials');
}
// Generate login token for user authentication
const loginToken = auth.generateLoginToken({
userId: user.id,
role: user.role,
level: user.level,
});
logger.info('User logged in', { userId: user.id });
res.json({ token: loginToken, user: { id: user.id, email: user.email } });
})
);
// Create API token for external service
app.post(
'/admin/api-tokens',
auth.requireLoginToken(),
auth.requireUserRoles(['admin.tenant']),
error.asyncRoute(async (req, res) => {
const { keyId, permissions } = req.body;
// Generate API token for service authentication
const apiToken = auth.generateApiToken(
{
keyId,
role: 'service',
level: 'external',
permissions,
},
'1y'
);
res.json({ apiToken });
})
);
// Protected user route (requires login token)
app.get(
'/api/profile',
auth.requireLoginToken(),
error.asyncRoute(async (req, res) => {
const user = auth.user(req);
const profile = await database.user.findUnique({
where: { id: user.userId },
});
res.json(profile);
})
);
// Admin-only route (requires login token + admin role)
app.get(
'/api/admin/users',
auth.requireLoginToken(),
auth.requireUserRoles(['admin.tenant']),
error.asyncRoute(async (req, res) => {
const users = await database.user.findMany();
res.json(users);
})
);
// API endpoint (requires API token)
app.post(
'/webhook/data',
auth.requireApiToken(),
error.asyncRoute(async (req, res) => {
const token = auth.user(req);
logger.info('Webhook received', { keyId: token.keyId });
res.json({ received: true });
})
);
// Error handling middleware (must be last)
app.use(error.handleErrors());
Prompt for Multi-Tenant Data API
Build a multi-tenant API where users can only see their organization's data,
but admins can access all organizations.
AI Agent Output:
import { databaseClass } from '@voilajsx/appkit/database';
import { authClass } from '@voilajsx/appkit/auth';
import { errorClass } from '@voilajsx/appkit/error';
const auth = authClass.get();
const error = errorClass.get();
// User data (tenant-isolated)
app.get(
'/api/projects',
auth.requireLogin(),
error.asyncRoute(async (req, res) => {
const database = await databaseClass.get(); // Auto-filtered by user's tenant
const projects = await database.project.findMany({
include: { tasks: true },
});
res.json(projects); // Only current tenant's projects
})
);
// Admin data (cross-tenant)
app.get(
'/api/admin/all-projects',
auth.requireRole('admin.system'),
error.asyncRoute(async (req, res) => {
const dbTenants = await databaseClass.getTenants(); // All tenants
const allProjects = await dbTenants.project.findMany({
include: {
tasks: true,
_count: { select: { tasks: true } },
},
});
res.json(allProjects); // All organizations' projects
})
);
// Organization-specific admin access
app.get(
'/api/admin/org/:orgId/projects',
auth.requireRole('admin.org'),
error.asyncRoute(async (req, res) => {
const { orgId } = req.params;
const orgDatabase = await databaseClass.org(orgId).get();
const projects = await orgDatabase.project.findMany();
res.json(projects); // Specific organization's projects
})
);
๐ Production Deployment
Required Environment Variables
# Core Security (Required)
VOILA_AUTH_SECRET=your-super-secure-jwt-secret-minimum-32-chars
# Database (Required)
DATABASE_URL=postgresql://user:pass@host:5432/database
# Production Services (Auto-detected)
REDIS_URL=redis://user:pass@host:6379
AWS_S3_BUCKET=your-bucket
RESEND_API_KEY=re_your_api_key
VOILA_SECURITY_CSRF_SECRET=your-csrf-secret-32-chars
# Multi-tenancy (Optional)
VOILA_DB_TENANT=auto
# Organization Scaling (Optional)
ORG_ACME=postgresql://acme.dedicated.aws.com/prod
ORG_STARTUP=mongodb://startup.azure.com/db
Docker Production Setup
FROM node:18-alpine
WORKDIR /app
# Copy package files
COPY package*.json ./
RUN npm ci --only=production
# Copy application
COPY . .
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD node -e "require('http').get('http://localhost:3000/health', (res) => { process.exit(res.statusCode === 200 ? 0 : 1) })"
EXPOSE 3000
CMD ["node", "server.js"]
Kubernetes Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: voila-app
spec:
replicas: 3
selector:
matchLabels:
app: voila-app
template:
metadata:
labels:
app: voila-app
spec:
containers:
- name: app
image: my-app:latest
ports:
- containerPort: 3000
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: app-secrets
key: database-url
- name: REDIS_URL
valueFrom:
secretKeyRef:
name: app-secrets
key: redis-url
livenessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 30
periodSeconds: 10
๐ Performance & Scalability
Benchmarks
- Startup Time: < 100ms (all modules loaded)
- Memory Usage: < 50MB baseline (production)
- Request Throughput: 10,000+ req/sec (with Redis)
- Database Connections: Automatic pooling and management
Scaling Characteristics
Environment | Cache | Storage | Queue | Database |
---|---|---|---|---|
Development | Memory | Local | Memory | Single |
Staging | Redis | S3 | Redis | Single |
Production | Redis Cluster | S3/R2 + CDN | Redis Cluster | Read Replicas |
Enterprise | Multi-region | Multi-cloud | Distributed | Multi-tenant |
๐งช Testing & Quality
Testing Setup
import { utilClass } from '@voilajsx/appkit/util';
import { loggerClass } from '@voilajsx/appkit/logger';
import { cacheClass } from '@voilajsx/appkit/cache';
import { databaseClass } from '@voilajsx/appkit/database';
import { authClass } from '@voilajsx/appkit/auth';
describe('API Tests', () => {
beforeEach(() => {
// Reset modules for clean tests
utilClass.clearCache();
});
afterEach(async () => {
// Clean up resources
await loggerClass.clear();
await cacheClass.clear();
await databaseClass.clear();
});
test('should handle user creation safely', async () => {
const auth = authClass.get();
const util = utilClass.get();
const userData = {
email: 'test@example.com',
name: 'Test User',
};
// Test safe property access
const email = util.get(userData, 'email');
expect(email).toBe('test@example.com');
// Test JWT token creation
const token = auth.signToken({
userId: 123,
role: 'user',
level: 'basic',
});
expect(token).toBeDefined();
// Test token verification
const payload = auth.verifyToken(token);
expect(payload.userId).toBe(123);
});
});
Code Quality Standards
- 100% TypeScript: Full type safety across all modules
- Comprehensive Tests: Unit, integration, and e2e testing
- Security Audits: Regular dependency and vulnerability scanning
- Performance Monitoring: Built-in metrics and observability
๐ SEO & Discovery
Keywords & Technologies
- Node.js Framework: Enterprise-grade backend development
- AI Code Generation: LLM-optimized, agentic programming
- Multi-tenant SaaS: Progressive scaling, organization management
- Zero Configuration: Environment-driven, production-ready
- TypeScript Ready: Full type safety, modern development
- Microservices: Modular architecture, independent scaling
- JWT Authentication: Role-based access control, security
- Real-time Applications: WebSocket support, event-driven, pub/sub
- Cloud Native: Docker, Kubernetes, auto-scaling
- Developer Experience: Fast development, maintainable code
Use Cases
- SaaS Applications: Multi-tenant, progressive scaling
- API Backends: RESTful, GraphQL, real-time
- E-commerce Platforms: Payments, inventory, user management
- Content Management: File handling, media processing
- Enterprise Applications: Security, compliance, audit trails
- Microservices: Independent, scalable, maintainable
- AI Applications: LLM integration, automated workflows
- Startup MVPs: Rapid development, production-ready
๐ Learning Resources
Quick References
- ๐ CLI Reference - Complete command guide and usage examples
- ๐ค LLM Integration Guide - AI development patterns and module usage
- ๐ Code Standards - Documentation guidelines for backend apps
Module Documentation
- Authentication & Authorization - Dual token system, role.level hierarchy, automatic inheritance
- Database & Multi-tenancy - Progressive scaling, organizations
- File Storage & CDN - Local to cloud, automatic optimization
- Caching & Performance - Memory to Redis, namespace isolation
- Background Jobs - Processing, scheduling, reliability
- Email & Communications - Multi-provider, templates
- Real-time Events - WebSocket, pub/sub, notifications
- Security & Compliance - CSRF, encryption, rate limiting
- Error Handling - HTTP status codes, semantic errors
- Logging & Observability - Structured, multi-transport
- Configuration Management - Environment-driven, type-safe
- Utilities & Helpers - 12 essential developer tools
๐ Community & Support
Getting Help
- ๐ GitHub Issues - Bug reports and feature requests
- ๐ง Email Support - Direct support for enterprises
Contributing
We welcome contributions! See our Contributing Guide for:
- ๐ Bug fixes and improvements
- ๐ Documentation enhancements
- โจ New module features
- ๐งช Test coverage improvements
- ๐ก Feature suggestions
๐ License
MIT ยฉ VoilaJSX - See LICENSE for details.
๐ Built for the AI-first future of software development
Where enterprise applications are generated, not written
โญ Star us on GitHub
๐ Tags
nodejs
typescript
framework
ai-ready
enterprise
multi-tenant
saas
microservices
jwt-authentication
zero-config
production-ready
agentic-ai
llm-optimized
progressive-scaling
real-time
websocket
pub-sub
developer-experience