Deploying to Cloudflare Workers: A Complete Guide

Deploying to Cloudflare Workers: A Complete Guide

Deploying to Cloudflare Workers: A Complete Guide

Cloudflare Workers provides an excellent platform for deploying modern web applications. In this guide, we’ll deploy an Astro site to Cloudflare Workers with optimal configuration.

Why Cloudflare Workers?

  • Global Edge Network - Deploy to 300+ locations worldwide
  • Fast Cold Starts - V8 isolates start in milliseconds
  • Cost Effective - Generous free tier
  • Built-in Security - DDoS protection and SSL included

Prerequisites

Before we begin, make sure you have:

# Install Wrangler CLI
npm install -g wrangler

# Login to Cloudflare
wrangler login

Project Setup

1. Install the Cloudflare Adapter

npm install @astrojs/cloudflare

2. Configure Astro

Update your astro.config.mjs:

import { defineConfig } from 'astro/config';
import cloudflare from '@astrojs/cloudflare';

export default defineConfig({
  adapter: cloudflare({
    mode: 'advanced',
  }),
  output: 'hybrid',
});

3. Create Wrangler Configuration

Create a wrangler.toml file:

name = "hacksubset-blog"
main = "dist/_worker.js/index.js"
compatibility_date = "2024-01-01"

[site]
bucket = "./dist"

[vars]
NODE_VERSION = "20"

# Optional: Add KV namespaces
# [[kv_namespaces]]
# binding = "MY_KV"
# id = "your-kv-id"

Build Script

Add these scripts to your package.json:

{
  "scripts": {
    "dev": "astro dev",
    "build": "astro build",
    "preview": "wrangler pages dev dist",
    "deploy": "astro build && wrangler pages deploy dist"
  }
}

CI/CD with GitHub Actions

Create .github/workflows/deploy.yml:

name: Deploy to Cloudflare

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    
    steps:
      - uses: actions/checkout@v4
      
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
      
      - name: Install pnpm
        uses: pnpm/action-setup@v2
        with:
          version: 8
      
      - name: Install dependencies
        run: pnpm install
      
      - name: Build
        run: pnpm build
      
      - name: Deploy
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          command: pages deploy dist --project-name=hacksubset-blog

Environment Variables

Store secrets securely:

# Add a secret
wrangler secret put API_KEY

# Or use environment variables in CI
# CLOUDFLARE_API_TOKEN in GitHub Secrets

Performance Optimization

1. Enable Compression

// middleware.ts
export async function onRequest(context) {
  const response = await context.next();
  
  if (response.headers.get('Content-Type')?.includes('text/')) {
    response.headers.set('Content-Encoding', 'gzip');
  }
  
  return response;
}

2. Cache Static Assets

# wrangler.toml
[[rules]]
globs = ["**/*.{js,css,png,jpg}"]
cache_level = "bypass"

3. Use Image Optimization

---
import { Image } from 'astro:assets';
import heroImage from '../assets/hero.jpg';
---

<Image src={heroImage} alt="Hero" width={1200} height={630} />

Monitoring and Analytics

Enable Cloudflare Analytics:

# wrangler.toml
[analytics]
enabled = true

Troubleshooting

Common Issues

Build fails with module resolution errors:

# Clear cache and reinstall
rm -rf node_modules .astro
pnpm install

Worker size exceeds limit:

  • Enable code splitting
  • Remove unused dependencies
  • Use dynamic imports

Conclusion

Cloudflare Workers provides an excellent platform for deploying Astro sites with global reach and excellent performance. Follow this guide and you’ll have your site deployed in minutes!

Happy deploying! 🚀

Comments