Vibe-to-Production: AI Code Production Hardening
Transform rapidly prototyped AI-generated code into secure, maintainable, production-grade applications.
Critical Context
AI-generated code introduces vulnerabilities at alarming rates:
- •45% of AI-generated code contains security flaws (Veracode 2025)
- •72% failure rate for Java, 86% Cross-Site Scripting vulnerability rate
- •Common issues: missing input validation, SQL injection, XSS, hardcoded secrets, authentication bypasses
Production Readiness Workflow
Execute phases in order. Each phase builds on previous fixes.
Phase 1: Security Hardening (CRITICAL - Do First)
See references/security-checklist.md for detailed vulnerability patterns and fixes.
Immediate Actions:
- •Scan for secrets - Search codebase for API keys, passwords, tokens
- •Input validation - Add validation to ALL user inputs, API parameters
- •Output encoding - Escape ALL dynamic content rendered in HTML
- •Authentication - Verify auth on every protected route/API endpoint
- •SQL/NoSQL injection - Use parameterized queries, never string concatenation
- •Dependency audit - Run
npm audit/pip-audit/ equivalent
Environment Security:
# Never commit secrets - use .env files and verify .gitignore echo ".env*" >> .gitignore echo "*.pem" >> .gitignore echo "*_secret*" >> .gitignore
Phase 2: Code Quality & Architecture
See references/code-quality-checklist.md for detailed patterns.
Structure Improvements:
- •Remove dead code - Delete unused components, functions, imports
- •Extract constants - No magic numbers/strings in code
- •Component decomposition - Split large components (>300 lines)
- •Error boundaries - Wrap sections that can fail independently
- •Type safety - Add TypeScript types, Zod validation schemas
- •Consistent patterns - Standardize naming, file structure, imports
AI Code Anti-Patterns to Fix:
- •2.4x more abstraction layers than necessary - flatten architecture
- •Hallucinated dependencies - verify every package exists in registry
- •Overly complex solutions - simplify when possible
- •Missing edge case handling - add defensive code
Phase 3: Performance Optimization
See references/performance-checklist.md for Core Web Vitals optimization.
Critical Metrics (2025 Targets):
- •LCP (Largest Contentful Paint): < 2.5s
- •INP (Interaction to Next Paint): < 200ms
- •CLS (Cumulative Layout Shift): < 0.1
Quick Wins:
- •Images - Use WebP/AVIF, lazy loading, explicit dimensions
- •Code splitting - Dynamic imports for non-critical components
- •Bundle analysis - Identify and remove bloated dependencies
- •Caching - Implement proper cache headers, service workers
- •Fonts - Use
font-display: swap, subset fonts - •Third-party scripts - Defer/async, consider Partytown for web workers
React/Next.js Specific:
// Dynamic import for heavy components
const HeavyChart = dynamic(() => import('./Chart'), {
loading: () => <Skeleton />,
ssr: false
});
// Image optimization
<Image src={img} width={800} height={600} priority={aboveFold} />
Phase 4: Testing Implementation
See references/testing-strategy.md for comprehensive testing patterns.
Testing Pyramid (Target Distribution):
- •70% Unit tests - Individual functions, utilities
- •20% Integration tests - Component interactions, API routes
- •10% E2E tests - Critical user journeys only
Minimum Viable Test Suite:
- •Auth flows (login, logout, password reset)
- •Payment/checkout if applicable
- •Core business logic functions
- •API endpoint validation
- •Form submissions
Tools Recommendation:
- •Unit/Integration: Vitest or Jest + Testing Library
- •E2E: Playwright (best cross-browser) or Cypress
- •API: Supertest or native fetch testing
Phase 5: SEO & Accessibility
See references/seo-accessibility-checklist.md for comprehensive requirements.
SEO Essentials:
- •Meta tags (title, description, Open Graph)
- •Semantic HTML (h1-h6 hierarchy, landmarks)
- •Structured data (JSON-LD schema markup)
- •Sitemap.xml and robots.txt
- •Canonical URLs for duplicate content
- •Mobile-first responsive design
Accessibility (WCAG 2.2):
- •Color contrast ratio ≥ 4.5:1 for text
- •Keyboard navigation (all interactive elements)
- •ARIA labels for non-text content
- •Focus indicators visible
- •Alt text for images
- •Screen reader testing
Phase 6: Error Handling & Monitoring
See references/error-monitoring-checklist.md for production setup.
Error Handling Patterns:
// Global error boundary
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
logErrorToService(error, info.componentStack);
}
render() {
if (this.state.hasError) {
return <FallbackUI onRetry={() => this.setState({ hasError: false })} />;
}
return this.props.children;
}
}
// API error handling
async function fetchData(url) {
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (error) {
logger.error('Fetch failed', { url, error: error.message });
throw new UserFacingError('Unable to load data. Please try again.');
}
}
Logging Requirements:
- •Structured JSON format
- •Log levels: DEBUG, INFO, WARN, ERROR, FATAL
- •Never log PII, passwords, tokens
- •Include request IDs for tracing
- •Centralized aggregation (Sentry, LogRocket, Datadog)
Phase 7: Deployment Preparation
Pre-Launch Checklist:
- •Environment variables properly configured
- •Database migrations tested
- •SSL/HTTPS enforced
- •Security headers set (CSP, HSTS, X-Frame-Options)
- •Rate limiting on APIs
- •Backup strategy documented
- •Rollback procedure tested
- •Monitoring/alerting configured
Security Headers (nginx/vercel.json example):
{
"headers": [
{
"source": "/(.*)",
"headers": [
{ "key": "X-Content-Type-Options", "value": "nosniff" },
{ "key": "X-Frame-Options", "value": "DENY" },
{ "key": "X-XSS-Protection", "value": "1; mode=block" },
{ "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" },
{ "key": "Permissions-Policy", "value": "camera=(), microphone=(), geolocation=()" }
]
}
]
}
Quick Audit Script
Run this to identify common issues:
# Security scan
npm audit --audit-level=high
grep -rn "password\|secret\|api_key\|token" --include="*.{js,ts,jsx,tsx,json}" . | grep -v node_modules | grep -v ".env"
# Unused dependencies
npx depcheck
# Bundle size analysis
npx @next/bundle-analyzer # or webpack-bundle-analyzer
# Lighthouse audit
npx lighthouse http://localhost:3000 --output=json --output-path=./lighthouse.json
Output Deliverables
After production hardening, provide:
- •Security fixes implemented (with before/after)
- •Performance metrics comparison
- •Test coverage summary
- •Remaining technical debt items
- •Monitoring dashboard setup
- •Deployment instructions