Cloudflare 02 ☁️ Cloudflare Pages & Git Deployments — Connecting repositories, configuring build settings, and managing Preview vs. Production deployments
Cloudflare Pages is a static site hosting platform designed for frontend developers that integrates directly with version control systems. Unlike traditional hosting where you might upload files via FTP or manually trigger a CI/CD pipeline, Cloudflare Pages treats your Git repository as the source of truth. Every push to a connected repository triggers an automated build process on Cloudflare’s global network, resulting in an instant, globally cached deployment. This platform is engineered to handle modern frameworks like React, Vue, Next.js, and static site generators like Hugo or Jekyll, managing the build environment, dependency installation, and edge distribution automatically.
The platform architecture is split into two primary environments: Production and Preview. Production is linked to your primary branch (e.g., main or master), providing the live site URL and any custom domains you have configured. Preview, by contrast, is dynamically generated for every pull request, allowing developers to test changes in a live environment that mirrors production before merging code. This workflow eliminates the “it works on my machine” problem by ensuring the build process in the cloud matches the deployment output exactly.
This chapter details the configuration lifecycle of Cloudflare Pages. We will walk through the authentication process with GitHub or GitLab, the nuance of build settings—including build commands and output directories—and the strategic management of branch deployments to ensure that your production environment remains stable while your preview environments enable rapid iteration.
Key point: Cloudflare Pages automates the entire CI/CD pipeline; it builds your site upon every Git push, enforces isolation between Preview and Production URLs, and distributes the final artifacts across the global Cloudflare edge network without any manual intervention.
Why X exists
The deployment friction problem. Historically, deploying a website involved manual file uploads, server misconfigurations, or setting up complex third-party CI/CD tools like Jenkins or CircleCI. Cloudflare Pages exists to remove this friction by providing a managed, “zero-config” pipeline that handles the heavy lifting of environment setup and deployment.
The global distribution latency problem. Statically hosting a site on a single server means users far from that server experience high latency. Cloudflare Pages solves this by building your site once and instantly distributing the artifacts to hundreds of edge data centers, ensuring that content is always served from a location physically close to the user.
The “Preview” environment demand. Testing changes requires a staging environment, which is traditionally expensive and difficult to maintain. Cloudflare Pages solves this by dynamically spinning up a unique, live URL for every single pull request, allowing teams to verify UI changes in a real-world environment before merging.
The build environment inconsistency. Developers often struggle with mismatched versions of Node.js or build dependencies between their local machine and the server. Cloudflare Pages standardizes the build environment, ensuring that the same Docker-based runner builds your site every time, eliminating build-related bugs.
The trade-off. The primary trade-off is the loss of total control over the server environment. Unlike a VPS where you can install arbitrary system packages or run background processes, Cloudflare Pages is an opinionated, restricted platform. If your application requires a custom server-side runtime, long-lived background tasks, or a persistent database on the same filesystem, Cloudflare Pages will not suffice.
a. Connecting and Authentication
Connecting your Git provider (GitHub or GitLab) is the prerequisite to using Cloudflare Pages. When you authorize Cloudflare to access your repository, you are granting it “read-only” access to your source code. Cloudflare does not require write access; it simply pulls the latest commit from your specified branch to initiate the build process.
The authorization happens via OAuth. Once connected, Cloudflare lists your repositories, and selecting one creates the project linkage. This connection is persistent; every subsequent git push sent to the connected repository sends a webhook event to Cloudflare, which then polls the repository for the latest changes and triggers the build.
# Workflow overview
1. Select Git Provider (GitHub/GitLab)
2. Authorize Cloudflare OAuth App
3. Select the target repository
4. Cloudflare monitors for webhooks
It is important to manage these permissions carefully. In an organization setting, ensure that the GitHub App integration is installed at the organization level, not just the user level, to ensure that multiple developers can trigger builds and that the project remains accessible if the original creator leaves the organization.
b. Build Settings and Frameworks
Build settings are the instructions Cloudflare uses to transform your raw code into static HTML/CSS/JS. Cloudflare is smart enough to auto-detect the framework (e.g., if it sees package.json with a next dependency, it defaults to Next.js settings), but you often need to override these for custom architectures.
The two most critical fields are the “Build Command” and the “Build Output Directory.” The Build Command is what you would run locally to build the app (e.g., npm run build or hugo). The Build Output Directory is the folder where the resulting static files reside (e.g., dist, build, .next, or public).
# Typical Build Settings
- Build command: npm run build
- Build output directory: dist/
- Node version: 18.x
Environment variables are also configured here. Cloudflare Pages distinguishes between Build-time variables (available during the build process) and Runtime variables (available to Cloudflare Functions, if enabled). Misconfiguring these is a common source of build failures; ensure that any API keys needed for the build (like a static asset base URL) are in the Build section.
c. Preview vs. Production Deployments
The environment system in Cloudflare Pages is rigid and powerful. “Production” is explicitly mapped to your primary branch (usually main). Any commit merged into this branch triggers a deployment to the production URL, which is also where any custom domains you have attached to the project will point.
“Preview” deployments are triggered by any commit to a non-production branch or any open pull request. Cloudflare generates a unique URL for every commit (e.g., 5f3a2b.project.pages.dev). This URL is immutable; it serves exactly that specific commit. These previews allow for deep linking and asynchronous code review, as stakeholders can click a link in a PR and see the live result of that specific code change.
# Deployment Logic
- Merge to Main ──► Deploys to production domain
- Push to Feature ──► Deploys to unique preview URL
When you merge a PR from a feature branch into the production branch, Cloudflare does not just “move” the preview. It triggers a new production build. This ensures that the production site always reflects the most stable version of your code, while the preview URLs serve as an infinite history of your development work.
Complete Example Session
// ============================================
// PART 1: CONNECTING THE REPO
// ============================================
// Cloudflare Dashboard > Pages > Create a project > Connect to Git
// Select: "my-awesome-site" from GitHub
// ============================================
// PART 2: INITIAL BUILD SETTINGS
// ============================================
// Framework Preset: React
// Build command: npm run build
// Build output: dist/
// ============================================
// PART 3: ADDING NODE VERSION
// ============================================
// Environment variables:
// NODE_VERSION = 18.16.0
// ============================================
// PART 4: FIRST PRODUCTION DEPLOY
// ============================================
// Cloudflare fetches source code
// Installs dependencies (npm install)
// Runs build command
// Deploys to: my-awesome-site.pages.dev
// ============================================
// PART 5: CREATING A PREVIEW BRANCH
// ============================================
git checkout -b feature/new-hero
// Change hero component...
git commit -am "Update hero section"
git push origin feature/new-hero
// ============================================
// PART 6: PREVIEW DEPLOYMENT
// ============================================
// Cloudflare detects push to feature branch
// Builds project
// Assigns URL: hero-new.my-awesome-site.pages.dev
// ============================================
// PART 7: PR INTEGRATION
// ============================================
// GitHub Action/Cloudflare App comments on PR:
// "Preview deployment ready at https://..."
// ============================================
// PART 8: MERGING TO MAIN
// ============================================
git checkout main
git merge feature/new-hero
git push origin main
// ============================================
// PART 9: PRODUCTION PROMOTION
// ============================================
// Cloudflare detects merge
// Triggers production build
// Updates my-awesome-site.pages.dev
// ============================================
// PART 10: ROLLBACK
// ============================================
// Project > Deployments > Click "..." on last build
// Select "Rollback to this deployment"
The parts above covered the connection workflow, configuring the build environment, managing the branch-to-environment mapping, and performing a rollback.
Quick Reference
Build Settings
| Setting | Purpose | Example |
|---|---|---|
| Build Command | Instruction to compile site | npm run build |
| Output Directory | Path to final assets | dist/ or .next/ |
| Node Version | Build runtime environment | 18.x |
Environment Types
| Type | Branch | URL Structure |
|---|---|---|
| Production | Main/Master | project.pages.dev |
| Preview | All others | commit-hash.project.pages.dev |
Deployment Actions
| Action | Result |
|---|---|
| Merge to Main | Automatic production deploy |
| Push to Feature | Automatic preview deploy |
| Rollback | Reverts assets to previous hash |
Best Practices
✅ Do This:
# Pin your Node version in environment variables // ✅
# Use absolute paths for assets (or public prefix) // ✅
# Always include a _redirects file for SPAs // ✅
# Use different variable scopes for Build vs Runtime // ✅
# Cleanup old branches regularly // ✅
❌ Don’t Do This:
# Rely on auto-detection for complex build logic // ❌
# Store secrets in plain text environment variables // ❌
# Forget to specify the output directory // ❌
# Push heavy binary files to your repository // ❌
# Ignore build logs when a deployment fails // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Build Fails | Mismatched Node version | Set NODE_VERSION env var |
| 404 on refresh | SPA routing missing | Add _redirects file |
| Assets not found | Wrong output directory | Update Build Output Dir setting |
| Slow builds | Massive node_modules | Cache dependencies (automatic) |
| Secrets exposed | Env vars in Git | Use Cloudflare Secrets Manager |
Real-World Examples
1. Next.js Static Export
Build command: next build && next export. Output: out/.
2. Hugo Blog
Build command: hugo. Output: public/.
3. Simple HTML/CSS
No build command required. Output: ./.
4. React Vite App
Build command: npm run build. Output: dist/.
5. Astro Site
Build command: npm run build. Output: dist/.
6. Monorepo (Turborepo)
Build command: npm run build --filter=web. Output: apps/web/dist/.
7. Docusaurus
Build command: npm run build. Output: build/.
8. Jekyll
Build command: bundle exec jekyll build. Output: _site/.
9. Nuxt.js
Build command: npm run generate. Output: .output/public/.
10. SvelteKit
Build command: npm run build. Output: build/.
Visual
The CI/CD Pipeline
┌──────────────────────────────────────────────┐
│ GIT PUSH │
│ │ │
│ ▼ │
│ [ CLOUDFLARE BUILD RUNNER ] │
│ - Install Dependencies │
│ - Run Build Command │
│ │ │
│ ▼ │
│ [ GLOBAL EDGE NETWORK ] │
│ - Deploy Files │
└──────────────────────────────────────────────┘
Branch Mapping Logic
┌──────────────────────────────────────────────┐
│ REPOSITORIES │
│ │
│ Branch: main ──────► Production Environment │
│ (Custom Domains / pages.dev) │
│ │
│ Branch: feature ───► Preview Environment │
│ (commit-hash.pages.dev) │
└──────────────────────────────────────────────┘
The Deployment Environment
┌──────────────────────────────────────────────┐
│ DEPLOYMENT SNAPSHOT (Immutable) │
│ │
│ Commit Hash: a1b2c3d4 │
│ Branch: feature-login │
│ URL: a1b2c3d4.project.pages.dev │
│ │
│ [ Always points to this specific code ] │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Primary Auth | OAuth (GitHub/GitLab) |
| Trigger | Webhook on Git Push |
| Production URL | project.pages.dev |
| Preview URL | hash.project.pages.dev |
| Build Environment | Node.js (Version configurable) |
| Asset Path | _redirects (required for SPA) |
Key takeaways:
- Cloudflare Pages is Git-integrated. It removes the need for external CI/CD tools by watching your repository and triggering builds automatically on every commit.
- Preview environments are critical. By generating a unique, live URL for every commit, Cloudflare facilitates seamless code review and testing.
- Environment settings are per-project. You must explicitly configure your build command and output directory to match your framework’s requirements.
- Production is tied to the main branch. Only merges to your primary branch trigger updates to your production domain.
- Rollbacks are instant. Because every deployment is an immutable snapshot of your build artifacts, rolling back is a simple interface action, not a re-build.
Remember: A successful Cloudflare Pages deployment is built on strict environment configuration. Pin your Node version, define your output directory correctly, and ensure your routing is handled (via _redirects for SPAs). Treat every push as a production-ready artifact, and use preview URLs to validate your changes before merging to the production branch.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!