Cookies vs Sessions with CookieStore

gjb picture gjb · Feb 22, 2013 · Viewed 19.1k times · Source

In Rails 3, what is the difference between storing data in a cookie and storing data in a session, with the session store set to the default of CookieStore?

e.g.

cookie[:foo] = 'bar'

# MyApp::Application.config.session_store :cookie_store, key: '_myapp_session'
session[:foo] = 'bar'

As far as I can tell, both end up stored in a client-side cookie.

When would you choose to use one over the other?

Thanks.

Answer

Wolfgang picture Wolfgang · Mar 1, 2013

The main difference is that when you use cookie[:foo] = 'bar' the user is able to see the value for the cookie, i.e. 'bar'. When you use session[:foo] = 'bar' the value will be encrypted by rails and stored in the _myapp_session cookie.

You would use the cookie[] format when the information you want to store is not bound to the session, e.g. when the users selects the preferred language.

You would use the session[] format when you want to store information that is related to the current session, e.g. the id of the the user.