Skip to content

Cloudflare Deployment Guide

This guide covers deploying both the main application and documentation to Cloudflare.

Main Application Deployment

Prerequisites

  • Cloudflare account
  • Wrangler CLI installed (npm install -g wrangler)
  • KV namespaces created

Step 1: Create KV Namespaces

bash
# Create production namespaces
wrangler kv:namespace create "CHARACTERS_KV"
wrangler kv:namespace create "JOURNAL_KV"

# Create preview namespaces (for staging)
wrangler kv:namespace create "CHARACTERS_KV" --preview
wrangler kv:namespace create "JOURNAL_KV" --preview

Step 2: Update wrangler.toml

toml
name = "imperium-maledictum"
main = "worker.js"
compatibility_date = "2024-01-01"

[site]
bucket = "./dist"

[[kv_namespaces]]
binding = "CHARACTERS_KV"
id = "your-characters-kv-id"
preview_id = "your-characters-preview-id"

[[kv_namespaces]]
binding = "JOURNAL_KV"
id = "your-journal-kv-id"
preview_id = "your-journal-preview-id"

[vars]
TOKEN = "your-secret-token-here"

Step 3: Deploy to Cloudflare Workers

bash
# Build the application
npm run build

# Deploy to Cloudflare
npm run worker:deploy

Step 4: Configure Custom Domain

  1. Go to your Cloudflare dashboard
  2. Navigate to Workers & Pages
  3. Select your worker
  4. Go to Settings → Triggers
  5. Add custom domain: maledictum.jatoft.se

Documentation Deployment (VitePress)

Option 1: Cloudflare Pages Direct

  1. Build the documentation:
bash
npm run docs:build
  1. Create a new Cloudflare Pages project:
bash
cd docs/.vitepress/dist
wrangler pages deploy . --project-name=imperium-docs
  1. Configure custom domain in Cloudflare Pages dashboard:
    • Add docs.maledictum.jatoft.se

Option 2: GitHub Actions Deployment

Create .github/workflows/deploy-docs.yml:

yaml
name: Deploy Documentation

on:
  push:
    branches: [main]
    paths:
      - 'docs/**'
      - '.github/workflows/deploy-docs.yml'

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '20'
          
      - name: Install dependencies
        run: npm ci
        
      - name: Build documentation
        run: npm run docs:build
        
      - name: Deploy to Cloudflare Pages
        uses: cloudflare/pages-action@v1
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          projectName: imperium-docs
          directory: docs/.vitepress/dist
          gitHubToken: ${{ secrets.GITHUB_TOKEN }}

Option 3: Separate Worker for Docs

Create docs-worker.js:

javascript
import { getAssetFromKV } from '@cloudflare/kv-asset-handler';

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event));
});

async function handleRequest(event) {
  try {
    // Serve static assets from KV
    return await getAssetFromKV(event, {
      mapRequestToAsset: serveSinglePageApp,
    });
  } catch (e) {
    // Return 404 page
    return new Response('Not found', { status: 404 });
  }
}

function serveSinglePageApp(request) {
  const url = new URL(request.url);
  // Always serve index.html for client-side routing
  url.pathname = '/index.html';
  return new Request(url.toString(), request);
}

Environment Variables

Required Variables

  • TOKEN: Shared secret for KV storage authentication
  • CHARACTERS_KV: KV namespace binding for character data
  • JOURNAL_KV: KV namespace binding for journal entries

Setting Variables

bash
# Set production variables
wrangler secret put TOKEN

# For local development
cp .dev.vars.example .dev.vars
# Edit .dev.vars with your values

Monitoring and Debugging

Worker Analytics

  1. Go to Cloudflare dashboard
  2. Navigate to Workers & Pages
  3. Select your worker
  4. View Analytics tab

Debugging KV Storage

bash
# List all keys
wrangler kv:key list --namespace-id=your-namespace-id

# Get specific value
wrangler kv:key get "token:character:id" --namespace-id=your-namespace-id

# Delete key
wrangler kv:key delete "token:character:id" --namespace-id=your-namespace-id

Tail Worker Logs

bash
wrangler tail

Performance Optimization

Enable Caching

Add cache headers in worker:

javascript
const headers = {
  'Content-Type': 'application/json',
  'Cache-Control': 'public, max-age=3600', // 1 hour cache
};

Use Cloudflare CDN

  • Enable Auto Minify in Cloudflare dashboard
  • Configure Page Rules for static assets
  • Enable Brotli compression

Troubleshooting

Common Issues

  1. KV namespace not found

    • Verify namespace IDs in wrangler.toml
    • Ensure namespaces are created
  2. Authentication failures

    • Check TOKEN environment variable
    • Verify token in request headers
  3. Build failures

    • Clear node_modules and reinstall
    • Check Node.js version compatibility
  4. Custom domain not working

    • Verify DNS settings
    • Check SSL certificate status

Security Best Practices

  1. Rotate tokens regularly

    bash
    wrangler secret put TOKEN
  2. Use preview environments

    bash
    wrangler deploy --env preview
  3. Monitor usage

    • Set up alerts for unusual activity
    • Review access logs regularly
  4. Implement rate limiting

    • Use Cloudflare Rate Limiting rules
    • Add custom rate limiting in worker

Next Steps