Modify response then cache

I’m trying to fetch a remote URL with a worker, modify headers and cache a new response. When I’m caching the response, I get the error:
Body has already been used. It can only be used once. Use tee() first if you need to read it twice.
I’m unsure how to use tee() in my case. Can you direct me, please?

 async fetch(request, env, ctx) {
        // Get url param from a query string
        const urlParsed = new URL(request.url)
        const remoteUrl = urlParsed.searchParams.get('url')

        // Convert to a GET to be able to cache
        const cacheKey = new Request(remoteUrl, {
            headers: request.headers,
            method: 'GET',

        const cache = caches.default
        const cacheResponse = await cache.match(cacheKey)
        if (cacheResponse) return cacheResponse

        // fetch remote file
        const response = await fetch(remoteUrl)
        // Clone the response so that it's no longer immutable
        const newResponse = new Response(response.body, response)

        // Add a custom header with a value
        newResponse.headers.append('Access-Control-Allow-Origin', '*')
        newResponse.headers.append('Access-Control-Allow-Methods', 'GET')
            'Origin, Content-Type, Accept, X-Requested-With, Authorization'
        newResponse.headers.append('cache-control', 'max-age=86400')

        // Error occurs here
        await cache.put(cacheKey, newResponse)

        return newResponse

You can use

You can also improve by doing

as it won’t block docs

1 Like