How to display images stored in Cloudflare R2

Tag: Back-end

How to display images stored in Cloudflare R2

How to access your images stored in Cloudflare R2, then displaying it in your site!

Are you looking for a way to display your images stored in your Cloudflare R2 bucket? Then you've come to the right place!


There are two ways to access and display your images in your R2 bucket, with URL.createObjectURL or using the AWS S3 API. Though, I wouldn't recommend using createObjectURL, due to some sort of bug that's going on in Firefox browsers. I chose the S3 API way, but if you were to somehow want to use createObjectURL, there are other tutorials out there in the internet!


For starters, install the AWS S3 API and the URL Generator into your project, then import the following modules. Don't forget to mark your file as use server!


imagefetch.ts
"use server";
import {
S3Client,
GetObjectCommand
} from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

Then, you make a new S3Client, like so:


const S3 = new S3Client({
region: "auto",
endpoint: "https://your-account-id.r2.cloudflarestorage.com",
credentials: {
accessKeyId: "your-bucket-accessKeyId",
secretAccessKey: "your-bucket-secretAccessKey"
},
});

Oh yeah, don't forget to replace the values with your own endpoint (can be found in your R2 bucket's settings), and access key & secret key (can be made from "Make R2 API Tokens" in the R2 overview page)!


Now we make the main function, this time I named it imageFetch with the parameter link: any, and the function returns a string promise, that is made with getSignedUrl with the following parameters. I used the link parameter in the Key parameter in the GetObjectCommand so that I could specifically get the image I want. Also, fill out the Bucket parameter with the name of your bucket!


export default async function imageFetch(link: any) {
return await getSignedUrl(S3, new GetObjectCommand({Bucket: 'blog', Key: `${link}.webp`}), { expiresIn: 3600 })
}

Now, it's time to use it! Import the function into your React file, await call the function and assign it to a variable, then use it in your Image component!


page.tsx
...
let image = await imageFetch(results[0].url)
...
return (
...
src={image}
width={500}
height={500}
alt={blogTitle}
className="m-auto"
/>
...
)

And you're all set! I hope this helped you making a project of your own. Stay determined, and see you soon!