Share session (cookies) between subdomains in Rails? Share session (cookies) between subdomains in Rails? ruby-on-rails ruby-on-rails

Share session (cookies) between subdomains in Rails?


As it turns outs 'domain: all' creates a cookie for all the different subdomains that are visited during that session (and it ensures that they are passed around between request). If no domain argument is passed, it means that a new cookie is created for every different domain that is visited in the same session and the old one gets discarded. What I needed was a single cookie that is persistent throughout the session, even when the domain changes. Hence, passing domain: "lvh.me" solved the problem in development. This creates a single cookie that stays there between different subdomains.

For anyone needing further explanation, this is a great link: http://excid3.com/blog/sharing-a-devise-user-session-across-subdomains-with-rails-3/


http://excid3.com/blog/sharing-a-devise-user-session-across-subdomains-with-rails-3/

"The part you want to watch out for here is that if you set :domain => :all like is recommend in some places, it simply won’t work unless you’re using localhost. :all defaults to a TLD length of 1, which means if you’re testing with Pow (myapp.dev) it won’t work either because that is a TLD of length 2."

In other words you need:

 App.config.session_store ... , :domain => :all, :tld_length => 2

Also a good idea to clear your cookies


I was looking for a way to solve this problem without having to explicitly state the domain name, so I could hop between localhost, lvh.me, and whichever domains I would use in production without having to keep editing the session_store.rb file. However, setting "domain: :all" didn't seem to be working for me.

Ultimately I found that I needed to state the tld_length (top level domain length) in that expression. The default tld_length is 1 while example.lvh.me has a tld_length of 2 and 127.0.0.1.xip.io has a tld_length of 5, for example. So what I had in the session_store.rb file for subdomains on lvh.me in development and whatever else in production was the below.

MyApp::Application.config.session_store :cookie_store, key: '_MyApp_session', domain: :all, tld_length: 2

Hope this helps someone, as it took me a long time to find this answer!