Deployment

Complete guide to deploying MegaVault to production environments with best practices for security, performance, and reliability.

Deployment Overview

MegaVault can be deployed to various platforms including Vercel, Docker containers, and traditional VPS servers. This guide covers the most common deployment scenarios.

Vercel (Recommended)

Serverless deployment

  • ✅ Zero configuration
  • ✅ Automatic HTTPS
  • ✅ Global CDN
  • ✅ Preview deployments

Docker

Containerized deployment

  • ✅ Consistent environments
  • ✅ Easy scaling
  • ✅ Self-hosted control
  • ✅ Container orchestration

VPS/Cloud

Traditional hosting

  • ✅ Full server control
  • ✅ Custom configurations
  • ✅ Cost effective scaling
  • ✅ Direct access
💡

Deployment Requirements

Before deploying, ensure you have:
  • Production Redis database (Upstash recommended)
  • S3-compatible storage (Cloudflare R2 or AWS S3)
  • Domain name with SSL certificate
  • Environment variables configured

Production Environment

Setting up production services and dependencies for optimal performance and security.

Database Setup

Upstash Redis

  • Create Account: Sign up at upstash.com
  • Create Database: Choose your region
  • Get Connection: Copy Redis URL
  • Configure TLS: Enable secure connections

Self-Hosted Redis

  • Install Redis: Latest stable version
  • Configure Auth: Set strong password
  • Enable Persistence: RDB + AOF
  • Setup Monitoring: Redis insights

Storage Configuration

Cloudflare R2 Setup
# Create R2 bucket
wrangler r2 bucket create megavault-production

# Configure CORS
wrangler r2 bucket cors put megavault-production --file cors.json

# Generate API tokens with R2 permissions
# Account ID, Access Key ID, Secret Access Key

SSL and Security

  • HTTPS Only: Enforce SSL/TLS for all connections
  • Security Headers: Configure CSP, HSTS, and other headers
  • API Rate Limiting: Implement rate limiting for API endpoints
  • Input Validation: Validate all user inputs

Vercel Deployment

Vercel provides the easiest deployment experience with automatic builds and deployments.

Setup Process

1

Prepare Production Build

Build and optimize the application for production.

# Install dependencies
npm ci --production

# Build the application
npm run build

# Test production build locally
npm start
2

Configure Environment

Set up production environment variables.

# Production environment variables
NEXTAUTH_URL=https://your-domain.com
NEXTAUTH_SECRET=your-production-secret
REDIS_URL=your-redis-connection-string
R2_ACCOUNT_ID=your-r2-account-id
R2_ACCESS_KEY_ID=your-access-key
R2_SECRET_ACCESS_KEY=your-secret-key
3

Deploy to Platform

Deploy using your preferred platform (Vercel, Docker, etc.).

# Vercel deployment
vercel --prod

# Docker deployment
docker build -t megavault .
docker run -p 3000:3000 megavault

Vercel Configuration

vercel.json
{
  "buildCommand": "npm run build",
  "outputDirectory": ".next",
  "installCommand": "npm ci",
  "framework": "nextjs",
  "functions": {
    "app/api/**/*.ts": {
      "maxDuration": 30
    }
  },
  "headers": [
    {
      "source": "/(.*)",
      "headers": [
        {
          "key": "X-Content-Type-Options",
          "value": "nosniff"
        },
        {
          "key": "X-Frame-Options",
          "value": "DENY"
        },
        {
          "key": "X-XSS-Protection",
          "value": "1; mode=block"
        }
      ]
    }
  ]
}

Environment Variables

Vercel Environment Setup
# Add environment variables via Vercel dashboard or CLI
vercel env add NEXTAUTH_URL production
vercel env add NEXTAUTH_SECRET production
vercel env add REDIS_URL production
vercel env add R2_ACCOUNT_ID production
vercel env add R2_ACCESS_KEY_ID production
vercel env add R2_SECRET_ACCESS_KEY production

# Deploy with environment variables
vercel --prod

Custom Domain

  1. Add Domain: Add your custom domain in Vercel dashboard
  2. Configure DNS: Point your domain to Vercel's nameservers
  3. SSL Certificate: Automatic SSL certificate provisioning
  4. Redirects: Configure www to non-www redirects

Docker Deployment

Containerized deployment provides consistency across environments and easy scaling.

Dockerfile

Dockerfile
FROM node:18-alpine AS base

# Install dependencies only when needed
FROM base AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --only=production

# Rebuild the source code only when needed
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

# Production image, copy all the files and run next
FROM base AS runner
WORKDIR /app

ENV NODE_ENV production

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000
ENV PORT 3000

CMD ["node", "server.js"]

Docker Compose

docker-compose.prod.yml
version: '3.8'

