sequenceDiagram participant Browser as Browser (Front End) participant Server as Web Server (Back End) participant Database as Database Browser->>Server: 1. Request HTML Server->>Browser: 2. Sends HTML Server->>Database: 3. Sent the token awerfoi34hj98gfq3nhf9834hf19834uhf198p34fh1o3ig1h9834fh19384fh134f
Cookies
Introduction to HTTP Cookies
Tracking Users
User Sessions
flowchart LR Client -->|HTTP request| Server Server -->|HTTP response| Client
User send their first
chat message
-No cookies
Database
User/Client
Server
- The server knows this is their first message since there is no cookie in their request

User Sessions
Username:
Guest-r8d
Token: fd933a6e-
b4c6-4636-b046-
ac8b8d617792
Database
User/Client
Server
- Server generates a random username for this user
- Server generates a random secret token that will uniquely identify the user
- Store both values in a database

User Sessions
Set a cookie with the value
"fd933a6e-b4c6-4636-
b046-ac8b8d617792"
Database
User/Client
Server
Username:
Guest-r8d
Token: fd933a6e-
b4c6-4636-b046-
ac8b8d617792
- In the response to the user, set a cookie containing their token
- Use the expires directive to make sure this is not a session cookie (Yes, it's confusing that we overload the word session)
- It's a session cookie in that it tracks a users session with our app
- It's not a session cookie in that it is not tied to session of their browser

User Sessions
Next chat message contains
"fd933a6e-b4c6-4636-b046-
ac8b8d617792" in a cookie
Database
User/Client
Server
Username:
Guest-r8d
Token: fd933a6e-
b4c6-4636-b046-
ac8b8d617792
- Since this token is set as a cookie
- It is sent in the headers of all subsequent requests from this user

User Sessions
Lookup the
record with a
Token equal to
"fd933a6e-
b4c6-4636-b046-
ac8b8d617792"
Database
User/Client
Server
Username:
Guest-r8d
Token: fd933a6e-
b4c6-4636-b046-
ac8b8d617792
- The server see that there is a cookie set and looks up the token in the database to retrieve this users profile including their username
- When adding the chat message to the database, we know to set "Guest-r8d" as the author

User Sessions
Thanks for the
message!
Database
User/Client
Server
Username:
Guest-r8d
Token: fd933a6e-
b4c6-4636-b046-
ac8b8d617792
- No need to set cookies or do anything special on subsequent responses

User Sessions
- With multiple users:
- Each user has a different username and token
- The tokens are all secret so users cannot steal each others identities
- Usernames are public and displayed to all users in the chat
- Server identifies each user based on their token cookie