Adaptive Image Format Conversion

In this document, we demonstrate how to identify the browser type via User-Agent in the request header, use fetch API to get the image from the origin, and convert it to the format required by the browser.
// Browser image format
const broswerFormat = {
Chrome: 'webp',
Opera: 'webp',
Firefox: 'webp',
Safari: 'jp2',
Edge: 'webp',
IE: 'jxr'

addEventListener('fetch', event => {
// If the function code throws an unhandled exception, Edge Functions forwards the current request back to the origin.

async function handleEvent(event) {
const { request } = event;
const userAgent = request.headers.get('user-agent');
const bs = getBroswer(userAgent);
const format = broswerFormat[bs];
// Do not convert the image format
if (!format) {
return fetch(request);

// Convert image format
const response = await fetch(request, {
eo: {
image: {

// Set the response header
response.headers.set('x-ef-format', format);
return response;

function getBroswer(userAgent) {
if (/Edg/i.test(userAgent)) {
return 'Edge'
if (/Trident/i.test(userAgent)) {
return 'IE'
if (/Firefox/i.test(userAgent)) {
return 'Firefox';
if (/Chrome/i.test(userAgent)) {
return 'Chrome';
if (/Opera|OPR/i.test(userAgent)) {
return 'Opera';
if (/Safari/i.test(userAgent)) {
return 'Safari'

Sample Preview

In the address bar of the browser, enter a URL (such as that matches a trigger rule of the edge function to preview the effect of the sample code.

Google Chrome: webp

Apple Safari: jp2

Microsoft IE: jxr