What is the recommended way to check if a value is set?
TL;DR
Jumping to the answer, I believe these examples would work:
if ( req.http.cookie ~ ".") {
return(pass);
}
or
if ( req.http.cookie != "") {
return(pass);
}
Either of these call return(pass)
if the value req.http.cookie
is set.
However, going back to a first attempt, the most surprising result was this always evaluated to TRUE.
if ( req.http.cookie ) {
return(pass);
}
50% of the reason for that is explained in VCL best practices | Fastly Documentation that “Empty strings are always truthy”.
However what if req.http.cookie
is “not set”, and verified to be (null)
. That should return FALSE, right? No, guess what happens. The if statement seems to convert req.http.cookie
from (null)
to empty string
. Now it’s really empty string
. And then it’s TRUE (empty strings are truthy).
Next,
if ( req.http.cookie == null) {
and
if ( req.http.cookie == (null)) {
Cause errors. They are not solutions.
This one,
if ( req.http.cookie != "") {
return(pass);
}
is sort of surprising. When req.http.cookie
is (null)
or “not set”, that is a value which is slightly different from an empty string “”. Similar, but not the same.
Yet in this particular comparison, (null)
or “not set” is considered equivalent to empty string “”. req.http.cookie
isn’t modified. It remains (null)
afterwards.