On Cross Subdomain Cookies
July 12, 2011 § 1 Comment
The first Ruby gem I ever wrote was tld-cookies. While it is very poorly named, probably should have been called root-domain-cookies
or something like that, it adds a nice little bit of functionality to the Rails 3 cookie jars.
One of the things about Rails 3 that I thought was really cool, was the way cookies were accessed. It’s not a big and fancy piece of code, but to me it is just a slick way to do things. The chaining of the different cookie jars makes it trivial to create the cookies you want and need.
cookies.permanent.signed[:awesome_cookie] = "cookies awesomeness" cookies.signed[:awesome_cookie] => "cookies awesomeness"
At the time I was working on a project at work that required the use of a lot of dynamic subdomains, and we wanted to be able to write cookies across all of the subdomains as well as for individual subdomains. In Rails 3 you could set the domain when you write to the cookie like:
cookies.signed[:awesome_cookie] = { :value => "cookies awesomeness", :domain => "example.com" } cookies.signed[:awesome_cookie_sub] = { :value => "cookies awesomeness subdomain", :domain => "sub.example.com" }
Now that is a lot of extra work and looks pretty ugly. You could set the default domain for you cookies like this:
Rails.application.config.session_store :cookie_store, :key => '_app_name_session', :domain => :all
But I guess I’d rather explicitly say when a cookie is to be used across all subdomains. To this point I tld-cookies
add a tld
cookie jar to your Rails 3 app which sets the domain for the cookie to be the root domain, i.e. example.com.
cookies.tld.signed[:tld_cookie] = "ACROSS ALL SUBDOMAINS!!!" cookies.signed[:tld_cookie] => "ACROSS ALL SUBDOMAINS!!!"
As you can see above, you use it similarly to how you would use the permanent
cookie jar. The slight difference is when you want to delete the cookie you have to use the tld
accessor.
So yeah, first Ruby gem. Poorly named, fun little learning project.
[…] side note, this same project is the one that inspired me to write my first ruby gem, tld-cookies. It’s a nice little gem that makes it easy to set a cookie that works across all subdomains […]