Frontend Application (Next.js)
Complete guide to deploying and managing the Next.js frontend application with server-side rendering and optimal performance.
🏗️ Overview
Section titled “🏗️ Overview”The frontend is a modern Next.js application optimized for production deployment in Kubernetes. It provides a fast, SEO-friendly user interface with server-side rendering capabilities.
Architecture Components
Section titled “Architecture Components”Frontend Deployment:├── Next.js Container (SSR Application)├── Persistent Volume (Build Cache)├── Auto-scaling (HPA)└── Ingress (SSL/TLS)
🚀 Application Features
Section titled “🚀 Application Features”Technology Stack
Section titled “Technology Stack”- Framework: Next.js 13+ with App Router
- Runtime: Node.js 18+ LTS
- Rendering: Server-Side Rendering (SSR) and Static Generation
- Styling: Modern CSS-in-JS or Tailwind CSS
- TypeScript: Full type safety
Key Features
Section titled “Key Features”- Server-Side Rendering: Improved SEO and initial page load
- Static Generation: Pre-built pages for optimal performance
- Image Optimization: Next.js built-in image optimization
- Build Cache: Persistent volume for faster builds
- Progressive Web App: PWA capabilities enabled
🔧 Deployment Configuration
Section titled “🔧 Deployment Configuration”Container Specification
Section titled “Container Specification”frontend: image: ghcr.io/hsm00/myproject-mono/frontend:latest port: 3000 resources: requests: cpu: 300m memory: 400Mi limits: cpu: 600m memory: 2Gi
Environment Variables
Section titled “Environment Variables”The frontend uses environment variables for configuration:
Application Settings
Section titled “Application Settings”NEXT_PUBLIC_APP_URL=https://myproject.comNEXT_PUBLIC_BACKEND_URL=https://app.myproject.comNODE_ENV=production
API Configuration
Section titled “API Configuration”NEXT_PUBLIC_GOOGLE_API_KEY=[your-google-api-key]NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=[your-stripe-key]
WebSocket Configuration
Section titled “WebSocket Configuration”NEXT_PUBLIC_REVERB_HOST=app.myproject.comNEXT_PUBLIC_REVERB_APP_KEY=[your-reverb-key]NEXT_PUBLIC_REVERB_PORT=443NEXT_PUBLIC_REVERB_SCHEME=https
Health Checks
Section titled “Health Checks”Liveness Probe
Section titled “Liveness Probe”livenessProbe: httpGet: path: / port: 3000 initialDelaySeconds: 30 periodSeconds: 10
Readiness Probe
Section titled “Readiness Probe”readinessProbe: httpGet: path: / port: 3000 initialDelaySeconds: 10 periodSeconds: 5
💾 Persistent Storage
Section titled “💾 Persistent Storage”Build Cache Optimization
Section titled “Build Cache Optimization”The frontend uses a persistent volume to cache Next.js build artifacts:
persistence: enabled: true accessMode: ReadWriteOnce size: 10Gi mountPath: /app/.next/cache
Benefits:
- Faster subsequent builds
- Reduced memory usage
- Improved deployment times
- Better resource utilization
Volume Configuration
Section titled “Volume Configuration”volumes: - name: cache-volume persistentVolumeClaim: claimName: frontend-cache
volumeMounts: - name: cache-volume mountPath: /app/.next/cache
🔄 Auto-scaling
Section titled “🔄 Auto-scaling”Horizontal Pod Autoscaler
Section titled “Horizontal Pod Autoscaler”autoscaling: enabled: true minReplicas: 1 maxReplicas: 3 targetCPUUtilizationPercentage: 80 # Optional memory-based scaling targetMemoryUtilizationPercentage: 70
Scaling Behavior
Section titled “Scaling Behavior”- Scale Up: When CPU > 80% for 2 minutes
- Scale Down: When CPU < 50% for 5 minutes
- Max Surge: 1 pod at a time
- Max Unavailable: 0 (zero-downtime scaling)
Custom Metrics (Advanced)
Section titled “Custom Metrics (Advanced)”For traffic-based scaling:
behavior: scaleUp: stabilizationWindowSeconds: 120 policies: - type: Percent value: 100 periodSeconds: 60 scaleDown: stabilizationWindowSeconds: 300 policies: - type: Percent value: 50 periodSeconds: 60
🌐 Ingress & Domain Configuration
Section titled “🌐 Ingress & Domain Configuration”Domain Setup
Section titled “Domain Setup”- Primary Domain:
myproject.com
- WWW Alias:
www.myproject.com
- SSL/TLS: Automatic Let’s Encrypt certificates
Ingress Configuration
Section titled “Ingress Configuration”ingress: enabled: true className: traefik annotations: kubernetes.io/ingress.class: traefik cert-manager.io/cluster-issuer: letsencrypt traefik.ingress.kubernetes.io/router.middlewares: default-redirect-https@kubernetescrd hosts: - host: myproject.com paths: - path: / pathType: Prefix - host: www.myproject.com paths: - path: / pathType: Prefix tls: - secretName: myproject-tls hosts: - myproject.com - www.myproject.com
HTTPS Redirect Middleware
Section titled “HTTPS Redirect Middleware”Automatic HTTP to HTTPS redirection:
# Traefik middleware for HTTPS redirectapiVersion: traefik.containo.us/v1alpha1kind: Middlewaremetadata: name: redirect-httpsspec: redirectScheme: scheme: https permanent: true
🚀 Performance Optimization
Section titled “🚀 Performance Optimization”Next.js Configuration
Section titled “Next.js Configuration”Optimized Next.js configuration for production:
const nextConfig = { output: "standalone", experimental: { serverComponentsExternalPackages: [], }, images: { domains: ["static.myproject.com"], formats: ["image/webp", "image/avif"], }, compress: true, poweredByHeader: false,};
module.exports = nextConfig;
Image Optimization
Section titled “Image Optimization”// Optimized image component usageimport Image from "next/image";
<Image src="/hero-image.jpg" alt="Hero Image" width={800} height={600} priority sizes="(max-width: 768px) 100vw, 50vw"/>;
Caching Strategy
Section titled “Caching Strategy”Build-time Caching
Section titled “Build-time Caching”- Static assets with long-term caching
- Incremental Static Regeneration (ISR)
- Optimized bundle splitting
Runtime Caching
Section titled “Runtime Caching”- API response caching
- Client-side navigation caching
- Service worker for offline support
📦 Features & Integrations
Section titled “📦 Features & Integrations”SEO Optimization
Section titled “SEO Optimization”- Meta Tags: Dynamic meta tag generation
- Structured Data: JSON-LD schema markup
- Sitemap: Automatic sitemap generation
- Robots.txt: Search engine directives
Analytics Integration
Section titled “Analytics Integration”- Google Analytics: Page view tracking
- Performance Monitoring: Core Web Vitals
- User Behavior: Custom event tracking
Internationalization (i18n)
Section titled “Internationalization (i18n)”- Multi-language Support: English and German
- Locale Routing: Automatic locale detection
- Content Translation: Localized content management
PWA Features
Section titled “PWA Features”- Service Worker: Offline functionality
- App Manifest: Install prompt
- Push Notifications: User engagement
- Background Sync: Data synchronization
🚀 Deployment
Section titled “🚀 Deployment”Deploy Frontend Application
Section titled “Deploy Frontend Application”# Basic deploymenthelm upgrade --install frontend ./frontend \ --namespace production \ --create-namespace
# Deploy specific versionhelm upgrade --install frontend ./frontend \ --namespace production \ --set image.tag=v1.2.3
# Deploy with custom domainhelm upgrade --install frontend ./frontend \ --namespace production \ --set ingress.hosts[0].host=yourdomain.com
Update Application
Section titled “Update Application”# Rolling updatehelm upgrade frontend ./frontend \ --namespace production \ --set image.tag=v1.2.4 \ --wait --timeout=10m
# Force restartkubectl rollout restart deployment/frontend -n production
Verify Deployment
Section titled “Verify Deployment”# Check pod statuskubectl get pods -n production -l app.kubernetes.io/name=frontend
# Check deployment statuskubectl rollout status deployment/frontend -n production
# Test applicationcurl -I https://myproject.com
📊 Monitoring
Section titled “📊 Monitoring”Application Logs
Section titled “Application Logs”# View application logskubectl logs -f deployment/frontend -n production
# Check recent logskubectl logs --tail=100 deployment/frontend -n production
# Filter logs by levelkubectl logs deployment/frontend -n production | grep ERROR
Performance Metrics
Section titled “Performance Metrics”Key metrics to monitor:
- Response Time: Page load performance
- First Contentful Paint (FCP): Initial rendering time
- Largest Contentful Paint (LCP): Largest element rendering
- Time to Interactive (TTI): Interactivity readiness
- Cumulative Layout Shift (CLS): Visual stability
Health Monitoring
Section titled “Health Monitoring”# Application healthcurl https://myproject.com
# Check SSL certificatecurl -vI https://myproject.com 2>&1 | grep -A 2 "SSL certificate"
# Lighthouse performance checklighthouse https://myproject.com --output=json
🚨 Troubleshooting
Section titled “🚨 Troubleshooting”Common Issues
Section titled “Common Issues”1. Pod Startup Issues
Section titled “1. Pod Startup Issues”# Check pod eventskubectl describe pod frontend-xxx -n production
# Check container logskubectl logs frontend-xxx -n production
# Check resource usagekubectl top pod frontend-xxx -n production
2. Build Cache Issues
Section titled “2. Build Cache Issues”# Check persistent volumekubectl get pvkubectl describe pvc frontend-cache -n production
# Clear build cachekubectl exec -it deployment/frontend -n production -- rm -rf /app/.next/cache/*
3. SSL/Certificate Issues
Section titled “3. SSL/Certificate Issues”# Check certificate statuskubectl get certificate -n productionkubectl describe certificate myproject-tls -n production
# Check cert-manager logskubectl logs -f deployment/cert-manager -n cert-manager
4. Performance Issues
Section titled “4. Performance Issues”# Check HPA statuskubectl get hpa -n productionkubectl describe hpa frontend -n production
# Monitor resource usagekubectl top pods -n production -l app.kubernetes.io/name=frontend
Debug Commands
Section titled “Debug Commands”# Interactive shellkubectl exec -it deployment/frontend -n production -- sh
# Check Next.js buildkubectl exec -it deployment/frontend -n production -- ls -la /app/.next
# Verify environment variableskubectl exec -it deployment/frontend -n production -- env | grep NEXT_PUBLIC
🔒 Security
Section titled “🔒 Security”Content Security Policy
Section titled “Content Security Policy”const securityHeaders = [ { key: "Content-Security-Policy", value: "default-src 'self'; script-src 'self' 'unsafe-eval' 'unsafe-inline'; style-src 'self' 'unsafe-inline';", }, { key: "X-Frame-Options", value: "DENY", }, { key: "X-Content-Type-Options", value: "nosniff", },];
module.exports = { async headers() { return [ { source: "/(.*)", headers: securityHeaders, }, ]; },};
Environment Variable Security
Section titled “Environment Variable Security”# Sensitive variables (use Kubernetes Secrets)NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY # Safe (public)STRIPE_SECRET_KEY # Dangerous (use Secret)NEXT_PUBLIC_GOOGLE_API_KEY # Safe (public, restricted)
Network Security
Section titled “Network Security”- HTTPS Only: All traffic encrypted
- HSTS Headers: HTTP Strict Transport Security
- Secure Cookies: HttpOnly and Secure flags
📝 Configuration Examples
Section titled “📝 Configuration Examples”Custom Values File
Section titled “Custom Values File”image: tag: "v1.2.3"
autoscaling: enabled: true minReplicas: 2 maxReplicas: 5
resources: requests: cpu: 500m memory: 800Mi limits: cpu: 1000m memory: 2Gi
ingress: hosts: - host: yourdomain.com - host: www.yourdomain.com
Environment-Specific Deployment
Section titled “Environment-Specific Deployment”# Production deploymenthelm upgrade --install frontend-prod ./frontend \ --namespace production \ --values values-production.yaml
# Staging deploymenthelm upgrade --install frontend-staging ./frontend \ --namespace staging \ --values values-staging.yaml \ --set ingress.hosts[0].host=staging.yourdomain.com
🔄 Maintenance
Section titled “🔄 Maintenance”Regular Tasks
Section titled “Regular Tasks”- Monitor application performance
- Check error rates and logs
- Verify SSL certificate status
Weekly
Section titled “Weekly”- Update dependencies
- Review performance metrics
- Check build cache utilization
Monthly
Section titled “Monthly”- Security updates
- Performance optimization
- Capacity planning review
Backup & Recovery
Section titled “Backup & Recovery”# Configuration backupkubectl get configmap frontend-config -o yaml > backup-frontend-config.yaml
# Persistent volume backupkubectl create job --from=cronjob/backup-pvc backup-frontend-cache
# Restore configurationkubectl apply -f backup-frontend-config.yaml
🎨 Customization
Section titled “🎨 Customization”Theming and Branding
Section titled “Theming and Branding”// Update branding in layout.tsxexport const metadata = { title: "Your SaaS Application", description: "Your application description", icons: { icon: "/favicon.ico", shortcut: "/favicon-16x16.png", apple: "/apple-touch-icon.png", },};
Custom Components
Section titled “Custom Components”// Add custom components to src/components/export interface CustomButtonProps { variant: 'primary' | 'secondary' children: React.ReactNode}
export const CustomButton: React.FC<CustomButtonProps> = ({ variant, children}) => { return ( <button className={`btn btn-${variant}`}> {children} </button> )}
🔗 Related Documentation
Section titled “🔗 Related Documentation”- Backend Application - Laravel API integration
- Configuration Guide - Environment setup
- Certificate Management - SSL/TLS configuration
- Monitoring - Performance tracking
The Next.js frontend provides a modern, performant user interface optimized for SEO and user experience.