Nextjs on Cloudflare

October 30, 2024

I'll be honest, I use Cloudflare for DDoS protection, and I love it. But I've never really used any of their other products.

Occasionally, I've looked at and tried things like R2, but since most projects that require file storage already use AWS or GCP anyway, I end up using S3 or Cloud Storage. I think this is the case for most developers. Where you are using a single cloud provider for everything.

But it's hard to ignore the offerings from Cloudflare at this stage - which now include file hosting, databases, KV stores, and of course the Workers platform.

And with OpenNext coming along (with some help from SST), you apparently can run Nodejs runtime working inside Cloudflare Workers.

Quick setup

First, install the necessary packages:

npm install -D wrangler @opennextjs/cloudflare

Now create a wrangler.toml file in the root of your project:

main = ".worker-next/index.mjs"
name = "blog"
compatibility_date = "2024-09-26"
compatibility_flags = ["nodejs_compat"]
minify = true
assets = { directory = ".worker-next/assets", binding = "ASSETS" }

(you can now also cosplay as rust developer and become insufferable at meetups)

What makes this interesting is that you can now use Nodejs runtime inside Cloudflare Workers for your Nextjs application.

Deploying

npm run build:worker && wrangler deploy

This will automatically deploy the dist directory to Cloudflare and prompt you to login if you haven't already.

Overall, it's a pretty smooth experience to deploy and run, the workers/pages platform is pretty solid and similar to Vercel.