LogoNEXTDEVKIT Docs

Cloudflare Workers

Deploy NEXTDEVKIT to Cloudflare Workers with OpenNext.js for global edge performance

Deploy your NEXTDEVKIT application to Cloudflare Workers, the most cost-effective platform for global edge deployment. Cloudflare Workers provide excellent performance with built-in CDN and ultra-low latency worldwide.

🎯 Why Choose Cloudflare Workers

  • Most Cost-Effective: Extremely affordable with pay-per-request pricing
  • Global Edge Network: Deploy to 300+ locations worldwide with ~10ms cold start
  • Built-in CDN: Global content delivery network included
  • Zero Egress Fees: No bandwidth charges for outbound traffic
  • Generous Free Tier: 100,000 requests/day on free plan

📋 Prerequisites

Before deploying your NEXTDEVKIT project, ensure you have:

  • Cloudflare Account: Sign up here if you don't have one
  • Clouflare Worker Standard Plan ($5/Month): Because of the worker size 3 MB limitation of the free plan, you need to upgrade to the standard plan.
  • Environment Variables: Production environment variables ready (see Environment Guide)

🚀 Deployment Steps

Step 1: Configure Environment Variables

Please refer to the Environment Guide for the detailed environment variables.

Copy .env.example to .env.production and update the environment variables.

Step 2: Configure Wrangler Configuration

Update your wrangler.jsonc file in the project root.

{
    "account_id": "your-account-id",
    "name": "your-worker-name",
}

If you change the worker name, you also need to update the wrangler.jsonc services binding to the new worker name.

"services": [
    {
        "binding": "WORKER_SELF_REFERENCE",
        "service": "your-worker-name"
    }
]

Step 3: Configure D1 Database

Create a new D1 database for your NEXTDEVKIT project in the production environment:

# Create D1 database
pnpm wrangler d1 create prod-d1-tutorial

Expected Output:

   ✅ Successfully created DB 'prod-d1-tutorial' in region WEUR
   Created your new D1 database.

   {
     "d1_databases": [
       {
         "binding": "DB",
         "database_name": "prod-d1-tutorial",
         "database_id": "<unique-ID-for-your-database>"
       }
     ]
   }

Step 4: Create KV Namespace

Create a KV namespace for caching and session storage:

# Create KV namespace
pnpm wrangler kv namespace create nextdevkit-cloudflare-template-kv

Expected Output:

🌀 Creating namespace with title "USERS_NOTIFICATION_CONFIG"
✨ Success!
Add the following to your configuration file in your kv_namespaces array:
{
  "kv_namespaces": [
    {
      "binding": "USERS_NOTIFICATION_CONFIG",
      "id": "<BINDING_ID>"
    }
  ]
}

Step 5: Configure wrangler.jsonc

Update your wrangler.jsonc file with the database and KV configuration:

// wrangler.jsonc
{
  "name": "nextdevkit-cloudflare-template",
  "compatibility_flags": ["nodejs_compat"],
  
  // D1 Database Configuration
  "d1_databases": [
    {
      "binding": "NEXT_TAG_CACHE_D1",
      "database_name": "your-database-name",
      "database_id": "<unique-ID-for-your-database>",
      "migrations_dir": "drizzle"
    }
  ],
  
  // KV Namespace Configuration
  "kv_namespaces": [
    {
      "binding": "NEXT_INC_CACHE_KV",
      "id": "<unique-ID-for-your-namespace>"
    }
  ],
}

Step 6: Initialize D1 Database In the Local Environment

Initialize D1 database in local development environment:

# Create local D1 database
npx wrangler d1 execute your-database-name --local --command='SELECT 1'

Reference: For detailed database setup, see the Database Guide.

Step 7: Deploy to Cloudflare

pnpm install

# Login to your Cloudflare account
pnpm wrangler login

# Check your account id
pnpm wrangler whoami

# Build the project
pnpm run build:prod

# Database migration
pnpm run db:migrate:prod

# Deploy to production
pnpm run deploy

🌐 Important: Domain Configuration

Scenario 1: You Already Have a Domain (e.g., workers.nextdevkit.com)

If you already own a domain that you want to use:

  1. Set environment variables to your final domain:

    BETTER_AUTH_URL="https://workers.nextdevkit.com"
    NEXT_PUBLIC_APP_URL="https://workers.nextdevkit.com"
  2. Deploy the application with these settings

  3. Bind your domain in the Cloudflare dashboard:

    • Go to your worker in the Cloudflare dashboard
    • Navigate to "Settings" → "Domains & Routes"
    • Add your custom domain under "Custom Domain"

Scenario 2: You Don't Have a Domain Yet

