Need guidance on caching behavior with regard to session cookies


#1

Hello,

I have a Node.js application where each individual page has a logged in user view and a visitor view. I would like the caching to behave differently in such cases. In particular:

I would like Fastly to do the following:

  • If a session cookie called connect.sid does not exist, fetch from the cache. (no session)
  • If a session cookie called connect.sid exists, but its value is null, fetch from the cache. (no session)
  • If a session cookie called connect.sid exists, and has a non-zero value, forward to origin, and do not cache. (valid session)

Can anyone help me with a VCL example for this, and how I can add it to Fastly?

Thank you!
Bahadir


#2

Hello Bahadir,

I recommend you to use vary header and pass on vcl_recv.

vcl_recv

Check if “connect.sid” and the value exist

if (req.http.cookie ~ “connect.sid=(?!;)+” {
set req.http.x-connect-sid = “true”;
return(pass);
} else {
set req.http.x-connect-sid = “false”;
}

vcl_fetch

vary on the custom header

if (beresp.http.Vary) {
set beresp.http.Vary = beresp.http.Vary “, x-connect-sid”;
} else {
set beresp.http.Vary = “x-connect-sid”;
}

vcl_deliver

Hide the existence of the header from downstream

if (resp.http.Vary) {
set resp.http.Vary = regsub(resp.http.Vary, “x-connect-sid”, “Cookie”);
}

Thanks.

Regards,
Junichi


#3

Hi Junichi,

It worked! Thank you!

For reference I copied over Fastly boilerplate VCL, and inserted each snippet in the original examples between the function beginning and #Fastly hash define start. In particular I inserted vcl_recv, vcl_fetch, vcl_deliver snippets.

There was a missing closing parenthesis the first line, it should be:
if (req.http.cookie ~ “connect.sid=(?!;)+”) {

The behavior I get now is that those pages that have the cookie are uncached, and those that don’t have it are returned from the cache.

I came to learn that a connect.sid can be present even when not authenticated. So in my case I added another cookie auth_state that indicates login and logout and detecting that.

Thanks,
Bahadir