LogoMkSaaS Docs
Deployment

Cloudflare

Learn how to deploy your project to the Cloudflare Workers platform

This guide will help you deploy your mksaas project to the Cloudflare Workers platform using OpenNext.js.

Important: Use the Cloudflare Branch

Deploying to Cloudflare Workers requires using the cloudflare branch instead of the main branch. This branch contains the necessary OpenNext.js configuration and Cloudflare-specific adaptations.

Prerequisites

Before deploying your project to Cloudflare Workers, make sure you have:

  1. A Git repository containing your project code (like GitHub)
  2. A Cloudflare account, sign up here if you don't have one
  3. PostgreSQL database (if using the default database configuration)

Note on Worker Size Limits

The size limit of a Cloudflare Worker is 3 MiB on the Workers Free plan, and 10 MiB on the Workers Paid plan. After building your Worker, wrangler will show both the original and compressed sizes:

Total Upload: 13833.20 KiB / gzip: 2295.89 KiB

Only the latter (compressed size) matters for the Worker size limit, so if your project is larger than 3 MiB, you need to subscribe to the Workers Paid plan.

Deployment Steps

Switch to the Cloudflare Branch

Clone the cloudflare branch of the MkSaaS template repository, and push the code to your new GitHub repository:

# Clone the cloudflare branch of the MkSaaS template repository
git clone -b cloudflare https://github.com/MkSaaSHQ/mksaas-template.git <your-project-name>
cd <your-project-name>

# Add the upstream repository and fetch the latest changes
git remote add upstream https://github.com/MkSaaSHQ/mksaas-template.git
git fetch upstream

# Remove the origin repository and add your new GitHub repository
git remote remove origin
git remote add origin <your-repository-url>

# Rename the branch to main and push the changes to the origin repository
git branch -M main
git push -u origin main

Install Dependencies

Install all required dependencies including Wrangler CLI:

pnpm install

This will install all dependencies including the Wrangler CLI tool needed for Cloudflare Workers deployment.

Install Wrangler CLI

Install the Wrangler CLI, and then run wrangler login to login to your Cloudflare account.

pnpm install -g wrangler

# Login to your Cloudflare account
wrangler login

Set up PostgreSQL Database

If you're using the default PostgreSQL database configuration, you'll need to set up a PostgreSQL database.

Once you have your PostgreSQL database ready, note down the connection string in this format:

postgres://user:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name

After the database is created, you need to initialize the database by following the Database Guide.

Configure Local Development Database

For local development, update the wrangler.jsonc file with your local PostgreSQL connection string:

wrangler.jsonc
{
  "hyperdrive": [
    {
      "binding": "HYPERDRIVE",
      "id": "YOUR_HYPERDRIVE_ID_HERE",
      "localConnectionString": "postgres://user:password@localhost:5432/your_local_database"
    }
  ]
}

Replace the localConnectionString with your actual local database connection string.

Configure Hyperdrive Binding

Hyperdrive accelerates database queries by pooling connections and caching requests. Create a Hyperdrive configuration for your production database:

npx wrangler hyperdrive create <NAME_OF_HYPERDRIVE_CONFIG> --connection-string="postgres://user:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name"

Replace the connection string with your actual PostgreSQL connection details. After successful creation, you'll receive a Hyperdrive ID that you can also view in your Cloudflare Dashboard.

Update the wrangler.jsonc file with your Hyperdrive ID:

wrangler.jsonc
{
  "hyperdrive": [
    {
      "binding": "HYPERDRIVE",
      "id": "YOUR_HYPERDRIVE_ID_HERE"
    }
  ]
}

Disable Hyperdrive Query Cache

  1. Go to the Cloudflare Dashboard
  2. Navigate to Storage & DatabasesHyperdrive
  3. Click on the created Hyperdrive config, navigate to Settings
  4. Click Disable Caching

Configure Environment Variables

Set up your environment variables for both development and production:

  1. For development: Copy the example files and configure them

    cp env.example .env
    cp dev.vars.example .dev.vars
  2. Configure variables: Follow the Environment Setup Guide to set up all required environment variables in .env files, and leave .dev.vars as it is for now.

There are 2 environment variables you need to take care about for local development:

  • NEXT_PUBLIC_BASE_URL: the base URL for your application, set it to http://localhost:8787 instead of http://localhost:3000 for local development, because your application will be run by opennext-cloudflare, which will automatically run on port 8787 by default.
  • DATABASE_URL: the connection string for your database, set it to the local database connection string for local development instead of the production hosted database connection string.

