Sessions and cookies are both used to track user state (like being logged in) across multiple HTTP requests since HTTP itself is stateless. Here’s how they work and how they differ:
1. Cookies
- A cookie is a small piece of data stored in the user's browser, sent by the server via HTTP response headers.
- Every time the browser makes a request to the same server, it automatically includes the cookie in the request headers.
Typical Flow:
- User logs in → Server responds with a Set-Cookie header.
- The browser saves this cookie.
- For subsequent requests, the browser automatically sends the cookie in the Cookie header.
Example of a cookie in HTTP:
Set-Cookie: session_id=abcd1234; HttpOnly; Secure; SameSite=Strict;
Cookies can store:
- Session IDs (to identify user sessions).
- Preferences or settings.
- Authentication tokens (e.g., JWTs).
2. Sessions
- A session is data stored on the server that is tied to a unique user.
- When a user logs in, the server creates a session and stores data (e.g.,
user_id
).
- The server sends a session ID to the browser via a cookie.