If you don't have a domain and want to use Cloudflare's auto-generated domain:

  1. Use placeholder values for initial deployment:

    BETTER_AUTH_URL="https://placeholder.workers.dev"
    NEXT_PUBLIC_APP_URL="https://placeholder.workers.dev"
  2. Deploy the application - Cloudflare will automatically assign you a domain like your-worker-name.your-subdomain.workers.dev

  3. Update environment variables with the assigned domain:

    BETTER_AUTH_URL="https://your-worker-name.your-subdomain.workers.dev"
    NEXT_PUBLIC_APP_URL="https://your-worker-name.your-subdomain.workers.dev"
  4. Redeploy the application with the correct domain

⚠️ Important: If you configuring the error domain, login redirects will not work properly because the authentication system needs the correct domain URLs.

🔧 Database Migration

Run Migrations

# Generate migration files
pnpm run db:generate

# Apply migrations to development
pnpm run db:migrate:dev

# Apply migrations to production
pnpm run db:migrate:prod

Run Drizzle Studio in your local machine

npx wrangler d1 execute your-database-name --local --command='SELECT 1'

pnpm run db:studio

Database Management

# Clean D1 cache
pnpm run d1:cache:clean

# Manage KV storage
pnpm run list:kv
pnpm run delete:kv

Known Issues

In the local environment, run pnpm dev will throw the following error:

 Compiled middleware in 256ms
 [WARNING]                             You have defined bindings to the following internal Durable Objects:

                                - {"name":"NEXT_CACHE_DO_QUEUE","class_name":"DOQueueHandler"}
                                These will not work in local development, but they should work in production.
  
                                If you want to develop these locally, you can define your DO in a separate Worker, with a
  separate configuration file.
                                For detailed instructions, refer to the Durable Objects section here:
  https://developers.cloudflare.com/workers/wrangler/api#supported-bindings


 Ready in 1478ms
 [WARNING]                             You have defined bindings to the following internal Durable Objects:

                                - {"name":"NEXT_CACHE_DO_QUEUE","class_name":"DOQueueHandler"}
                                These will not work in local development, but they should work in production.
  
                                If you want to develop these locally, you can define your DO in a separate Worker, with a
  separate configuration file.
                                For detailed instructions, refer to the Durable Objects section here:
  https://developers.cloudflare.com/workers/wrangler/api#supported-bindings


workerd/server/server.c++:1873: warning: A DurableObjectNamespace in the config referenced the class "DOQueueHandler", but no such Durable Object class is exported from the worker. Please make sure the class name matches, it is exported, and the class extends 'DurableObject'. Attempts to call to this Durable Object class will fail at runtime, but historically this was not a startup-time error. Future versions of workerd may make this a startup-time error.
workerd/server/server.c++:1873: warning: A DurableObjectNamespace in the config referenced the class "DOQueueHandler", but no such Durable Object class is exported from the worker. Please make sure the class name matches, it is exported, and the class extends 'DurableObject'. Attempts to call to this Durable Object class will fail at runtime, but historically this was not a startup-time error. Future versions of workerd may make this a startup-time error.

This Issue is an known issue of OpenNext, you can follow the OpenNext issue for more details.

The warning can be safely ignored as the caching Durable Objects are not used during the build.

📊 Analytics

  • Monitor performance in Cloudflare Dashboard
  • Track request patterns and errors
  • View global traffic distribution
  • Monitor database performance

🚨 Common Issues and Solutions

Build Failures

Issue: Build process fails during deployment

Solutions:

  • Ensure Node.js version is 20+
  • Check all dependencies are installed
  • Verify wrangler.jsonc configuration
  • Clear build cache: rm -rf .next .open-next

Database Connection Issues

Issue: Cannot connect to D1 database

Solutions:

  • Verify database ID in wrangler.jsonc
  • Check binding names match code usage
  • Ensure migrations are applied

Reference: For database troubleshooting, see the Database Guide.

Environment Variable Issues

Issue: Environment variables not working

Solutions:

  • Use wrangler secret put for sensitive values
  • Check variable names are correct
  • Verify .dev.vars for local development
  • Ensure NEXT_PUBLIC_ prefix for client-side variables

Performance Issues

Issue: Slow response times

Solutions:

  • Enable Smart Placement in wrangler.jsonc
  • Implement proper caching strategies
  • Optimize bundle size
  • Use KV for frequently accessed data

🎉 Next Steps

After successful deployment:

  1. Test Your Application: Verify all features work correctly
  2. Set Up Monitoring: Configure error tracking and analytics
  3. Configure Custom Domain: Set up your own domain
  4. Optimize Performance: Implement caching and optimization strategies
  5. Scale Resources: Upgrade as your application grows

🔗 Useful Resources

Ready to deploy your NEXTDEVKIT application to Cloudflare Workers? Follow the steps above and experience the power of global edge computing! 🌍⚡