[Web] Cookie and Session

 Cookie and Session


HTTP is inherently stateless: the server doesn't remember any information about the client between requests. To create a stateful experience (like staying logged in), cookies and sessions are used together.

Cookies

  • small pieces of data stored directly on the client (on the browser).
  • they keep preferences, track analysis and store session ID or auth tokens.
  • Usually, the size is limited up to 4KB.
  • It expires after a certain time, depending on the configuration on the client, or it can persist until manually deleted.
  • Potentially, they are visible to the user. Sensitive data should be avoided or encrypted.

Sessions

  • Data about the user or their activity kept on the server.
  • They store user authentication status or other sensitive information.
  • A session ID is usually sent to the client in a cookie, which is used by the server to find the correct session data.
  • The size of sessions may vary.
  • It's more secure by design, since sensitive data stays on the server.

How they work together

  1. When a user logs in, the server creates a session (storing the user info) and returns a session ID.
  2. The client stores the session ID in a cookie
  3. In the future requests, the client sends the session cookie to the server, which uses the session ID to retrieve stored data and maintain the user's state.

Key point

While it looks continuous to the end-users, under the hood, each request is stateless - just repeatedly retrieving stored session data to simulate continuity.

Comments