Skip to content

Instantly share code, notes, and snippets.

@readonlychild
Last active August 19, 2022 03:04
Show Gist options
  • Save readonlychild/e3e376471a9f1f920f10465c8f784542 to your computer and use it in GitHub Desktop.
Save readonlychild/e3e376471a9f1f920f10465c8f784542 to your computer and use it in GitHub Desktop.
image/webp detection

lamdba@edge

With the following lambda@edge, the server-side code can now check values for

  • headers['x-webp-support']
  • headers['x-avif-support']
  • headers['x-ix-bestf']

and make decisions for the response

  • These headers will most likely need to be white-listed at the CDN layer.
exports.handler = async (event, context) => {
  const req = event.Records[0].cf.request;
  const headers = req.headers;

  let avifsupport = '0';
  let webpsupport = '0';

  if (headers['accept']) {
    if (headers['accept'][0].value.indexOf('image/webp') > -1) {
      headers['x-webp-support'] = [{
        key: 'x-webp-support',
        value: '1'
      }];
      webpsupport = '1';
    }
    if (headers['accept'][0].value.indexOf('image/avif') > -1) {
      headers['x-avif-support'] = [{
        key: 'x-avif-support',
        value: '1'
      }];
      avifsupport = '1';
    }
  }

  let bestf = 'png';
  if (webpsupport === '1') bestf = 'webp';
  if (avifsupport === '1') bestf = 'avif';

  headers['x-ix-bestf'] = [{
    key: 'x-ix-bestf',
    value: bestf
  }];

  return req;
};

Without lambda@edge

It can be decided to switch a png request to either webp or avif by looking into the request.header['accept'] where modern browsers send these capabilities.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment