Compare Client IP against list of IP Ranges

I am looking for a simple way to check if an IP address is in a particular set of CIDR ranges? Say I have a set like this (just much larger, and the prefix lengths are variable)

const whiteList = new Set([
    "1.1.1.0/24",
    "8.0.0.0/8",
    "2a00:face::/29"
])

I want to do something like:

  const ip = request.headers.get("cf-connecting-ip")
  let isWhiteList = **whiteList.has(ip)**
  if (isWhitelist) {
    do something;
  else {
    do somethingElse;
  }

Obviously the whiteList.has does nothing here. Is there a quick and easy way to compare the client IP against a CIDR list?

There is a package for this.

2 Likes

Thanks @Xaq. I had seen that package before, but presumed the whole npm, webpack setup would be tricker than it is.

1 Like

Yeah, still too much code for workers. I may code my own and share it here.