How to set cookie in faraday

fsword picture fsword · Aug 5, 2012 · Viewed 7.2k times · Source

I'm using Faraday as an HTTP client to test my HTTP service (based on Sinatra). It's very powerful for me, but I have a problem.

We track sessions on the Sinatra service, but I cannot set the cookie value with the Faraday client. This is the sample code:

# `response` is from the Sinatra service
cookie = response.headers['set-cookie']

# now, for the follow up request...
response = client.get '/api/profile' do |req|
  req.headers['Cookie'] = cookie
end

The server cannot find the session. Why?

Answer

wich picture wich · Oct 17, 2012

The Set-Cookie and Cookie headers are not the same, read the RFC to know how to interpret them. In short the Set-Cookie header also contains instructions for the client how to handle the data (domain, path, expiry, etc.) and gives an update to the existing cookie store. The Cookie header on the other hand provides the contents of the cookie store, but not the meta data.

You would need to obtain or implement some kind of cookie handler to insert into your Faraday middle-ware stack.