Backend Development with Security Focus
Secure backend development prevents vulnerabilities while maintaining functionality. Every endpoint, database query, and user input is a potential attack vector.
Core Security Principles
Golden rule: Never trust client input. Always validate, sanitize, and verify.
- Defense in Depth - Multiple layers of security controls
- Principle of Least Privilege - Grant minimum necessary permissions
- Fail Securely - Fail to a secure state when errors occur
- Assume Breach - Design assuming attackers are already inside
- Security by Design - Build security from the start, not as afterthought
API Security
Key Principles:
- Use UUIDs instead of sequential IDs to prevent enumeration
- Implement rate limiting on all endpoints
- Apply authentication middleware before business logic
- Validate all input formats (UUID, email, etc.)
- Use parameterized queries to prevent SQL injection
- Return only necessary fields (don't expose passwords, internal data)
- Version your APIs (
/api/v1/, /api/v2/)
- Limit request payload sizes (JSON: 10kb, files: 5MB max)
- Whitelist allowed file types for uploads
- Always verify authorization (user owns resource or has permissions)
Authentication & Authorization
JWT Best Practices:
- Use strong secrets (64+ characters, generate with
crypto.randomBytes(64).toString('hex'))
- Short-lived access tokens (15 min) + long-lived refresh tokens (7 days)
- Store minimal payload (user ID only, no sensitive data)
- Validate token type (access vs refresh) and expiration
- Use separate secrets for access and refresh tokens
- Support secret rotation for zero-downtime updates
Password Security:
- Enforce strong passwords (12+ chars, uppercase, lowercase, number, special char)
- Hash with bcrypt (salt rounds: 12+)
- Never store plaintext passwords
- Implement account lockout (5 failed attempts = 15 min lock)
- Use generic error messages (don't reveal if email exists)
- Consider MFA for sensitive operations
Role-Based Access Control (RBAC):
- Define roles (Admin, User, Guest) and permissions separately
- Map roles to permissions explicitly
- Check authentication first, then authorization
- Create reusable middleware for permission checks
- Use enums for type safety
- Always verify resource ownership (IDOR prevention)
Input Validation & Sanitization
Schema Validation (use Zod, Joi, or similar):
- Define schemas for all API inputs (body, params, query)
- Validate types, formats, lengths, patterns
- Use
.trim(), .toLowerCase(), .optional(), .default() as needed
- Return detailed validation errors (field + message)
- Create reusable validation middleware
SQL Injection Prevention:
- ALWAYS use parameterized queries (
$1, $2 placeholders)
- NEVER concatenate strings in SQL queries
- Use ORMs (Prisma, TypeORM) when possible for built-in protection
- Escape special characters if parameterization isn't possible
XSS Prevention:
- Sanitize HTML input with DOMPurify or similar
- Whitelist allowed tags and attributes
- Escape output when rendering user content
- Use Content Security Policy headers
- Prefer storing plain text; sanitize only when HTML is necessary
Path Traversal Prevention:
- Validate filenames with regex (alphanumeric, dash, underscore, dot only)
- Use
path.resolve() and check resolved path starts with allowed directory
- Never trust user-provided paths directly
- Whitelist allowed file extensions
- Check file existence before serving
Database Security
Connection Security:
- Use SSL/TLS in production (rejectUnauthorized: true)
- Store credentials in environment variables
- Configure connection pool limits (max: 20, timeout: 2000ms)
- Handle connection errors gracefully
- Use separate read-only users for reporting queries
Query Security:
- Always use parameterized queries (prevents SQL injection)
- Wrap multi-step operations in transactions
- Use ROLLBACK on errors
- Log query errors (but not sensitive data)
- Release connections after use
Data Encryption at Rest:
- Encrypt sensitive fields (credit cards, SSN, PII)
- Use AES-256-GCM for encryption
- Store IV and auth tag with encrypted data
- Use strong encryption keys (32 bytes, in hex)
- Never store encryption keys in code - use environment variables
Error Handling
Secure Error Responses:
- Never expose stack traces or internal details in production
- Log full error details server-side (path, method, user, stack)
- Return generic messages to clients ("Internal server error")
- Use custom error classes with isOperational flag
- Differentiate between operational errors (404, 400) and programmer errors (500)
- Include detailed errors only in development mode
- Use centralized error handling middleware
Security Headers & CORS
Essential Security Headers (use helmet.js):
X-Frame-Options: DENY - Prevent clickjacking
X-Content-Type-Options: nosniff - Prevent MIME sniffing
X-XSS-Protection: 1; mode=block - Enable XSS filter
Strict-Transport-Security - Force HTTPS (max-age=31536000; includeSubDomains)
Content-Security-Policy - Define allowed content sources
Referrer-Policy: strict-origin-when-cross-origin - Control referrer info
Permissions-Policy - Disable unused browser features
CORS Configuration:
- Never use
origin: '*' in production
- Whitelist specific origins in environment variables
- Allow localhost only in development
- Enable credentials for cookie-based auth
- Cache preflight requests (maxAge: 86400)
- Specify allowedHeaders (Content-Type, Authorization)
- Set exposedHeaders for pagination (X-Total-Count)
Secrets Management
Environment Variables:
- Never hardcode secrets in source code
- Use
.env files (add to .gitignore)
- Validate all environment variables on startup using Zod
- Enforce minimum lengths for secrets (64+ characters)
- Validate formats (email, URL, specific prefixes like
sk_)
- Exit process if required secrets are missing
- Use cloud secret managers in production (AWS Secrets Manager, Vault)
Secrets Rotation:
- Support multiple active secrets for zero-downtime rotation
- Try current secret first, fallback to previous
- Set expiration dates for old secrets
- Rotate secrets quarterly or after suspected compromise
Rate Limiting & DoS Prevention
Rate Limiting Strategy:
- Use Redis store for distributed rate limiting
- General API: 100 requests per 15 minutes
- Auth endpoints: 5 attempts per hour (skip successful requests)
- Key by user ID if authenticated, otherwise IP
- Progressive limits (authenticated users get higher limits)
- Return 429 status with clear error message
Request Throttling:
- Slow down after threshold (50 requests) before blocking
- Add incremental delays (500ms per extra request)
- Set maximum delay (20 seconds)
- Prevents aggressive blocking while discouraging abuse
Logging & Monitoring
Structured Logging (use Winston or Pino):
- Use JSON format with timestamps
- Log levels: error, warn, info, debug
- Include context: method, URL, status, duration, userId, IP
- Separate error.log and combined.log files
- Console logging in development only
- Never log sensitive data (passwords, tokens, credit cards)
- Sanitize objects before logging (redact sensitive fields)
Security Event Monitoring:
- Track critical events (failed logins, invalid tokens, permission denials)
- Log IP, user agent, path, timestamp for all security events
- Alert on SQL injection attempts, XSS attempts
- Integrate with monitoring services (Sentry, DataDog, New Relic)
- Set up alerts for suspicious patterns (multiple failed logins, rate limit exceeded)
- Review logs regularly for anomalies
Common Vulnerabilities (OWASP Top 10)
SQL Injection:
- Always use parameterized queries (
$1, $2) - NEVER string concatenation
- Use ORMs (Prisma, TypeORM) for built-in protection
Cross-Site Scripting (XSS):
- Sanitize HTML input (DOMPurify)
- Escape output when rendering
- Use Content Security Policy headers
Cross-Site Request Forgery (CSRF):
- Use CSRF tokens for cookie-based auth (csurf package)
- Set httpOnly, secure, sameSite: 'strict' on cookies
- For JWT APIs, validate origin and use proper CORS
Insecure Deserialization:
- NEVER use eval() or Function() with user input
- Use JSON.parse + schema validation only
- Avoid vm.runInNewContext and similar
XML External Entities (XXE):
- Disable external entity resolution in XML parsers
- Use JSON instead of XML when possible
Insecure Direct Object References (IDOR):
- Always verify resource ownership before returning data
- Check
resource.userId === req.user.uuid or admin status
- Use UUIDs instead of sequential IDs
Testing Security
Unit Tests:
- Test password validation (reject weak, accept strong)
- Test password hashing (bcrypt format, verify correct/incorrect)
- Test authorization (401 without token, 403 without permissions)
- Test input validation (reject malicious patterns)
Integration Tests:
- Test SQL injection attempts (should return 400, not all data)
- Test rate limiting (10+ requests should trigger 429)
- Test IDOR (users can't access others' resources)
- Test CSRF protection on state-changing endpoints
Automated Security Scanning:
npm audit - Check dependencies for vulnerabilities
npx snyk test - Continuous vulnerability monitoring
eslint-plugin-security - Static analysis for security issues
gitleaks detect - Check for hardcoded secrets in code
- Run scans in CI/CD pipeline
Implementation Guidelines
IMPORTANT: Do NOT create summary markdown files, documentation files, or README files unless explicitly requested by the user.
Best Practices
- Never Trust User Input - Validate, sanitize, and escape all input regardless of source
- Use Parameterized Queries - Always use prepared statements for database queries
- Implement Proper Authentication - Use industry-standard methods (JWT, OAuth) with secure configuration
- Apply Principle of Least Privilege - Grant minimum necessary permissions to users and services
- Encrypt Sensitive Data - Use encryption at rest and in transit (TLS/SSL)
- Keep Dependencies Updated - Regularly update packages and scan for vulnerabilities
- Implement Rate Limiting - Prevent abuse and DoS attacks on all endpoints
- Log Security Events - Monitor and alert on suspicious activities
- Handle Errors Securely - Never expose stack traces or internal details to clients
- Use Security Headers - Implement helmet.js and configure CSP, HSTS, etc.
- Validate Environment Config - Ensure all required secrets are present on startup
- Implement Request Timeouts - Prevent resource exhaustion from slow requests
- Use HTTPS Everywhere - Never transmit sensitive data over unencrypted connections
- Implement CSRF Protection - For cookie-based auth, use CSRF tokens
- Regular Security Audits - Conduct code reviews and penetration testing
- Have an Incident Response Plan - Prepare for security breaches before they happen
- Minimize Attack Surface - Disable unnecessary features and endpoints
- Use Security Linters - Integrate security scanning in CI/CD pipeline
- Implement Proper Session Management - Use secure, httpOnly cookies with appropriate expiration
- Document Security Decisions - Maintain a threat model and security architecture docs
References
1---
2name: backend-security
3description: Backend development with security-first approach. Use when building APIs, handling data, implementing authentication, or addressing security vulnerabilities.
4metadata:
5 source: https://skillmd.com/skills/aibot88/backend-security
6---
7
8# Backend Development with Security Focus
9
10Secure backend development prevents vulnerabilities while maintaining functionality. Every endpoint, database query, and user input is a potential attack vector.
11
12## Core Security Principles
13
14**Golden rule**: Never trust client input. Always validate, sanitize, and verify.
15
161. **Defense in Depth** - Multiple layers of security controls
172. **Principle of Least Privilege** - Grant minimum necessary permissions
183. **Fail Securely** - Fail to a secure state when errors occur
194. **Assume Breach** - Design assuming attackers are already inside
205. **Security by Design** - Build security from the start, not as afterthought
21
22## API Security
23
24**Key Principles**:
25- Use UUIDs instead of sequential IDs to prevent enumeration
26- Implement rate limiting on all endpoints
27- Apply authentication middleware before business logic
28- Validate all input formats (UUID, email, etc.)
29- Use parameterized queries to prevent SQL injection
30- Return only necessary fields (don't expose passwords, internal data)
31- Version your APIs (`/api/v1/`, `/api/v2/`)
32- Limit request payload sizes (JSON: 10kb, files: 5MB max)
33- Whitelist allowed file types for uploads
34- Always verify authorization (user owns resource or has permissions)
35
36## Authentication & Authorization
37
38**JWT Best Practices**:
39- Use strong secrets (64+ characters, generate with `crypto.randomBytes(64).toString('hex')`)
40- Short-lived access tokens (15 min) + long-lived refresh tokens (7 days)
41- Store minimal payload (user ID only, no sensitive data)
42- Validate token type (access vs refresh) and expiration
43- Use separate secrets for access and refresh tokens
44- Support secret rotation for zero-downtime updates
45
46**Password Security**:
47- Enforce strong passwords (12+ chars, uppercase, lowercase, number, special char)
48- Hash with bcrypt (salt rounds: 12+)
49- Never store plaintext passwords
50- Implement account lockout (5 failed attempts = 15 min lock)
51- Use generic error messages (don't reveal if email exists)
52- Consider MFA for sensitive operations
53
54**Role-Based Access Control (RBAC)**:
55- Define roles (Admin, User, Guest) and permissions separately
56- Map roles to permissions explicitly
57- Check authentication first, then authorization
58- Create reusable middleware for permission checks
59- Use enums for type safety
60- Always verify resource ownership (IDOR prevention)
61
62## Input Validation & Sanitization
63
64**Schema Validation** (use Zod, Joi, or similar):
65- Define schemas for all API inputs (body, params, query)
66- Validate types, formats, lengths, patterns
67- Use `.trim()`, `.toLowerCase()`, `.optional()`, `.default()` as needed
68- Return detailed validation errors (field + message)
69- Create reusable validation middleware
70
71**SQL Injection Prevention**:
72- ALWAYS use parameterized queries (`$1`, `$2` placeholders)
73- NEVER concatenate strings in SQL queries
74- Use ORMs (Prisma, TypeORM) when possible for built-in protection
75- Escape special characters if parameterization isn't possible
76
77**XSS Prevention**:
78- Sanitize HTML input with DOMPurify or similar
79- Whitelist allowed tags and attributes
80- Escape output when rendering user content
81- Use Content Security Policy headers
82- Prefer storing plain text; sanitize only when HTML is necessary
83
84**Path Traversal Prevention**:
85- Validate filenames with regex (alphanumeric, dash, underscore, dot only)
86- Use `path.resolve()` and check resolved path starts with allowed directory
87- Never trust user-provided paths directly
88- Whitelist allowed file extensions
89- Check file existence before serving
90
91## Database Security
92
93**Connection Security**:
94- Use SSL/TLS in production (rejectUnauthorized: true)
95- Store credentials in environment variables
96- Configure connection pool limits (max: 20, timeout: 2000ms)
97- Handle connection errors gracefully
98- Use separate read-only users for reporting queries
99
100**Query Security**:
101- Always use parameterized queries (prevents SQL injection)
102- Wrap multi-step operations in transactions
103- Use ROLLBACK on errors
104- Log query errors (but not sensitive data)
105- Release connections after use
106
107**Data Encryption at Rest**:
108- Encrypt sensitive fields (credit cards, SSN, PII)
109- Use AES-256-GCM for encryption
110- Store IV and auth tag with encrypted data
111- Use strong encryption keys (32 bytes, in hex)
112- Never store encryption keys in code - use environment variables
113
114## Error Handling
115
116**Secure Error Responses**:
117- Never expose stack traces or internal details in production
118- Log full error details server-side (path, method, user, stack)
119- Return generic messages to clients ("Internal server error")
120- Use custom error classes with isOperational flag
121- Differentiate between operational errors (404, 400) and programmer errors (500)
122- Include detailed errors only in development mode
123- Use centralized error handling middleware
124
125## Security Headers & CORS
126
127**Essential Security Headers** (use helmet.js):
128- `X-Frame-Options: DENY` - Prevent clickjacking
129- `X-Content-Type-Options: nosniff` - Prevent MIME sniffing
130- `X-XSS-Protection: 1; mode=block` - Enable XSS filter
131- `Strict-Transport-Security` - Force HTTPS (max-age=31536000; includeSubDomains)
132- `Content-Security-Policy` - Define allowed content sources
133- `Referrer-Policy: strict-origin-when-cross-origin` - Control referrer info
134- `Permissions-Policy` - Disable unused browser features
135
136**CORS Configuration**:
137- Never use `origin: '*'` in production
138- Whitelist specific origins in environment variables
139- Allow localhost only in development
140- Enable credentials for cookie-based auth
141- Cache preflight requests (maxAge: 86400)
142- Specify allowedHeaders (Content-Type, Authorization)
143- Set exposedHeaders for pagination (X-Total-Count)
144
145## Secrets Management
146
147**Environment Variables**:
148- Never hardcode secrets in source code
149- Use `.env` files (add to `.gitignore`)
150- Validate all environment variables on startup using Zod
151- Enforce minimum lengths for secrets (64+ characters)
152- Validate formats (email, URL, specific prefixes like `sk_`)
153- Exit process if required secrets are missing
154- Use cloud secret managers in production (AWS Secrets Manager, Vault)
155
156**Secrets Rotation**:
157- Support multiple active secrets for zero-downtime rotation
158- Try current secret first, fallback to previous
159- Set expiration dates for old secrets
160- Rotate secrets quarterly or after suspected compromise
161
162## Rate Limiting & DoS Prevention
163
164**Rate Limiting Strategy**:
165- Use Redis store for distributed rate limiting
166- General API: 100 requests per 15 minutes
167- Auth endpoints: 5 attempts per hour (skip successful requests)
168- Key by user ID if authenticated, otherwise IP
169- Progressive limits (authenticated users get higher limits)
170- Return 429 status with clear error message
171
172**Request Throttling**:
173- Slow down after threshold (50 requests) before blocking
174- Add incremental delays (500ms per extra request)
175- Set maximum delay (20 seconds)
176- Prevents aggressive blocking while discouraging abuse
177
178## Logging & Monitoring
179
180**Structured Logging** (use Winston or Pino):
181- Use JSON format with timestamps
182- Log levels: error, warn, info, debug
183- Include context: method, URL, status, duration, userId, IP
184- Separate error.log and combined.log files
185- Console logging in development only
186- Never log sensitive data (passwords, tokens, credit cards)
187- Sanitize objects before logging (redact sensitive fields)
188
189**Security Event Monitoring**:
190- Track critical events (failed logins, invalid tokens, permission denials)
191- Log IP, user agent, path, timestamp for all security events
192- Alert on SQL injection attempts, XSS attempts
193- Integrate with monitoring services (Sentry, DataDog, New Relic)
194- Set up alerts for suspicious patterns (multiple failed logins, rate limit exceeded)
195- Review logs regularly for anomalies
196
197## Common Vulnerabilities (OWASP Top 10)
198
199**SQL Injection**:
200- Always use parameterized queries (`$1`, `$2`) - NEVER string concatenation
201- Use ORMs (Prisma, TypeORM) for built-in protection
202
203**Cross-Site Scripting (XSS)**:
204- Sanitize HTML input (DOMPurify)
205- Escape output when rendering
206- Use Content Security Policy headers
207
208**Cross-Site Request Forgery (CSRF)**:
209- Use CSRF tokens for cookie-based auth (csurf package)
210- Set httpOnly, secure, sameSite: 'strict' on cookies
211- For JWT APIs, validate origin and use proper CORS
212
213**Insecure Deserialization**:
214- NEVER use eval() or Function() with user input
215- Use JSON.parse + schema validation only
216- Avoid vm.runInNewContext and similar
217
218**XML External Entities (XXE)**:
219- Disable external entity resolution in XML parsers
220- Use JSON instead of XML when possible
221
222**Insecure Direct Object References (IDOR)**:
223- Always verify resource ownership before returning data
224- Check `resource.userId === req.user.uuid` or admin status
225- Use UUIDs instead of sequential IDs
226
227## Testing Security
228
229**Unit Tests**:
230- Test password validation (reject weak, accept strong)
231- Test password hashing (bcrypt format, verify correct/incorrect)
232- Test authorization (401 without token, 403 without permissions)
233- Test input validation (reject malicious patterns)
234
235**Integration Tests**:
236- Test SQL injection attempts (should return 400, not all data)
237- Test rate limiting (10+ requests should trigger 429)
238- Test IDOR (users can't access others' resources)
239- Test CSRF protection on state-changing endpoints
240
241**Automated Security Scanning**:
242- `npm audit` - Check dependencies for vulnerabilities
243- `npx snyk test` - Continuous vulnerability monitoring
244- `eslint-plugin-security` - Static analysis for security issues
245- `gitleaks detect` - Check for hardcoded secrets in code
246- Run scans in CI/CD pipeline
247
248## Implementation Guidelines
249
250**IMPORTANT**: Do NOT create summary markdown files, documentation files, or README files unless explicitly requested by the user.
251
252## Best Practices
253
2541. **Never Trust User Input** - Validate, sanitize, and escape all input regardless of source
2552. **Use Parameterized Queries** - Always use prepared statements for database queries
2563. **Implement Proper Authentication** - Use industry-standard methods (JWT, OAuth) with secure configuration
2574. **Apply Principle of Least Privilege** - Grant minimum necessary permissions to users and services
2585. **Encrypt Sensitive Data** - Use encryption at rest and in transit (TLS/SSL)
2596. **Keep Dependencies Updated** - Regularly update packages and scan for vulnerabilities
2607. **Implement Rate Limiting** - Prevent abuse and DoS attacks on all endpoints
2618. **Log Security Events** - Monitor and alert on suspicious activities
2629. **Handle Errors Securely** - Never expose stack traces or internal details to clients
26310. **Use Security Headers** - Implement helmet.js and configure CSP, HSTS, etc.
26411. **Validate Environment Config** - Ensure all required secrets are present on startup
26512. **Implement Request Timeouts** - Prevent resource exhaustion from slow requests
26613. **Use HTTPS Everywhere** - Never transmit sensitive data over unencrypted connections
26714. **Implement CSRF Protection** - For cookie-based auth, use CSRF tokens
26815. **Regular Security Audits** - Conduct code reviews and penetration testing
26916. **Have an Incident Response Plan** - Prepare for security breaches before they happen
27017. **Minimize Attack Surface** - Disable unnecessary features and endpoints
27118. **Use Security Linters** - Integrate security scanning in CI/CD pipeline
27219. **Implement Proper Session Management** - Use secure, httpOnly cookies with appropriate expiration
27320. **Document Security Decisions** - Maintain a threat model and security architecture docs
274
275## References
276
277- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
278- [OWASP Cheat Sheet Series](https://cheatsheetseries.owasp.org/)
279- [Node.js Security Best Practices](https://nodejs.org/en/docs/guides/security/)
280- [Express.js Security Best Practices](https://expressjs.com/en/advanced/best-practice-security.html)
281- [CWE Top 25 Most Dangerous Software Weaknesses](https://cwe.mitre.org/top25/)
282- [NIST Cybersecurity Framework](https://www.nist.gov/cyberframework)
283- [JWT Best Practices](https://tools.ietf.org/html/rfc8725)
284- [API Security Best Practices](https://github.com/shieldfy/API-Security-Checklist)