Sharing Sessions across Domains

Become a Subscriber

Today’s tip is a simple one: configuring rails to share session state across multiple domain and/or subdomains. Rails sessions are really just a simple cookie store. Session store configuration is usually set up in config/initializers/session_store.rb and specifies what class to use to store the session. Possible values are :cookie_store which is the default, :mem_cache_store, and :disabled. Custom session stores can also be specified, which is what we will need for sharing across domains.

Replace AppName below with your own application name. This can be found in your config/application.rb file as the module wrapper around your Application class:

AppName::Application.config.session_store :cookie_store, key: '_devise_session', domain: :all

In this code, we’re pretty much following the defaults with the cookie storage, and whatever key name we want. The important bit is domain: all which creates a cookie for all the different subdomains that are visited during that session and 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. This configuration will instead create a single cookie that is persistent throughout the session, even when the domain changes.