Cloudflare "Cache Reserve" with NextJs 15 project
Unanswered
Britannia Petite posted this in #help-forum
Britannia PetiteOP
We are trying to implement Cache Reserve for a NextJS 15 project but run into the issue that the pages are streamed, hence no content-length header is set (which is required for Cache reserve to work). It turns out that this is not as easy as I thought to implement in Nextjs: We have 500k landing pages, so we cannot generate the pages statically.
How would I best "wrap" single routes so I can attach a Content-length header that makes Cache Reserve work?
Thanks for any pointers!
How would I best "wrap" single routes so I can attach a Content-length header that makes Cache Reserve work?
Thanks for any pointers!
8 Replies
Chub mackerel
Streaming pages can’t have Content-Length since the full size isn’t known. To make Cache Reserve work, you need to either buffer the page fully on the server before sending it or serve it from a cached/static version where the length is known.
Britannia PetiteOP
Thanks for letting me know! Is there an example on how to buffer the page fully on the server before sending it?
How "dangerous" do you think this is? We are using CF to cache everything quite aggressively but need a content-length for "Cache Reverse" to work. Not 100% sure about possible site effects when introducing this. Could be a nightmare
Chub mackerel
Yeah, buffering the full page is possible but comes with trade-offs. Essentially you’d need to render the page fully on the server first (collect all the HTML into a string), then set the Content-Length header and send it
Britannia PetiteOP
Would I do this in the middleware? Or on the route? I cann ot seem to find the option to do this, for e.g. a /about-us page or something easy to start with
Chub mackerel
You’d need to handle it at the route level (e.g. in a custom route or API handler) where you can fully render the page to a string (renderToString/renderToReadableStream), buffer it, then set the Content-Length before sending
Britannia PetiteOP
Thanks for that! Will look into this
Britannia PetiteOP
Do you happen to have a practical example of a page that is served like that? I simply cannot make it work except on a route.