Rails: Behind the Sessions

In rails, there are basically three ways to store server-side information in the client’s browser: cookies, session, and flash.

spoiler alert: they’re all actually just cookies

As we all knows, cookie is some data stored in browser. What kind of data? anything you want to store. There are size limitation of course. Rails put an implicit 4kb limit to every cookie stored.

To make a cookie, one can simply write cookies[:field_name] = 'value' and voila! now your client has a key-value pair {field_name: 'value'} stored in their browser.


The problem is, your client can see that data, and tamper with it.

open cookie
Cookie thief!

So here comes session to the rescue!

There are to ways session mitigate this problem. First, session will encrypt the information stored in the browser. Second, the data you want to store is not actually stored in the client’s browser.

What will happen is, the app will store an encrypted session id in the browser, and store the data attributed with that session id server-side.

Similar to cookie, you can simply write session[:field_name] = 'value'. The session id will be encrypted by SHA1 with the secret_key_base variable configured in config/secrets.yml file.

locked cookie
Secured cookies

The last one is flash.

flash cookie 2
Flash cookie

To put it simply, flash is a cookie that can only be used once. It delete itself right after it’s opened. How sad.

As above, to make a flash you write flash[:field_name] = 'value'

Flash is usually used to store a success/failure message between each request. Like ‘Login success’ or ‘Username already taken’. Naturally the content became irrelevant after one request, so why would we need to keep it while it has lost its meaning of life? That might be cruel but such is life.

hanging flash cookie
Suicidal Flash cookie

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s