Open nicolasvienot opened 4 months ago
I can open a new issue if needed, please let me know 👍 it might also be related to: https://github.com/kwhitley/itty-router/issues/249
Thanks @nicolasvienot - can you give me minimal repro steps to see this immutable headers issue on a Worker? I use CORS on virtually all my Workers (which is what I exclusively develop on these days) and am not running into this...
I'd like to ensure this is absolutely necessary before adding so many bytes! :)
@kwhitley I think you can use this sample to reproduce the issue:
import { Router, cors } from 'itty-router'
const router = Router({
before: [preflight],
finally: [corsify]
})
router.get('/sample', ({ params }) => {
const cache = caches.default
const cached = await cache.match(request)
if (cached !== undefined) {
return cached
}
const response = new Response(null, { status: 200 })
ctx.waitUntil(cache.put(request, response.clone()))
return response
})
return await router.fetch(request).catch(error)
When you access the first time, it returns 200, but the next requests will return 500 error.
{
"status": 500,
"error": "Can't modify immutable headers."
}
And there will be a warning message in worker logs:
A ReadableStream branch was created but never consumed. Such branches can be created, for instance, by calling the tee() method on a ReadableStream, or by calling the clone() method on a Request or Response object. If a branch is created but never consumed, it can force the runtime to buffer the entire body of the stream in memory, which may cause the Worker to exceed its memory limit and be terminated. To avoid this, ensure that all branches created are consumed.
* Unused stream created:
at corsify (file:///.../temp/node_modules/.pnpm/itty-router@5.0.18/node_modules/src/src/cors.ts:81:44)
Description
A fix was implemented in https://github.com/kwhitley/itty-router/commit/74f63abb25d12666e7c05e5e82fcf7432f8dbda4 to clone the response in
corsify
in order to avoid this error:Unfortunately, it seems not to be enough, and we're still having the issue with Cloudflare when a response is modified by
corsify
. A solution we found and implemented is to recreate a response by usingnew Response(...)
.Applying the fix here.
Related Issue
Link to the related issue: related to #242
Type of Change (select one and follow subtasks)