# Dynamic cookie domain (for multitenant app)

**URL:** <https://www.ruby-forum.com/t/dynamic-cookie-domain-for-multitenant-app/185324>\
**Category:** Rails\
**Created:** [March 18, 2010, 7:46am UTC](https://www.ruby-forum.com/t/dynamic-cookie-domain-for-multitenant-app/185324 "2010-03-18T07:46:08Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![axyd80](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/82dd89/32.png) [@axyd80](https://www.ruby-forum.com/u/axyd80)\
**Post date:** [March 18, 2010, 7:46am UTC](https://www.ruby-forum.com/t/dynamic-cookie-domain-for-multitenant-app/185324/1 "2010-03-18T07:46:08Z")

</div>

There is a Multitenant App, that should serve sites on domains like  
this:  
[client1.app.com](http://client1.app.com)  
[client2.app.com](http://client2.app.com)  
And it’s easy to share cookies between all of them (using ‘.app.com’  
cookie domain):  
ActionController::Base.session = {:key =\> thekey, :secret =\>  
thesecret, :domain =\> ‘.app.com’}

But! There is one more requirement, those sites should be also avaliable  
as:  
[www.client1.com](http://www.client1.com)

So, in order to all this works the App should dynamically change the  
cookie domain:  
[xxx.app.com](http://xxx.app.com) =\> “.app.com”  
[www.xxx.com](http://www.xxx.com) =\> “.xxx.com” or leave it blank

Google told me that there is one approach  
[http://codetunes.com/2009/04/17/dynamic-cookie-domains-with-racks-middleware/](http://codetunes.com/2009/04/17/dynamic-cookie-domains-with-racks-middleware/)  
but it doesn’t works (Rails 2.3.5).

I also tried my own solution:

class CrossDomainCookies  
def initialize(app)  
@app = app  
end

```
def call(env)
  host = env["HTTP_HOST"].split(':').first.downcase
  if host.include?('.')
    normalized_host = host.scan(/[^\.]+\.[^\.]+$/).first
    cookie_domain = ".#{normalized_host}"
  else
    normalized_host = host
    cookie_domain = host
  end

  Rails.logger.info cookie_domain

  ActionController::Base.session_options['domain'] = cookie_domain

  @app.call(env)
end

```

end

But it also doesn’t works, maybe there are some other solutions?
