Resizing a private image in an R2 bucket through a worker

export default {
    async fetch(request, env): Promise<Response> {
        const url = new URL(request.url);
        const key = url.pathname.slice(1);

        switch (request.method) {
            case "PUT":

                const url = key + "/image"
                await env.MY_BUCKET.put(url, request.body);

                const resizeOptions = {cf: {image: {width: 500,height: 500,quality: 50,},},};

                const transformedResponse = await fetch(`https://pub-0dc2d101c4l85b4635bbd2ab7et172.r2.dev/${url}`, resizeOptions); //<--Puplic Bucket
                
                if (!transformedResponse.ok) {
                    return new Response(`Image transformation failed: ${transformedResponse.statusText}`, { status: transformedResponse.status });
                }

                const transformedImage = await transformedResponse.arrayBuffer();

                const thumbnailUrl = key + "/thumbnail";
                await env.MY_BUCKET.put(thumbnailUrl, transformedImage);

                return new Response(`Put ${key} successfully! Thumbnail stored at ${thumbnailUrl}`);

            default:
                return new Response("Method Not Allowed", {
                    status: 405,
                    headers: {
                        Allow: "PUT, GET, DELETE",
                    },
                });
        }
    },
} satisfies ExportedHandler<Env>;

How can I handle the fetch operation to resize my image when my R2 bucket is private? The resizing only works with a URL, right? Do I have to create another worker to make this possible?
Thanks Niklas
Was this page helpful?