DEV Community

S M Tahosin
S M Tahosin

Posted on

How to Deploy Next.js to Cloudflare Pages for Free (2026)

Netlify's 100GB bandwidth limit can burn through fast. Cloudflare Pages offers unlimited bandwidth for free. Here's how to deploy your Next.js app.

Why Cloudflare Pages?

Feature Netlify Free Cloudflare Free
Bandwidth 100 GB/mo Unlimited
Build minutes 300/mo 500/mo
Serverless functions Yes Yes
Custom domains Yes Yes
Edge network Global Global (faster)

Step 1: Enable Static Export

// next.config.ts
const nextConfig = {
  output: "export",
};
export default nextConfig;
Enter fullscreen mode Exit fullscreen mode

Note: Static export means no SSR. Use Cloudflare Functions for API routes instead.

Step 2: Move API Routes to Cloudflare Functions

Create functions/api/generate.js:

export async function onRequestPost(context) {
  const { request, env } = context;
  const { prompt } = await request.json();

  const res = await fetch(
    `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${env.GEMINI_API_KEY}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        contents: [{ parts: [{ text: prompt }] }],
      }),
    }
  );

  const data = await res.json();
  const text = data?.candidates?.[0]?.content?.parts?.[0]?.text || "";
  return new Response(JSON.stringify({ text }), {
    headers: { "Content-Type": "application/json" },
  });
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Build and Deploy

npm run build
npx wrangler pages deploy out --project-name my-app
Enter fullscreen mode Exit fullscreen mode

Step 4: Set Environment Variables

Go to Cloudflare Dashboard → Pages → your project → Settings → Environment Variables.

Add GEMINI_API_KEY as a secret.

Step 5: Custom Domain (Optional)

Pages → Custom domains → Add domain → follow DNS instructions.

That's It!

Your app is live with:

  • Unlimited bandwidth
  • Global edge network
  • Serverless API functions
  • Free SSL

I migrated 3 projects from Netlify to Cloudflare and haven't looked back.


Building AI tools on Cloudflare? Check out my projects:

Top comments (0)