services:
  megavault:
    build: .
    ports:
      - "3000:3000"
    environment:
      - NEXTAUTH_URL=https://your-domain.com
      - NEXTAUTH_SECRET=${NEXTAUTH_SECRET}
      - REDIS_URL=${REDIS_URL}
      - R2_ACCOUNT_ID=${R2_ACCOUNT_ID}
      - R2_ACCESS_KEY_ID=${R2_ACCESS_KEY_ID}
      - R2_SECRET_ACCESS_KEY=${R2_SECRET_ACCESS_KEY}
    restart: unless-stopped
    depends_on:
      - redis

  redis:
    image: redis:alpine
    volumes:
      - redis_data:/data
    restart: unless-stopped

  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
      - ./ssl:/etc/nginx/ssl
    depends_on:
      - megavault
    restart: unless-stopped

volumes:
  redis_data:

Deployment Commands

Docker Deployment
# Build and start containers
docker-compose -f docker-compose.prod.yml up -d

# Check logs
docker-compose logs -f megavault

# Update deployment
docker-compose pull
docker-compose -f docker-compose.prod.yml up -d --no-deps megavault

# Scale application
docker-compose -f docker-compose.prod.yml up -d --scale megavault=3

Environment Configuration

Proper environment configuration is crucial for security and functionality in production.

Required Environment Variables

Production .env
# Application
NODE_ENV=production
NEXTAUTH_URL=https://your-domain.com
NEXTAUTH_SECRET=your-very-long-random-secret-here

# Database
REDIS_URL=rediss://username:password@host:port

# Storage (Cloudflare R2)
R2_ACCOUNT_ID=your-account-id
R2_ACCESS_KEY_ID=your-access-key-id
R2_SECRET_ACCESS_KEY=your-secret-access-key
R2_BUCKET_NAME=megavault-production
R2_ENDPOINT=https://your-account-id.r2.cloudflarestorage.com

# Optional
NEXT_PUBLIC_APP_URL=https://your-domain.com
SMTP_HOST=smtp.your-provider.com
SMTP_PORT=587
SMTP_USER=your-smtp-user
SMTP_PASS=your-smtp-password

Security Configuration

next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'standalone',
  poweredByHeader: false,
  compress: true,
  headers: async () => [
    {
      source: '/(.*)',
      headers: [
        {
          key: 'X-DNS-Prefetch-Control',
          value: 'on'
        },
        {
          key: 'Strict-Transport-Security',
          value: 'max-age=63072000; includeSubDomains; preload'
        },
        {
          key: 'X-Content-Type-Options',
          value: 'nosniff'
        },
        {
          key: 'X-Frame-Options',
          value: 'DENY'
        },
        {
          key: 'Referrer-Policy',
          value: 'strict-origin-when-cross-origin'
        }
      ]
    }
  ]
};

module.exports = nextConfig;

Monitoring & Logging

Implement comprehensive monitoring and logging for production deployments.

Application Monitoring

Performance Monitoring

  • Vercel Analytics: Built-in performance metrics
  • Google Analytics: User behavior tracking
  • Sentry: Error tracking and monitoring
  • Uptime Robot: Service availability monitoring

Infrastructure Monitoring

  • Server Resources: CPU, memory, disk usage
  • Database Health: Redis connection and performance
  • Storage Usage: R2/S3 usage and costs
  • API Performance: Response times and error rates

Logging Configuration

logger.ts
import pino from 'pino';

export const logger = pino({
  level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
  transport: process.env.NODE_ENV === 'development' ? {
    target: 'pino-pretty',
    options: {
      colorize: true
    }
  } : undefined,
  formatters: {
    level: (label) => {
      return { level: label };
    },
  },
});

Health Checks

health-check.ts
// app/api/health/route.ts
import { redis } from '@/lib/redis';

export async function GET() {
  try {
    // Check Redis connection
    await redis.ping();
    
    // Check storage connection
    // Add storage health check here
    
    return Response.json({
      status: 'healthy',
      timestamp: new Date().toISOString(),
      services: {
        redis: 'up',
        storage: 'up'
      }
    });
  } catch (error) {
    return Response.json({
      status: 'unhealthy',
      error: error.message
    }, { status: 503 });
  }
}

Maintenance & Updates

Regular maintenance and update procedures for production deployments.

Update Process

  1. Backup Data: Create backups of Redis and configuration
  2. Test Updates: Deploy to staging environment first
  3. Monitor Deployment: Watch for errors during rollout
  4. Rollback Plan: Be prepared to rollback if issues occur

Backup Strategy

Backup Script
#!/bin/bash
# backup.sh

DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/backups/megavault"

# Create backup directory
mkdir -p $BACKUP_DIR

# Backup Redis data
redis-cli --rdb $BACKUP_DIR/redis_backup_$DATE.rdb

# Compress backup
gzip $BACKUP_DIR/redis_backup_$DATE.rdb

# Clean old backups (keep 30 days)
find $BACKUP_DIR -name "*.gz" -mtime +30 -delete

echo "Backup completed: $DATE"

Performance Optimization

  • CDN Configuration: Use CDN for static assets
  • Image Optimization: Optimize images with Next.js Image component
  • Bundle Analysis: Regularly analyze bundle size
  • Database Optimization: Monitor and optimize Redis usage
⚠️

Production Checklist

Before going live, verify:
  • All environment variables are set correctly
  • SSL certificates are valid and auto-renewing
  • Monitoring and alerting are configured
  • Backup procedures are tested and automated
  • Performance benchmarks meet requirements