Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Jin He
Jin He
8,123 Points

About the usage of cookies and session

Hey guys, I'm feeling confused about the usage of cookies and sessions, what kind of data should cookie store, what kind of data should session store, when should I use cookies to store data, when should I use session to store data ????

1 Answer

Matt West
Matt West
14,545 Points

Hey Jin!

Any data that you store in a session will be lost at the end of that session. If you need to store data that persists between sessions, you should use cookies.

Cookies can be set to either expire at the end of the session, or persist for a set amount of time (take a look at the 'Expires/ Max-Age' column in screenshot below). They're stored by the browser and stay on the user's computer until they expire or are deleted.

Both of these storage technologies store simple key/value pairs and are best suited for small amounts of data like user IDs or short strings.

Let's run through an example.

Say you're building a website that allows users to log in to a special members area. You'd need to store the user's information when they log in (typically an ID or some other authentication token) so that you can check to make sure they are logged in as they browse around the members area.

If you wanted the user's session to end when they leave your website and close their browser, then you would store this information in the session as that information is automatically cleared out when the browser is closed. When they come back to your website they would need to log in again.

But say you have a 'Remember me' checkbox on your login form for people that want to remain logged in between sessions. Now you would save their information in a cookie with an expiry date at some reasonable length in the future. Unlike with session storage, this cookie is persistent, so if a user closes their browser and then comes back later they would still be logged in (as long as the cookie hasn't expired).

I hope this helps to give you a clearer picture of when to use cookies vs session storage.
Let me know if you have any other questions :)