Coder's Cat

Cookie vs. Session

2020-04-22

What’s the difference between Cookie and Session? Session is not always stored on server-side.

file:img/2020_04_22_cookie-vs-session.org_20200506_231846.png

Cookie and Session are two concepts will be met many times in Web development.

Can you give more details about them?

In daily life, a cookie is a dessert or a piece of cake.

In the field of the software world, a Cookie is an information saved by your web browser.

As we all know, HTTP is stateless. So how do you identify a specific customer?

Cookies do that.

Each time an HTTP request is made, the client sends the appropriate Cookie information to the server. It can be set to expire at any time, and if you don’t take the initiative to clear it, you can keep it for a long time, even if you shut down your computer. Another limitation is: Cookie has a size of limit of 4K.

Since it is stored on the client-side, the attackers can tamper with the locally stored information to trick the server. What should we do?

Session will be the solution.

Session

Session is another mechanism used to identify specific users.

Normally, Session is stored on the server-side, they are stored in a file, database or memory in servers. Session ID could be stored in cookies.

When a user logout from a website, the session will be deleted by server. The stored session ID will be invalid.

In fact, both Cookie and Session are a way to record a state of users. They are typically used in scenarios such as “shopping carts”, where the server does not know exactly what the specific user is doing when you click on the order button. In order to identify and track users and understand that there are several items in the shopping cart. The server gets this information by creating a Cookie/Session for that user.

More …

Session is not always stored on server-side. The ultimate difference between Session and Cookie is Session is safer and it ends when users close their browsers. Session will be adopted when we do authorization.

You should not put confidential information in Cookies.

Some Web frameworks support the mechanism of CookieBased session. The session will be encoded, encrypted and stored in Cookies. Rails use this as the default session solution. Actually there are 6 methods to store session in Rails:

:cookie_store
:active_record_store
:drb_store
:mem_cache_store
:memory_store
:file_store

Join my Email List for more insights, It's Free!😋

Tags: Misc