Cookies vs Sessions in Rails
Think:
- Cookie โ Your library card ๐
- Session โ Books youโve borrowed ๐ stored at the library.
Cookies | Sessions |
---|---|
๐ Stored on userโs browser | ๐ข Stored on server |
๐ Can hold any data you put in them | ๐ Browser only holds an ID, data stays on server |
โฐ Last until expiration date | โฐ Usually expire when browser closes |
๐๏ธ Visible to user (they can see/edit) | ๐ Hidden from user (more secure) |
๐ Sent with every request (affects speed) | โก Only ID sent (faster) |
Rails Examples
Cookie Example โ Remember User Preferences
cookies[:theme] = "dark"
cookies[:theme] # => "dark"
Session Example โ Keep User Logged In
def create
user = User.find_by(email: params[:email])
if user&.authenticate(params[:password])
session[:user_id] = user.id
redirect_to dashboard_path
else
flash[:error] = "Invalid credentials"
render :new
end
end
Storage & Format
Cookies:
- Stored client-side in browser.
- Size limit ~4KB.
- Plaintext unless encrypted/signed.
Sessions in Rails 8:
- By default, stored in encrypted cookie store (client-side, but unreadable).
- Can be stored in DB, cache, or Redis for larger data.
- Session cookie holds encrypted JSON blob.
Rails Internal Implementation
Default Config (config/initializers/session_store.rb
):
Rails.application.config.session_store :cookie_store, key: '_app_session', secure: true
cookies.signed
โ signed to prevent tampering.cookies.encrypted
โ encrypted + signed.- Session uses
ActionDispatch::Cookies
+ActionDispatch::Session
middleware.
Security Considerations
- Never store sensitive data directly in plain cookies.
- Use
cookies.encrypted
or sessions for sensitive info. - Set
secure: true
(HTTPS only) andhttponly: true
(no JS access). - Rotate secret keys if compromised.
- Keep session data minimal โ less network overhead.
Performance Tips
- Use cookies for small, infrequently changed preferences (theme, language).
- Use sessions for user state that must be tamper-proof.
- For large session data, move to Redis/memcache to avoid cookie bloat.
โก TL;DR
- Cookie = browser storage, Session = server-managed user state.
- Rails sessions often stored in encrypted cookies by default.
- Keep data small, secure, and use HTTPS.