DEV Community

Shan Asif
Shan Asif

Posted on

Session vs Cookie

Sessions and cookies are both used to store information about users, but they have different characteristics and purposes:

Cookie:

  • Where it's stored: On the user's browser.
  • Purpose: To remember information about the user, such as login details or preferences, across different browsing sessions.
  • Lifetime: Can persist for a long time, depending on how they are set up (until they expire or are deleted).
  • Use case: Often used for tracking, remembering login status, or storing user preferences.

Example:

When you visit an online store and it remembers your login details or your preferences (like language settings), that's done using cookies.

You might close the browser and come back later, and the website still remembers you because the cookie is still there.

Session:

  • Where it's stored: On the server.
  • Purpose: To keep track of a user's activity while they are visiting a website.
  • Lifetime: Typically lasts only as long as the user's visit to the website. It ends when the user closes the browser or logs out.
  • Use case: Often used for maintaining a user's state and information while they navigate a site, like keeping items in a shopping cart.

Example:

When you add items to a shopping cart on an e-commerce site, that information is stored in a session. If you leave the site or close your browser, the cart might be empty when you return.

The information is kept on the website's server and disappears when you leave or log out.

Session and Cookies Often Work Together:

1. Session Management:

When you visit a website, a session is created on the server to keep track of your activities and data during your visit. This session is identified by a unique session ID. This session ID is sent to the user's browser as a cookie.

2. Using Cookies to Store Session IDs:

  • To link your browser to this session on the server, the server typically sends a cookie to your browser with the session ID.
  • Your browser stores this cookie, and every time you make a request to the server (like clicking a link or submitting a form), it sends the cookie back to the server.
  • This way, the server knows which session belongs to you and can provide the correct data and experience.

3. Persistence Across Visits:

Even though sessions are temporary, cookies can allow for persistence across visits.

For example, if you log in and select "Remember Me," the site might use a cookie to store your login status so you don’t have to log in again on future visits.

Top comments (0)