Set Wrangler configuration name

Set the name in wrangler.jsonc file to your project name:

wrangler.jsonc
{
  "name": "your-project-name"
}

Generate types

After configuring .env and wrangler.jsonc files, generate Cloudflare-specific types:

pnpm run cf-typegen

This command will automatically generate the cloudflare-env.d.ts file containing type definitions for the Cloudflare Worker runtime environment.

Create a Cloudflare Worker Project

  1. Go to the Cloudflare Dashboard
  2. Navigate to Compute(Workers)Workers and PagesCreateImport a repository
  3. Select your repository (use the main branch by default)
  4. Configure the build settings:
    • Name: keep the name the same as the name in wrangler.jsonc file
    • Build command: Leave empty
    • Deploy command: pnpm run deploy
    • Root directory: Leave as default
    • Build Environment Variables: add NEXT_PUBLIC_BASE_URL variable, and set it to https://<your-project-name>.<account>.workers.dev or your custom domain

Configure Environment Variables

There are two ways to configure environment variables in Cloudflare Worker:

  1. Configure the environment variables in Cloudflare Worker Dashboard
  • Go to the SettingsVariables and Secrets
  • Click + Add, and add all the environment variables in production environment
  • Click Deploy to save the variables and trigger a build and deployment
  1. Configure the environment variables with Wrangler CLI

Create a new .env.production file in your project root directory, and copy the environment variables in .env file to it:

# Copy the .env file to .env.production
cp .env .env.production

# Update the environment variables in .env.production
# For example, you need to update the NEXT_PUBLIC_BASE_URL and DATABASE_URL environment variables

# Set the environment variables in Cloudflare Worker with Wrangler CLI
# https://developers.cloudflare.com/workers/wrangler/commands/#secret-bulk
wrangler secret bulk .env.production

Deploy Your Application

You can deploy your application in two ways:

Option 1: Automatic Deployment

  • Push your changes to the main branch (main branch is the default branch)
  • Cloudflare will automatically trigger a build and deployment

Option 2: Manual Deployment

  • Deploy directly from your local machine:

    pnpm run deploy

Set up custom domains

After successful deployment, your application will be available at auto-generated domain. You can:

  • Set up custom domains, and Cloudflare will automatically create the DNS records for you
  • Monitor your application in the Cloudflare Dashboard, like the Traffic and Logs
Cloudflare Worker Deployment

Best Practices

  1. Use pnpm run dev for Local Development

    For local development, prioritize using the pnpm run dev command as it allows for faster development and debugging of your Next.js application. In this mode, code changes are reflected quickly with hot reload. If you use pnpm run preview, the project will be built first and run in production mode, meaning code changes require running pnpm run preview again to take effect.

    If your application works normally locally with pnpm run dev but behaves abnormally in production, check the production logs to analyze the issue. If production logs are hard to access, you can run pnpm run preview locally to debug the issue in a production-like environment.

    Please check out the OpenNext.js Cloudflare | Develop & Deploy for more details.

  2. Use different databases for local development and production

    You should use different databases for local development and production. For local development, you should use the Database Guide to create a local PostgreSQL instance. For production, you should use the Hosted PostgreSQL Database, like Neon or Supabase.

    Please check out the Connect to a PostgreSQL database with Cloudflare Workers for more details.

  3. Enable Worker Logs for Debugging

    By default, MkSaaS template has already enabled Observability in wrangler.jsonc. You can enable Worker logs in your project settings under the Observability section. This may require creating a new R2 storage bucket to save log data - simply follow the guided setup process on the dashboard. Once successfully enabled, you can view your application's runtime logs in the Logs tab.

    Please check out the Cloudflare Wrangler Configuration for more details.

Common Issues

  1. Build Size Too Large: If your Worker exceeds the size limit, consider:

    • Upgrading to the Workers Paid plan
    • Optimizing your bundle size
    • Removing unnecessary dependencies
  2. Database Connection Issues: Ensure your Hyperdrive configuration is correct and your PostgreSQL database is accessible.

  3. Environment Variable Issues: Make sure all environment variables are configured in both build and runtime environments in Cloudflare.

  4. Type Errors: Run pnpm run cf-types after any configuration changes to regenerate type definitions.

Reference

Video Tutorial

Next Steps

Now that you understand how to deploy your website to Cloudflare Workers, explore these related topics: