Running Next.js on Cloudflare Pages.
NOTE: We're still actively updating this repository, docs, and preparing a potential release on NPM, this package is highly experimental and might break at any time, and we might even introduce a rename soon.
This (experimental) tool allows you to run Next.js with Edge Runtime on Cloudflare Pages!
Currently, Next.js outputs by default an individual Edge Function for each Page or API Route, including a full NextWebServer
for each function. This is not ideal since that requires us to write a custom router, since for Cloudflare Workers / Pages, we can only upload one worker (or multiple functions but those get bundled anyways).
So, for now we're using esbuild and the middleware-manifest.json
outputted by next build
to bundle those functions together, and output a _worker.js
file based on the worker.template.ts
file, compatible for Cloudflare Pages with a custom router that forwards requests to the right functions.
We put all truely static files in the _routes.json
file so we can skip executing this worker.
I'm experimenting with hooking into the webpack configuration of Next.js to be able to include a custom entrypoint for a custom CloudflareWebServer
based on BaseServer
optimized for Cloudflare Pages. This would allow us to build a LOT more features like incremental static generation and have overall greater feature parity.
NextWebServer
used for each edge runtime page / api route.BaseServer
used by NextServer
and NextWebServer
that I'm attempting to extend to build a better version for Cloudflare Pages.We haven't bundled this into NPM yet, so cloning this repository will be needed, you'd need to use PNPM. You'd need to make sure your project is using Edge Runtime.
next dev
.next build
to generate a build.nextflare build
in the root of your next.js project, where your package.json / next.config.js file is located.dist
will be generated, this folder you can directly upload to Cloudflare Pages.In order for SSR to work, you'd need to enable some compatibility flags on Cloudflare Pages, this is currently only possible using the API, this curl call will set the compatibility date to 2022-08-16
and add the following flags to your Cloudflare Pages project:
curl https://api.cloudflare.com/client/v4/accounts/ACCOUNT_ID/pages/projects/PROJECT_SLUG -H 'X-Auth-Email: YOUR_EMAIL' -H 'X-Auth-Key: YOUR_AUTH_KEY' -X PATCH -d '{"deployment_configs":{"production":{"compatibility_date": "2022-08-16", "compatibility_flags": ["transformstream_enable_standard_constructor","streams_enable_constructors"]},"preview":{"compatibility_date": "2022-08-16", "compatibility_flags": ["transformstream_enable_standard_constructor","streams_enable_constructors"]}}}'