-
-
Notifications
You must be signed in to change notification settings - Fork 2
SERVICE CODE GENERATION
New in nself v0.8+: Automatically generate production-ready service code from 40+ templates
nself includes a powerful service scaffolding system that generates complete, production-ready microservices from templates. No more writing boilerplate—get started coding your business logic immediately.
nself service list-templatesThis shows all 40+ available templates organized by category:
- Web Frameworks: Express, Fastify, Hono, Gin, Fiber, Rails, etc.
- Full-Stack Frameworks: NestJS, Django REST, FastAPI, Spring Boot
- Real-time & Messaging: Socket.IO, Temporal
- Background Jobs: BullMQ, Celery, Ray
- AI & ML Agents: LLM, Vision, Analytics, Training, Time Series
- And more...
nself service scaffold realtime --template socketio-ts --port 3101This generates:
services/realtime/
├── package.json # Dependencies configured
├── tsconfig.json # TypeScript config
├── Dockerfile # Production-ready container
├── README.md # Complete documentation
└── src/
└── server.ts # Working Socket.IO server with:
# - Type-safe events
# - Redis adapter ready
# - Room/namespace support
# - Health checks
# - Graceful shutdown
# Add to .env
CS_2=realtime:socketio-ts:3101:ws
CS_2_REDIS_PREFIX=ws:
CS_2_REPLICAS=2nself build && nself startYour service is now running at https://ws.yourdomain.com (or ws.localhost in dev).
Generate service code from a template.
Syntax:
nself service scaffold <name> --template <template> [options]Options:
-
--template, -t- Template to use (required) -
--port, -p- Port number (default: 3000) -
--output, -o- Output directory (default: services)
Examples:
# Socket.IO real-time service
nself service scaffold realtime --template socketio-ts --port 3101
# FastAPI REST API
nself service scaffold api --template fastapi --port 8000
# BullMQ background worker
nself service scaffold worker --template bullmq-ts --port 3102
# NestJS full-stack API
nself service scaffold backend --template nest-ts --port 4000
# Go Fiber high-performance API
nself service scaffold fiber-api --template fiber --port 8080List all available templates.
Options:
-
--language, -l- Filter by language (js, ts, python, go, ruby, rust, etc.) -
--category, -c- Filter by category
Examples:
# Show all templates
nself service list-templates
# TypeScript templates only
nself service list-templates --language typescript
# Real-time templates only
nself service list-templates --category "Real-time & Messaging"Show detailed information about a template.
Syntax:
nself service template-info <template>Example:
nself service template-info socketio-tsShows:
- Full description
- Language and category
- Key features
- Dependencies
- Usage examples
Interactive service creation wizard.
Syntax:
nself service wizardGuides you through:
- Service name
- Language selection
- Template selection
- Port configuration
- Confirmation and generation
Fast, lightweight HTTP frameworks for building APIs.
JavaScript/TypeScript:
-
express-js,express-ts- Minimalist, flexible -
fastify-js,fastify-ts- High performance, schema validation -
hono-js,hono-ts- Ultra-fast, edge-ready -
node-js,node-ts- Bare Node.js HTTP server
Python:
-
flask- Lightweight, flexible -
fastapi- Modern, async, auto-docs
Go:
-
gin- Fast, minimalist -
fiber- Express-inspired -
echo- High performance
Other:
-
rails,sinatra(Ruby) -
actix-web(Rust) -
laravel(PHP) -
vapor(Swift) -
oatpp(C++)
Enterprise-grade frameworks with batteries included.
-
nest-js,nest-ts- TypeScript-first, dependency injection -
django-rest- Python ORM, admin panel, full auth -
spring-boot- Java enterprise applications -
phoenix- Elixir real-time apps with LiveView -
aspnet- C# cross-platform framework
WebSocket and real-time communication services.
-
socketio-js,socketio-ts- Bidirectional events, rooms, Redis adapter -
temporal-js,temporal-ts- Durable workflow orchestration
Asynchronous task processing and job queues.
-
bullmq-js,bullmq-ts- Redis-backed job queues with TypeScript -
celery- Python distributed task queue -
ray- Python distributed computing
Specialized templates for AI/ML workloads.
-
agent-llm- LLM provider integration, streaming, RAG -
agent-vision- Computer vision, image processing, OCR -
agent-analytics- Data analysis, visualization, reporting -
agent-training- Model training, hyperparameter tuning -
agent-timeseries- Forecasting, anomaly detection
Type-safe and high-performance API development.
-
trpc- End-to-end type safety for TypeScript -
grpc- Protocol Buffers, high-performance RPC
Modern JavaScript/TypeScript runtimes.
-
bun- Fast all-in-one runtime -
deno- Secure TypeScript runtime
Goal: Socket.IO service with Redis adapter for horizontal scaling.
# 1. Generate service
nself service scaffold realtime --template socketio-ts --port 3101
# 2. Review generated code
cd services/realtime
cat src/server.ts # Type-safe events, rooms, broadcasting
# 3. Add Redis adapter (optional, for multiple instances)
npm install @socket.io/redis-adapter ioredis
# 4. Configure in .env
cat >> .env << 'EOF'
REDIS_ENABLED=true
CS_2=realtime:socketio-ts:3101:ws
CS_2_REDIS_PREFIX=ws:
CS_2_REPLICAS=2
CS_2_MEMORY=512M
EOF
# 5. Build and start
cd ../..
nself build && nself start
# 6. Test
curl http://localhost:3101/health
# {"status":"healthy","service":"realtime","connections":0}Access:
- Development:
ws://localhost:3101 - Production:
wss://ws.yourdomain.com
Goal: Python API with auto-generated docs and Pydantic validation.
# 1. Generate service
nself service scaffold api --template fastapi --port 8000
# 2. Customize code
cd services/api
# Edit main.py to add your endpoints
# 3. Configure
cat >> ../../.env << 'EOF'
CS_3=api:fastapi:8000
EOF
# 4. Build and start
cd ../..
nself build && nself start
# 5. Access auto-generated docs
open http://localhost:8000/docs # Swagger UI
open http://localhost:8000/redoc # ReDocGoal: BullMQ worker for processing async tasks.
# 1. Generate worker
nself service scaffold worker --template bullmq-ts --port 3102
# 2. Define job processors
cd services/worker/src
# Edit worker.ts to add job handlers
# 3. Configure
cat >> ../../../.env << 'EOF'
REDIS_ENABLED=true
CS_4=worker:bullmq-ts:3102
CS_4_CONCURRENCY=10
EOF
# 4. Build and start
cd ../../..
nself build && nself start
# 5. Enqueue jobs from other services
# Use BullMQ client to add jobs to queuesComplete stack: Web API + Real-time + Worker + AI Agent
# Generate all services
nself service scaffold api --template fastapi --port 8000
nself service scaffold realtime --template socketio-ts --port 3101
nself service scaffold worker --template bullmq-ts --port 3102
nself service scaffold ai --template agent-llm --port 8001
# Configure in .env
cat >> .env << 'EOF'
# Enable required services
REDIS_ENABLED=true
MINIO_ENABLED=true
MEILISEARCH_ENABLED=true
# Custom services
CS_1=api:fastapi:8000
CS_2=realtime:socketio-ts:3101:ws
CS_2_REDIS_PREFIX=ws:
CS_2_REPLICAS=2
CS_3=worker:bullmq-ts:3102
CS_4=ai:agent-llm:8001
CS_4_MEMORY=2G
EOF
# Build and start entire stack
nself build && nself start
# Access points:
# - API: http://api.localhost
# - WebSocket: ws://ws.localhost
# - AI: http://ai.localhost
# - Hasura: http://api.localhost (GraphQL)All templates include:
✅ Production-Ready Dockerfile
- Multi-stage builds
- Security best practices
- Non-root user
- Health checks
- Proper signal handling
✅ Development Tooling
- Hot reload / watch mode
- TypeScript (for TS templates)
- Linting configuration
- Debug support
✅ Health Checks
-
/healthendpoint - Ready for k8s/Docker health checks
✅ Environment Configuration
-
.envvariable support - Sensible defaults
- nself integration variables
✅ Documentation
- Comprehensive README
- Usage examples
- API documentation
- Deployment guide
Special Features:
// Type-safe events
interface ServerToClientEvents {
welcome: (data: WelcomeData) => void;
message: (data: MessageData) => void;
}
interface ClientToServerEvents {
message: (text: string) => void;
join_room: (room: string) => void;
}
// Redis adapter ready
import { createAdapter } from '@socket.io/redis-adapter';
io.adapter(createAdapter(pubClient, subClient));Includes:
- Room/namespace management
- Broadcasting
- Authentication hooks
- Rate limiting ready
- Presence tracking examples
Special Features:
# Auto-generated OpenAPI docs
# Pydantic validation
# Async/await support
@app.post("/items/")
async def create_item(item: Item):
# Validated automatically
return {"item": item}Includes:
- Swagger UI at
/docs - ReDoc at
/redoc - CORS configuration
- Database integration examples
- JWT auth ready
Special Features:
// Type-safe job processing
interface EmailJob {
to: string;
subject: string;
body: string;
}
worker.process('email', async (job: Job<EmailJob>) => {
const { to, subject, body } = job.data;
await sendEmail(to, subject, body);
});Includes:
- Job retries
- Scheduling
- Rate limiting
- Priority queues
- Job events
Special Features:
// Dependency injection
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
) {}
}
// Decorators
@Controller('users')
export class UsersController {
@Get()
findAll(): Promise<User[]> {
return this.usersService.findAll();
}
}Includes:
- Modular architecture
- Guards and interceptors
- Pipes for validation
- Database integration
- Swagger integration
services/
├── api/ # Main REST API (FastAPI/NestJS)
├── realtime/ # Socket.IO for real-time
├── worker/ # Background jobs (BullMQ)
├── ai/ # AI/ML services
└── grpc/ # gRPC microservices
-
3000-3099: Frontend applications -
3100-3199: Real-time services (WebSocket) -
4000-4999: Backend APIs -
8000-8999: Python services -
9000-9999: Go services
Use descriptive names that indicate purpose:
-
api- Main REST API -
realtime- WebSocket/Socket.IO -
worker- Background job processor -
ml-training- ML model training -
analytics- Analytics processing
# In .env
CS_1=api:fastapi:8000
CS_1_MEMORY=1G
CS_1_REPLICAS=2
CS_2=realtime:socketio-ts:3101:ws
CS_2_REDIS_PREFIX=ws:
CS_2_REPLICAS=3
CS_3=worker:bullmq-ts:3102
CS_3_CONCURRENCY=10# 1. Scaffold service
nself service scaffold myservice --template <template>
# 2. Develop locally
cd services/myservice
npm run dev # or python main.py, go run main.go
# 3. Test in isolation
curl http://localhost:PORT/health
# 4. Add to nself stack
# Edit .env to add CS_N=myservice:template:port
# 5. Build and deploy
nself build && nself startAfter scaffolding, the generated code is yours to customize:
nself service scaffold api --template fastapi --port 8000
cd services/api
# Customize freely:
# - Add new endpoints
# - Change dependencies
# - Modify Dockerfile
# - Add middleware
# - Configure loggingFiles are never overwritten by nself build - your changes persist.
Services auto-include environment variables for nself services:
// TypeScript example
const hasuraEndpoint = process.env.HASURA_GRAPHQL_ENDPOINT;
const hasuraSecret = process.env.HASURA_GRAPHQL_ADMIN_SECRET;
const redisUrl = process.env.REDIS_URL;
const minioEndpoint = process.env.MINIO_ENDPOINT;
// Use in your service
import fetch from 'node-fetch';
async function queryHasura(query: string) {
const response = await fetch(hasuraEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-hasura-admin-secret': hasuraSecret
},
body: JSON.stringify({ query })
});
return response.json();
}# Python example
import os
import httpx
HASURA_ENDPOINT = os.getenv('HASURA_GRAPHQL_ENDPOINT')
HASURA_SECRET = os.getenv('HASURA_GRAPHQL_ADMIN_SECRET')
async def query_hasura(query: str):
async with httpx.AsyncClient() as client:
response = await client.post(
HASURA_ENDPOINT,
json={'query': query},
headers={'x-hasura-admin-secret': HASURA_SECRET}
)
return response.json()$ nself service scaffold test --template invalid
Error: Template not found: invalid
Run 'nself service list-templates' to see available templatesSolution: Use nself service list-templates to find the correct template name.
$ nself service scaffold api --template fastapi
Error: Service directory already exists: services/api
Use a different name or remove the existing directorySolution: Choose a different name or remove the existing directory.
After scaffolding, install dependencies:
# Node.js/TypeScript
cd services/myservice
npm install
# Python
cd services/myservice
pip install -r requirements.txt
# Go
cd services/myservice
go mod downloadnself service scaffold api --template fastapi --output backend
# Generates: backend/api/ instead of services/api/#!/bin/bash
# generate-microservices.sh
services=(
"api:fastapi:8000"
"realtime:socketio-ts:3101"
"worker:bullmq-ts:3102"
"analytics:agent-analytics:8001"
)
for service in "${services[@]}"; do
IFS=':' read -r name template port <<< "$service"
nself service scaffold "$name" --template "$template" --port "$port"
done# Generate polyglot architecture
nself service scaffold api-gateway --template nest-ts --port 4000
nself service scaffold ml-service --template fastapi --port 8000
nself service scaffold cache-service --template go-fiber --port 9000
nself service scaffold worker --template bullmq-ts --port 3102ɳSelf CLI v1.0.9. MIT licensed. Docs CC BY 4.0.
GitHub · Issues · Discussions · nself.org · nself.org/docs
Getting Started
Commands
- Commands, Overview
- Lifecycle: cmd-init · cmd-build · cmd-start · cmd-stop · cmd-restart · cmd-dev
- Monitoring: cmd-status · cmd-logs · cmd-health · cmd-urls · cmd-doctor · cmd-monitor · cmd-alerts · cmd-sentry · cmd-watchdog
- Data: cmd-db · cmd-backup · cmd-dr · cmd-queue · cmd-webhooks
- Config: cmd-config · cmd-service · cmd-env · cmd-promote
- Networking: cmd-ssl · cmd-trust · cmd-dns-setup
- Security: cmd-access · cmd-security · cmd-secrets
- Tenancy: cmd-tenant · cmd-billing
- Plugins: cmd-plugin · cmd-license · cmd-dogfood (extracted, CLI-R11) · cmd-k8s (extracted, CLI-R11) · cmd-encryption (extracted, CLI-R11) · cmd-waf (extracted, CLI-R11) · cmd-federation (extracted, CLI-R11) · cmd-mail (extracted, CLI-R11) · cmd-dlq (extracted, CLI-R11)
- AI: cmd-ai · cmd-claw · cmd-model
- Templates: cmd-template
- Utilities: cmd-exec · cmd-clean · cmd-reset · cmd-update · cmd-upgrade · cmd-version · cmd-admin · cmd-migrate · cmd-migrate-firebase · cmd-migrate-supabase · cmd-completion
Features
- Features, Overview
- Feature-Auth
- Feature-Storage
- Feature-Search
- Feature-Functions
- Feature-Email
- Feature-Monitoring
- Feature-Plugins
- Feature-nClaw, AI Assistant
- Feature-nChat, Messaging
- Feature-nTV, Media Player
- Feature-nFamily, Family Social
- Feature-nCloud, Managed Hosting
- Feature-Memory-Rooms, Knowledge Organization
- Feature-Agent-Dashboard, Agent Metrics
- Feature-Image-Generation, AI Image Generation
Configuration
- Configuration, Overview
- Config-Env-Vars
- Config-Postgres
- Config-Hasura
- Config-Auth
- Config-Nginx
- Config-Optional-Services
- Config-Custom-Services
- Config-System
Plugins (87 + 10 monitoring)
Free (25)
- plugin-backup
- plugin-content-acquisition
- plugin-content-progress
- plugin-cron
- plugin-donorbox
- plugin-feature-flags
- plugin-github
- plugin-github-runner
- plugin-invitations
- plugin-jobs
- plugin-link-preview
- plugin-mdns
- plugin-mlflow
- plugin-monitoring
- plugin-notifications
- plugin-notify
- plugin-paypal
- plugin-search
- plugin-shopify
- plugin-stripe
- plugin-subtitle-manager
- plugin-tokens
- plugin-torrent-manager
- plugin-vpn
- plugin-webhooks
Pro (62)
- plugin-access-controls
- plugin-activity-feed
- plugin-admin-api
- plugin-nself-ai-gateway
- plugin-nself-ai-mcp
- plugin-nself-ai-mcp
- plugin-analytics
- plugin-auth
- plugin-backup-pro
- plugin-bots
- plugin-browser
- plugin-calendar
- plugin-cdn
- plugin-chat
- plugin-claw
- plugin-claw-budget
- plugin-claw-news
- plugin-claw-web
- plugin-cloudflare
- plugin-cms
- plugin-compliance
- plugin-cron-pro
- plugin-ddns
- plugin-devices
- plugin-documents
- plugin-donorbox-pro
- plugin-entitlements
- plugin-epg
- plugin-file-processing
- plugin-game-metadata
- plugin-geocoding
- plugin-geolocation
- plugin-google
- plugin-home
- plugin-idme
- plugin-knowledge-base
- plugin-linkedin
- plugin-livekit
- plugin-media-processing
- plugin-meetings
- plugin-moderation
- plugin-mux
- plugin-notify-pro
- plugin-object-storage
- plugin-observability
- plugin-paypal-pro
- plugin-photos
- plugin-podcast
- plugin-post
- plugin-realtime
- plugin-recording
- plugin-retro-gaming
- plugin-rom-discovery
- plugin-shopify-pro
- plugin-social
- plugin-sports
- plugin-stream-gateway
- plugin-streaming
- plugin-stripe-pro
- plugin-support
- plugin-tmdb
- plugin-voice
- plugin-web3
- plugin-workflows
Planned (26)
plugin-auditplugin-blogplugin-checkoutplugin-commerceplugin-drmplugin-exportplugin-flowplugin-importplugin-ldapplugin-mailgunplugin-mediaplugin-oauth-providersplugin-pagesplugin-postmarkplugin-rate-limitplugin-reportsplugin-samlplugin-schedulerplugin-sendgridplugin-ssoplugin-subscriptionplugin-thumbplugin-transcoderplugin-twilioplugin-wafplugin-watermark
Guides
- Guide-Production-Deployment
- Guide-SSL-Setup
- Guide-Multi-Tenancy
- Guide-Security-Hardening
- Guide-Monitoring-Setup
- Guide-Backup-Restore
- Guide-Custom-Services
- Guide-Migration-from-v1
Architecture
Reference
- API-Reference
- error-codes, Error Codes
Licensing
Security
Brand
Operations
- operations/release-cascade, Release Cascade
- operations/self-healing, Self-Healing Schema
- operations/redis-tuning, Redis Pool Tuning
- operations/meilisearch-warmup, MeiliSearch Warm-Up
- operations/jwt-rotation, JWT Key Rotation
- operations/windows-wsl2-setup, Windows / WSL2 Setup
- operations/gemini-oauth-reauth, Gemini OAuth Reauth
Contributing
Admin
- USER-ACTION-QUEUE, Pending Admin Actions
All commands (52)
- A: cmd-access · cmd-account · cmd-admin
- B: cmd-backup · cmd-build · cmd-bundle
- C: cmd-ci · cmd-clean · cmd-completion · cmd-config
- D: cmd-db · cmd-deploy · cmd-dev · cmd-doctor
- E: cmd-env · cmd-exec
- F: cmd-functions
- G: cmd-generate
- H: cmd-health · cmd-help-topics
- I: cmd-init · cmd-install
- L: cmd-license · cmd-login · cmd-logout · cmd-logs
- M: cmd-man · cmd-mcp · cmd-migrate
- O: cmd-oauth · cmd-ops
- P: cmd-plugin · cmd-promote
- R: cmd-remove · cmd-reset · cmd-restart · cmd-runner
- S: cmd-secrets · cmd-security · cmd-self-heal · cmd-server · cmd-service · cmd-start · cmd-status · cmd-stop
- T: cmd-telemetry · cmd-template · cmd-trust
- U: cmd-update · cmd-urls
- V: cmd-verify-sbom · cmd-version