How to present an image on webpage from R2 bucket

Hello,

I am trying to create a simple worker that returns an initial response with the Country code of the authenticated user, along with some other fields. The Country Code is Hyperlinked. This link should take them to current path/${countrycode} which should display the relevant country flag. I have uploaded all country flags named as {countrycode}.png in a Private R2 bucket.

Currently, my code works to the point of having the hyperlink that takes them to the path/${countrycode}. But I am having trouble getting it to fetch the image and displaying it on the browser. It ends up with ‘Country Flag not found’ output from my code.

I am not a developer and this is my first crack at it, so any assistance would be appreciated :slight_smile: .

Below is the worker code .js.

addEventListener(‘fetch’, (event) => {
event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
const url = new URL(request.url);
const pathSegments = url.pathname.split(‘/’).filter(Boolean);

// Extract user information from Cloudflare request headers
const email = request.headers.get(‘cf-access-authenticated-user-email’);
const timestamp = new Date().toISOString();
const country = request.headers.get(‘cf-ipcountry’);
const countryLink = <a href="/secure/${country.toLowerCase()}">${country}</a>;
const responseBody = ${email} authenticated at ${timestamp} from ${countryLink}.;

// This is the /secure path
if (pathSegments.length === 1 && pathSegments[0] === ‘secure’) {
return new Response(responseBody, {
headers: { ‘Content-Type’: ‘text/html’ },
});
}

// This is the /secure/${country} path
if (pathSegments.length === 2 && pathSegments[0] === ‘secure’) {
const countryParam = pathSegments[1];
try {
// Fetch the country flag from the private R2 bucket
const flagBuffer = await country_buckets.get(${countryParam}.png, ‘arrayBuffer’);
const flagResponse = new Response(flagBuffer, {
headers: {
‘Content-Type’: ‘image/png’,
},
});
return flagResponse;
} catch (error) {
// Handle errors (e.g., country flag not found)
return new Response(‘Country flag not found’, {
status: 404,
headers: {
‘Content-Type’: ‘text/plain’,
},
});
}
}

// Return a simple response for other paths
return new Response(responseBody, {
headers: { ‘Content-Type’: ‘text/html’ },
});
}

And here is the wrangle.toml file binding the bucket.

name = “my-worker”
type = “webpack”
main = “src/country.js”
account_id = “myaccountid
workers_dev = true
compatibility_date = “2023-12-06”
[[r2_buckets]]
binding = “country_buckets”
bucket_name = “my_bucket

[env.production]
zone_id = “myzoneid
route = “mydomainpath/secure
workers_dev = false