sickn33/agentic-awesome-skills / plugins/aasb-aas-api-platform-builder/skills/backend-dev-guidelines
backend-dev-guidelines
VerifiedYou are a senior backend engineer operating production-grade services under strict architectural and reliability constraints. Use when routes, controllers, services, repositories, express middleware, or prisma database access.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 8.9 KB |
| resources/architecture-overview.md | markdown | 13.3 KB |
| resources/async-and-errors.md | markdown | 7.8 KB |
| resources/complete-examples.md | markdown | 17.6 KB |
| resources/configuration.md | markdown | 7.0 KB |
| resources/database-patterns.md | markdown | 5.8 KB |
| resources/middleware-guide.md | markdown | 6.2 KB |
| resources/routing-and-controllers.md | markdown | 20.8 KB |
| resources/sentry-and-monitoring.md | markdown | 7.4 KB |
| resources/services-and-repositories.md | markdown | 23.2 KB |
| resources/testing-guide.md | markdown | 6.1 KB |
| resources/validation-patterns.md | markdown | 18.4 KB |
resources/configuration.md
View on GitHub# Configuration Management - UnifiedConfig Pattern
> Scope: independent illustrative fragments, not a supplied runnable application. Private project paths, helpers, DTOs and Prisma models must be implemented/adapted in the target repository. Pin and check installed Express/Sentry/Zod/Prisma versions. Authentication does not grant object/tenant access; authorize before reads/writes, enforce CSRF for cookie authentication, allowlist DTOs and project public response fields. Capture unexpected errors once at an approved, redacted boundary; never send raw request bodies, credentials or personal data to telemetry.
Complete guide to managing configuration in backend microservices.
## Table of Contents
- [UnifiedConfig Overview](#unifiedconfig-overview)
- [NEVER Use process.env Directly](#never-use-processenv-directly)
- [Configuration Structure](#configuration-structure)
- [Environment-Specific Configs](#environment-specific-configs)
- [Secrets Management](#secrets-management)
- [Migration Guide](#migration-guide)
---
## UnifiedConfig Overview
### Why UnifiedConfig?
**Problems with process.env:**
- ❌ No type safety
- ❌ No validation
- ❌ Hard to test
- ❌ Scattered throughout code
- ❌ No default values
- ❌ Runtime errors for typos
**Benefits of unifiedConfig:**
- ✅ Type-safe configuration
- ✅ Single source of truth
- ✅ Validated at startup
- ✅ Easy to test with mocks
- ✅ Clear structure
- ✅ Fallback to environment variables
---
## NEVER Use process.env Directly
### The Rule
```typescript
// ❌ NEVER DO THIS
const timeout = parseInt(process.env.TIMEOUT_MS || '5000');
const dbHost = process.env.DB_HOST || 'localhost';
// ✅ ALWAYS DO THIS
import { config } from './config/unifiedConfig';
const timeout = config.timeouts.default;
const dbHost = config.database.host;
```
### Why This Matters
**Example of problems:**
```typescript
// Typo in environment variable name
const host = process.env.DB_HSOT; // undefined! No error!
// Type safety
const port = process.env.PORT; // string! Need parseInt
const timeout = parseInt(process.env.TIMEOUT); // NaN if not set!
```
**With unifiedConfig:**
```typescript
const port = config.server.port; // number, guaranteed
const timeout = config.timeouts.default; // number, with fallback
```
---
## Configuration Structure
### UnifiedConfig Interface
```typescript
export interface UnifiedConfig {
database: {
host: string;
port: number;
username: string;
password: string;
database: string;
};
server: {
port: number;
sessionSecret: string;
};
tokens: {
jwt: string;
inactivity: string;
internal: string;
};
keycloak: {
realm: string;
client: string;
baseUrl: string;
secret: string;
};
aws: {
region: string;
emailQueueUrl: string;
accessKeyId: string;
secretAccessKey: string;
};
sentry: {
dsn: string;
environment: string;
tracesSampleRate: number;
};
// ... more sections
}
```
### Implementation Pattern
**File:** `/blog-api/src/config/unifiedConfig.ts`
```typescript
import * as fs from 'fs';
import * as path from 'path';
import * as ini from 'ini';
const configPath = path.join(__dirname, '../../config.ini');
const iniConfig = fs.existsSync(configPath) ? ini.parse(fs.readFileSync(configPath, 'utf-8')) : {};
export const config: Pick<UnifiedConfig, 'database' | 'server' | 'tokens'> = {
database: {
host: process.env.DB_HOST || iniConfig.database?.host || 'localhost',
port: Number(process.env.DB_PORT || iniConfig.database?.port || '3306'),
username: process.env.DB_USER || iniConfig.database?.username || 'app_user',
password: process.env.DB_PASSWORD || iniConfig.database?.password || '',
database: process.env.DB_NAME || iniConfig.database?.database || 'blog_dev',
},
server: {
port: Number(process.env.PORT || iniConfig.server?.port || '3002'),
sessionSecret: process.env.SESSION_SECRET || iniConfig.server?.sessionSecret || '',
},
tokens: {
jwt: process.env.JWT_SECRET || iniConfig.tokens?.jwt || '',
inactivity: '30m',
internal: process.env.INTERNAL_API_TOKEN || iniConfig.tokens?.internal || '',
},
};
// Validate critical config
if (!config.tokens.jwt || !config.tokens.internal || !config.server.sessionSecret || !config.database.password) {
throw new Error('Required secrets are not configured');
}
for (const port of [config.database.port, config.server.port]) {
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid port');
}
```
**Key Points:**
- Read from config.ini first
- Fallback to process.env
- Default values for development
- Validation at startup
- Type-safe access
---
## Environment-Specific Configs
### config.ini Structure
```ini
[database]
host = localhost
port = 3306
username = root
password = <LOCAL_SECRET_NOT_COMMITTED>
database = blog_dev
[server]
port = 3002
sessionSecret = your-secret-here
[tokens]
jwt = your-jwt-secret
inactivity = 30m
internal = internal-api-token
[keycloak]
realm = myapp
client = myapp-client
baseUrl = http://localhost:8080
secret = keycloak-client-secret
[sentry]
dsn = https://your-sentry-dsn
environment = development
tracesSampleRate = 0.1
```
### Environment Overrides
```bash
# .env file (optional overrides)
DB_HOST=production-db.example.com
DB_PASSWORD=<INJECTED_SECRET>
PORT=80
```
The snippets are partial configuration fragments; read config.ini only if present, fail on malformed files, and complete/validate every field required by the actual application. Never silently substitute production secrets.
**Precedence:**
1. process.env variables (highest priority; implement consistently in the bootstrap)
2. local development config.ini
3. Hard-coded defaults (lowest priority)
---
## Secrets Management
### DO NOT Commit Secrets
```gitignore
# .gitignore
config.ini
.env
sentry.ini
*.pem
*.key
```
### Use Environment Variables in Production
```typescript
// Development: config.ini
// Production: Environment variables
export const config: UnifiedConfig = {
database: {
password: process.env.DB_PASSWORD || iniConfig.database?.password || '',
},
tokens: {
jwt: process.env.JWT_SECRET || iniConfig.tokens?.jwt || '',
},
};
```
---
## Migration Guide
### Find All process.env Usage
```bash
grep -r "process.env" blog-api/src/ --include="*.ts" | wc -l
```
### Migration Example
**Before:**
```typescript
// Scattered throughout code
const timeout = parseInt(process.env.OPENID_HTTP_TIMEOUT_MS || '15000');
const keycloakUrl = process.env.KEYCLOAK_BASE_URL;
const jwtSecret = process.env.JWT_SECRET;
```
**After:**
```typescript
import { config } from './config/unifiedConfig';
const timeout = config.keycloak.timeout;
const keycloakUrl = config.keycloak.baseUrl;
const jwtSecret = config.tokens.jwt;
```
**Benefits:**
- Type-safe
- Centralized
- Easy to test
- Validated at startup
---
**Related Files:**
- SKILL.md
- [testing-guide.md](testing-guide.md)
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| deprecation-and-migrationaddyosmani/agent-skillsManages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when migrating a database schema in production, such as renaming or dropping a column without downtime (expand/contract). Use when deciding whether to maintain or sunset existing code. | Stars: 119k | Updated | Claude CodeCodex | Verified | Install |
| performance-optimizationaddyosmani/agent-skillsOptimizes application performance across frontend, backend, queries, and databases. Use when performance requirements exist, when you suspect performance regressions, when Core Web Vitals or load times need improvement, when N+1 query patterns need fixing, or when profiling reveals bottlenecks. | Stars: 119k | Updated | Claude CodeCodex | Verified | Install |
| agent-cost-reportthedotmack/claude-memBelievable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |
| agent-cost-reportthedotmack/claude-memBelievable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |