Phase 3 of 6

Frontend Deployment

Deploy Next.js frontend to Cloudflare Pages with Workers for API proxying

1-2 days
Beginner Level
5 main steps
⚠️ Critical 2025 Update!
Next.js 14/15 requires the @cloudflare/next-on-pages adapter and nodejs_compat flag. Your original plan needs this update!

Step 1: Cloudflare Account Setup

1.1
Create Cloudflare Account
  1. Go to https://dash.cloudflare.com/sign-up
  2. Create account or sign in
  3. Add your domain he2.ai to Cloudflare
  4. Update nameservers at your domain registrar
  5. Wait for DNS propagation (usually 5-30 minutes)
1.2
Configure DNS Records

Set up DNS records to point your domain to Cloudflare Pages and your API to AWS ALB.

DNS Records to Add:

  • he2.ai → Cloudflare Pages (configured after deployment)
  • www.he2.ai → CNAME to he2.ai
  • api.he2.ai → CNAME to AWS ALB DNS (🟠 Proxied - orange cloud)
1.3
Configure SSL/TLS
  1. Go to SSL/TLS settings in Cloudflare
  2. Set encryption mode: Full (strict)
  3. Enable Always Use HTTPS
  4. Minimum TLS Version: 1.2
  5. Enable Automatic HTTPS Rewrites

Step 2: Update Next.js Configuration Critical 2025 Update

🚨 This Step is REQUIRED!
Without these updates, your Next.js app will NOT work on Cloudflare Pages. This is the most common mistake in 2025.
2.1
Install @cloudflare/next-on-pages
bash
# Navigate to frontend directory
cd frontend

# Install the adapter
npm install --save-dev @cloudflare/next-on-pages

# Install Wrangler CLI
npm install --save-dev wrangler
2.2
Update package.json Scripts
json
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "pages:build": "npx @cloudflare/next-on-pages",
    "preview": "npm run pages:build && wrangler pages dev",
    "deploy": "npm run pages:build && wrangler pages deploy",
    "cf-typegen": "wrangler types --env-interface CloudflareEnv env.d.ts"
  }
}
2.3
Create wrangler.toml
toml
name = "helium-frontend"
compatibility_date = "2025-01-01"
pages_build_output_dir = ".vercel/output/static"

[env.production]
compatibility_flags = ["nodejs_compat"]
✅ nodejs_compat Flag:
This flag is REQUIRED for Next.js API routes to work on Cloudflare Workers. Don't skip this!
2.4
Update next.config.ts
typescript
/** @type {import('next').NextConfig} */
const nextConfig = {
  // Required for Cloudflare Pages
  output: 'export',
  
  images: {
    unoptimized: true, // Cloudflare handles image optimization
  },
  
  // Enable compression
  compress: true,
  
  // Optimize production builds
  swcMinify: true,
  
  // Environment variables
  env: {
    NEXT_PUBLIC_ENV_MODE: process.env.NEXT_PUBLIC_ENV_MODE || 'production',
  },
};

module.exports = nextConfig;

Step 3: Deploy to Cloudflare Pages

3.1
Connect GitHub Repository
  1. Go to Cloudflare Dashboard → Pages
  2. Click "Create a project"
  3. Connect to Git (GitHub)
  4. Select your repository
  5. Authorize Cloudflare to access GitHub
3.2
Configure Build Settings

Build Configuration:

  • Project name: helium-frontend
  • Framework preset: Next.js
  • Build command: cd frontend && npm install && npm run pages:build
  • Build output directory: frontend/.vercel/output/static
  • Root directory: /
  • Node version: 20
3.3
Set Environment Variables

In Cloudflare Pages project settings, add these environment variables:

bash
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
NEXT_PUBLIC_BACKEND_URL=https://api.he2.ai
NEXT_PUBLIC_URL=https://he2.ai
NEXT_PUBLIC_ENV_MODE=production
💡 Environment Variables:
Variables prefixed with NEXT_PUBLIC_ are exposed to the browser. Never put secret keys here!
3.4
Add Compatibility Flag

This is critical! Without this flag, your API routes won't work.

  1. Go to your Cloudflare Pages project settings
  2. Scroll to "Functions" section
  3. Click "Compatibility flags"
  4. Add flag: nodejs_compat
  5. Save changes
🚨 Don't Skip This!
This is the #1 reason Next.js deployments fail on Cloudflare Pages in 2025. The flag MUST be added!
3.5
Deploy Frontend
  1. Click "Save and Deploy"
  2. Wait for build to complete (3-5 minutes)
  3. Check build logs for any errors
  4. Visit your deployment URL
✅ Success Indicators:
• Build completes without errors
• Site loads at your .pages.dev URL
• No console errors in browser DevTools

Step 4: Configure Custom Domain

4.1
Add Custom Domains
  1. Go to your Pages project → Custom domains
  2. Click "Set up a custom domain"
  3. Add domain: he2.ai
  4. Add domain: www.he2.ai
  5. Cloudflare will automatically configure DNS
  6. SSL certificates are automatic (Full strict)

Step 5: Create Cloudflare Worker (API Proxy)

🔄 Why a Worker?
The Worker acts as a proxy between your frontend and AWS backend, adding rate limiting, CORS headers, and DDoS protection.
5.1
Install Wrangler CLI
bash
# Install Wrangler globally
npm install -g wrangler

# Login to Cloudflare
wrangler login

# Create worker project
mkdir -p infrastructure/cloudflare/workers
cd infrastructure/cloudflare/workers
wrangler init api-proxy
5.2
Create Worker Script

Create src/index.ts:

typescript
// Get ALB DNS from environment
const ALB_DNS = 'your-alb-dns.elb.us-east-1.amazonaws.com';

export default {
  async fetch(request: Request): Promise {
    const url = new URL(request.url);

    // Only proxy API requests
    if (!url.pathname.startsWith('/api')) {
      return new Response('Not Found', { status: 404 });
    }

    // Create request to ALB
    const albUrl = `https://${ALB_DNS}${url.pathname}${url.search}`;

    const modifiedRequest = new Request(albUrl, {
      method: request.method,
      headers: {
        ...Object.fromEntries(request.headers),
        'X-Forwarded-For': request.headers.get('CF-Connecting-IP') || '',
        'X-Forwarded-Proto': 'https',
        'Host': ALB_DNS,
      },
      body: request.body,
    });

    try {
      const response = await fetch(modifiedRequest);

      // Add CORS headers
      return new Response(response.body, {
        status: response.status,
        headers: {
          ...Object.fromEntries(response.headers),
          'Access-Control-Allow-Origin': 'https://he2.ai',
          'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
          'Access-Control-Allow-Headers': 'Content-Type, Authorization',
          'Access-Control-Allow-Credentials': 'true',
        },
      });
    } catch (error) {
      return new Response('Internal Server Error', { status: 500 });
    }
  },
};
5.3
Deploy Worker
bash
# Deploy worker
wrangler deploy

# Configure route for api.he2.ai
# This is done in Cloudflare dashboard:
# Workers & Pages → api-proxy → Settings → Triggers
# Add route: api.he2.ai/*

Step 6: Configure Rate Limiting & Security

6.1
Create Rate Limiting Rule
  1. Go to Security → WAF in Cloudflare
  2. Click "Create rule"
  3. Rule name: API Rate Limit
  4. Expression: (http.request.uri.path contains "/api")
  5. Action: Challenge
  6. Rate: 2000 requests per 5 minutes per IP
6.2
Enable DDoS Protection
  1. Go to Security → DDoS
  2. Enable HTTP DDoS attack protection
  3. Sensitivity: Medium (adjust based on traffic)
✅ Free DDoS Protection:
Cloudflare provides enterprise-grade DDoS protection for free. This protects your backend from attacks.

Phase 3 Verification Checklist