LogoMkSaaS Docs
Deployment

Cloudflare (Using D1 Database)

Learn how to deploy your project to the Cloudflare Workers platform with D1 database

This guide will help you deploy your mksaas project to the Cloudflare Workers platform with D1 database.

Important: Use the cloudflare-d1 Branch

Deploying to Cloudflare Workers requires using the cloudflare-d1 branch instead of the main branch. This branch contains the necessary OpenNext.js configuration and Cloudflare-specific adaptations, and uses D1 database by default.

If you want to use Postgres type database, please refer to Cloudflare Deployment.

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

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-d1 Branch

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

# Clone the cloudflare-d1 branch of the MkSaaS template repository
git clone -b cloudflare-d1 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

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 Wrangler configuration name

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

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

Create D1 Database

  1. Go to the Cloudflare Dashboard
  2. Navigate to Storage & DatabasesD1 Databases
  3. Click Create database
  4. Enter a database name (e.g., mksaas-demo)
  5. Select the database location (recommend choosing the region closest to your users)
  6. Click Create to create the database

After creation, note down the Database ID, which you'll need for the next configuration step.

Configure D1 Database Binding

Add D1 database configuration to the wrangler.jsonc file:

wrangler.jsonc
{
  "name": "your-project-name",
  "d1_databases": [
    {
      "binding": "DB",
      "database_name": "YOUR_DATABASE_NAME_HERE",
      "database_id": "YOUR_DATABASE_ID_HERE"
    }
  ]
}

Replace database_name with your created database name, and replace database_id with the newly created database ID.

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.

When using D1 database, you need to pay attention to the following environment variable configurations:

  • 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: when using D1 database, set DATABASE_URL to an empty string DATABASE_URL=""
  • CLOUDFLARE_ACCOUNT_ID: your Cloudflare account ID, which can be obtained from the Cloudflare Dashboard → Account Home → click next to the account name → select Copy account id
  • CLOUDFLARE_DATABASE_ID: the ID of your created D1 database, which can be found in the Cloudflare Dashboard → Storage & DatabasesD1 Databases → copy the ID next to the database name
  • CLOUDFLARE_API_TOKEN: API token for database operations, which needs to be created in Manage accountAccount API tokens → create a new API token with D1 database edit permissions and other permissions (as shown in the figure)

API Tokens

D1 database configuration example:

# For PostgreSQL(Supabase/Neon): Set DATABASE_URL and leave other D1 configuration empty
DATABASE_URL=""

# For Cloudflare D1: Leave DATABASE_URL empty and configure D1 bindings in wrangler.jsonc
CLOUDFLARE_ACCOUNT_ID="your_account_id_here"
CLOUDFLARE_DATABASE_ID="your_database_id_here"
CLOUDFLARE_API_TOKEN="your_api_token_here"

Initialize Database

After the database is created, you need to run database migrations to initialize the database structure:

pnpm db:generate
pnpm db:migrate

This command will create all necessary tables and structures according to your Drizzle ORM schema.

It is recommended to complete the database migration operation for the development database and production database by modifying the configuration in the drizzle.config.ts file.

For example, uncomment this line const isProduction = true; in drizzle.config.ts file to complete the database migration operation for the production database.

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 & AIWorkers 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 environment variable
# Note: When using D1 database, DATABASE_URL should remain an empty string

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

If there are issues running online after deployment, such as registration or login failure, you can check the build logs on Cloudflare to see if it prompts missing environment variables.

If there are missing environment variables, you can check the Worker runtime and build time environment variables in the settings, and then trigger a build again.

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 Settings

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 D1 databases for local development and production

    You should use different D1 databases for local development and production. Wrangler will automatically create a local D1 database for development, and production uses the D1 database you created in the Cloudflare Dashboard. This ensures separation between development and production data, avoiding data confusion.

    Please check out the Cloudflare D1 Documentation 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.

FAQ

  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 D1 database binding configuration is correct, and the database ID and binding name match the configuration in wrangler.jsonc. If you encounter connection issues, check Worker logs for detailed error information.

  3. Environment Variable Issues: Make sure all environment variables are configured in both Worker 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: