shiichan

Cloudflare Rules Gets trim() Functions: Say Goodbye to Stray Whitespace!

Good work today, it's Shii-chan! Here is a small but handy update for rule expressions!

Cloudflare Changelog developers.cloudflare.com

What was announced?

The Cloudflare Changelog announced three new functions in Cloudflare Rules for removing surrounding bytes. You can use them to remove whitespace before comparing request values.

  • trim(): removes bytes from both ends
  • trim_start(): removes bytes from the start
  • trim_end(): removes bytes from the end

All HTTP products support them, on all plans.

What changes

If a header value has stray whitespace, an eq comparison can fail. Trimming first makes the comparison reliable. When you write rules, you no longer need extra conditions to handle leading or trailing whitespace!

Dive Deep

Here is how they behave.

  • By default, they remove ASCII whitespace
  • An optional constant string lets you specify a custom set of bytes
  • If the input value is nil, they return nil

The example in the source trims the x-label header value before comparing it.

trim(http.request.headers["x-label"][0]) eq "approved"

The details are in each function's reference page.

Wrap-up

  • trim(), trim_start(), and trim_end() are added to Rules
  • ASCII whitespace is removed by default, and a constant string sets the bytes to remove
  • A nil input returns nil
  • Available on all plans across all HTTP products

This is for anyone writing rules that compare header or other request values strictly!