Published on

How to Deploy Your Next.js Blog to Cloudflare Pages

Authors

Cloudflare Pages is an excellent platform for hosting static sites and JAMstack applications. In this guide, I'll walk you through deploying a Next.js blog (like this one) to Cloudflare Pages with automatic deployments from GitHub.

Why Choose Cloudflare Pages?

Before diving into the deployment process, let's understand why Cloudflare Pages is a great choice for hosting your Next.js blog:

  • Global CDN: Your site is automatically distributed across Cloudflare's global network
  • Free SSL: Automatic HTTPS with Let's Encrypt certificates
  • Lightning Fast: Excellent performance with edge caching
  • Git Integration: Automatic deployments from GitHub, GitLab, or Bitbucket
  • Custom Domains: Easy setup with your own domain
  • Analytics: Built-in web analytics without external tracking

Prerequisites

Before we start, make sure you have:

  • A Next.js project pushed to a GitHub repository
  • A Cloudflare account (free tier is sufficient)
  • Your project configured for static export (if needed)

Step 1: Configure Your Next.js Project for Static Export

For Cloudflare Pages, you need to configure your Next.js project to generate static files. Add this to your next.config.js:

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'export',
  trailingSlash: true,
  images: {
    unoptimized: true,
  },
}

module.exports = nextConfig

Update your build script in package.json:

{
  "scripts": {
    "build": "next build",
    "export": "next export"
  }
}

Step 2: Connect Your Repository to Cloudflare Pages

  1. Log into Cloudflare Dashboard

  2. Create a New Project

    • Click "Create a project"
    • Choose "Connect to Git"
    • Select your Git provider (GitHub, GitLab, or Bitbucket)
  3. Authorize Cloudflare

    • Grant Cloudflare access to your repositories
    • You can choose specific repositories or all repositories
  4. Select Your Repository

    • Choose the repository containing your Next.js blog
    • Click "Begin setup"

Step 3: Configure Build Settings

Configure the deployment settings for your Next.js project:

Build command: npm run build
Build output directory: out
Root directory: /
Node.js version: 18.x

Environment Variables

If your blog uses environment variables, add them in the "Environment variables" section:

NODE_ENV=production
NEXT_PUBLIC_SITE_URL=https://yourdomain.com

Step 4: Deploy Your Site

  1. Review Settings

    • Double-check your build configuration
    • Ensure the branch is set correctly (usually main or master)
  2. Save and Deploy

    • Click "Save and Deploy"
    • Cloudflare will start building your site
    • The first deployment usually takes 2-5 minutes
  3. Monitor the Build

    • Watch the build logs for any errors
    • Common issues include missing dependencies or build failures

Step 5: Configure Custom Domain (Optional)

To use your own domain instead of the .pages.dev subdomain:

  1. Add Custom Domain

    • Go to your project in Cloudflare Pages
    • Click "Custom domains" tab
    • Click "Set up a custom domain"
  2. DNS Configuration

    • Add a CNAME record pointing to your .pages.dev domain
    • Or use Cloudflare as your DNS provider for automatic configuration
  3. SSL Certificate

    • Cloudflare automatically provisions SSL certificates
    • Your site will be available over HTTPS within minutes

Step 6: Set Up Automatic Deployments

Cloudflare Pages automatically deploys when you push to your connected branch:

# Any push to your main branch triggers a new deployment
git add .
git commit -m "Update blog content"
git push origin main

Preview Deployments

Cloudflare also creates preview deployments for pull requests:

  • Each PR gets its own preview URL
  • Perfect for reviewing changes before merging
  • Automatic cleanup when PR is closed

Optimization Tips

1. Optimize Images

Since Cloudflare Pages doesn't support Next.js Image Optimization out of the box:

// components/Image.tsx
import Image from 'next/image'

const OptimizedImage = ({ src, alt, ...props }) => {
  return <Image src={src} alt={alt} unoptimized={true} {...props} />
}

export default OptimizedImage

2. Configure Headers

Create a _headers file in your public directory:

/*
  X-Frame-Options: DENY
  X-Content-Type-Options: nosniff
  Referrer-Policy: strict-origin-when-cross-origin

/*.js
  Cache-Control: public, max-age=31536000, immutable

/*.css
  Cache-Control: public, max-age=31536000, immutable

3. Set Up Redirects

Create a _redirects file in your public directory:

# Redirect old blog URLs
/old-blog/* /blog/:splat 301

# Redirect www to non-www
https://www.yourdomain.com/* https://yourdomain.com/:splat 301

Troubleshooting Common Issues

Build Failures

Problem: Build fails with "Command not found" Solution: Ensure your package.json has the correct build script

Problem: Out of memory errors Solution: Try reducing bundle size or contact Cloudflare support

Routing Issues

Problem: 404 errors on direct page access Solution: Add trailingSlash: true to your Next.js config

Performance Issues

Problem: Slow loading times Solution:

  • Optimize images and assets
  • Enable Cloudflare's additional performance features
  • Use proper caching headers

Monitoring and Analytics

Cloudflare Pages provides built-in analytics:

  1. Web Analytics

    • Page views and unique visitors
    • Popular pages and referrers
    • No impact on site performance
  2. Deployment Analytics

    • Build times and success rates
    • Deploy frequency
    • Error tracking

Advanced Features

Functions (Serverless)

You can add serverless functions to your static site:

// functions/api/hello.js
export async function onRequest(context) {
  return new Response('Hello from Cloudflare Pages!')
}

A/B Testing

Cloudflare Pages supports A/B testing through Workers:

// Split traffic between two versions
export default {
  async fetch(request) {
    const url = new URL(request.url)

    if (Math.random() < 0.5) {
      url.hostname = 'version-a.pages.dev'
    } else {
      url.hostname = 'version-b.pages.dev'
    }

    return fetch(url, request)
  },
}

Conclusion

Deploying your Next.js blog to Cloudflare Pages is straightforward and provides excellent performance benefits. The platform's integration with Git makes it easy to maintain your site with automatic deployments.

Key benefits you'll enjoy:

  • Fast global delivery through Cloudflare's CDN
  • Automatic deployments from your Git repository
  • Free SSL certificates and custom domains
  • Built-in analytics without external dependencies
  • Excellent performance with edge caching

Whether you're running a personal blog or a business website, Cloudflare Pages offers a robust, scalable solution that grows with your needs.

Have you deployed to Cloudflare Pages? Share your experience in the comments below!