Take the 2-minute tour ×

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?


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?


share|improve this question
add comment

2 Answers

up vote 23 down vote accepted

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.

share|improve this answer
a correction; the value is not encrypted but encoded (with base64) by default. –  Cem Mar 22 '13 at 5:45
Although the question was about Rails 3, in which cookies were only encoded, it's worth noting that Rails 4 encrypts them. –  sheldonh May 25 '13 at 12:57
Why does Rails 4 encrypts ? Any idea? , Won't it be expensive for a rails app which encrypts/decript every requests? –  Krishnaprasad Varma Jun 14 '13 at 3:39
Hmm, is encryption really necessary? Surely what you really want is a signature, so that people can't forge it? –  Trejkaz Oct 18 '13 at 10:20
add comment





share|improve this answer
add comment

Your Answer


