Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Networking › HTTP

Cookies

Showing a name tag, every time, to a server that cannot remember you

Why it exists — Without cookies, to keep a login state you would have to attach an identifier to every link's address or to a hidden field in every form, and a value attached to an address leaks when the link is shared or saved in a history. A cookie sends this value in a request header instead of the address and has the browser attach it automatically, so the side that builds the pages does not have to handle the value for each link.

Where it's used today — It is mainly used to send the session ID after login (such as the JSESSIONID cookie of Tomcat) to tell the server that the requests come from the same user, and it is also used to remember settings such as the language. Login cookies get HttpOnly, Secure, and SameSite, which prevent or reduce reading by scripts, sending over plain HTTP, and being sent along with requests from other sites. Mobile apps sometimes send a token in the Authorization header instead of using cookies.

HTTP does not link one request to the next. The server cannot tell whether an earlier request came from the same browser. So when a login succeeds, the server sends a small value (a cookie) in the response, and the browser stores it and attaches it automatically to every request that goes to the same site.

Checked against real execution · Ran every combination with Chrome 158 (without a window) and a test server, and checked, including the combinations that shut the browser down and start it again with the same profile (default startup setting)

Concepts in this lab

Cookie
A small piece of data that a server sends in a response. The browser stores it and automatically sends it back with every request to the same site. HTTP does not remember state between requests, so this data is used to keep information that must carry over, such as a login state. Because it is stored in the user's browser, you must use it on the assumption that the user can read or change its contents.
HTTP as a stateless protocol
Why it exists — If the server had to remember the earlier conversation for each request, the resources needed to keep that memory would grow with the number of users, and a conversation could not continue once a connection was cut. HTTP is defined so that a request can be handled by looking at that request alone, so the server does not have to remember anything between requests.
Where it's used today — Receiving web pages and images, a mobile app calling a server API, and a server calling another service's API are all done over HTTP. For features like chat, in which the server also has to send data first at any time, WebSocket is used together with it.
HTTP is a communication protocol in which a client sends a request and a server responds. Stateless means that the server does not remember the content of earlier requests, so each request must carry all the information needed to process it. Because the server keeps no state, any server can take a request, which makes it easy to add servers. Information that must carry over, such as a login state, is kept with cookies, sessions, or tokens.
HttpOnly, Secure, and SameSite
Why it exists — A cookie could originally be read by scripts on the page, and it was sent along even over unencrypted HTTP connections and with requests that started from other sites. The server attaches these attributes to each cookie in the Set-Cookie header to choose and block these paths.
Where it's used today — It is usual to attach all three to a login session cookie. In Spring Boot, they are attached to the session cookie with the http-only, secure, and same-site settings under server.servlet.session.cookie.
Attributes that protect cookies. HttpOnly stops JavaScript from reading the cookie, which prevents the cookie from being stolen by a script injection attack. Secure makes the browser send the cookie only over HTTPS connections. SameSite restricts sending the cookie with requests that start from another site, which reduces CSRF attacks, but it is a secondary defense used together with a CSRF token, not a replacement for it.
Session
A way to store a user's state on the server side and give the client only an identifier (the session ID) that points to that stored state, delivered in a cookie. The actual information is on the server, so the client cannot change its contents (having the session ID stolen is a different problem). When there are several servers, a common setup keeps this state in a shared store such as Redis so that any server that receives a request can find the same state.

Try these

Running with the default settings

  1. This is the login request. It is the first request, so the browser has no cookie for this site. The server checks the ID and the password in the body.
  2. The server sends Set-Cookie: sid=abc123; Path=/; HttpOnly in the response header. The browser stores this value as a cookie of shop.example. The server writes down on its own side that "abc123 is member 7".
  3. This is the request for shop.example/orders. The browser attached sid to the Cookie header automatically. It is attached even though the code does not add it anywhere. The server looks up abc123 and knows that the request is from member 7.
  4. This is the request for shop.example/shop/cart. This path falls under Path=/, so the cookie is attached.
  5. This is a request going to another site, other.example. The cookie that shop.example gave is not attached. A cookie is attached only to requests going to the host that sent it, shop.example (the Domain attribute can widen this).
  6. JavaScript on the shop.example/shop/cart page reads document.cookie. A cookie with HttpOnly is not visible to scripts. It is still attached to requests automatically.

Result of this run

Code

// Only the controller class body is shown (class declaration, imports, and the example LoginRequest, Member, memberService, and sessionStore declarations omitted)
@PostMapping("/login")
ResponseEntity<Void> login(@RequestBody LoginRequest req) {
    Member m = memberService.check(req.id(), req.password());
    String sid = sessionStore.create(m.getId());        // "abc123" → member 7

    ResponseCookie cookie = ResponseCookie.from("sid", sid)
        .path("/")
        .httpOnly(true)
        .build();
    return ResponseEntity.ok()
        .header(HttpHeaders.SET_COOKIE, cookie.toString())
        .build();
}
// Response header: Set-Cookie: sid=abc123; Path=/; HttpOnly

Assumptions of this model

All combinations of the settings were run with Chrome 158 on this computer (run without a window) and a test server, and it was confirmed that whether a Cookie header was attached to the /orders and /shop/cart requests, whether it was attached to a request to a different host (other.example), and whether the value was visible in document.cookie on the page all match the model. The Set-Cookie value that the server sent is the text that the code on the screen (ResponseCookie of Spring Framework 7.0.9) really produces, and that Expires is added together with Max-Age was also confirmed in that output. The test server was built with Node.js, and Chrome was made to send the names shop.example and other.example to the test server on this computer. "Closing the browser and opening it again" means that Chrome was shut down normally and then started again with the same user data directory, and the result was observed with the default startup setting of a new profile (Open the New Tab page). In that case, the cookie with no lifetime set was gone and the cookie with Max-Age=3600 remained. When Chrome was started again while restoring the last session (the same way of starting as the "Continue where you left off" setting; here it was run with the --restore-last-session option), the cookie with no lifetime set also remained. Other browsers were not checked. The Secure, SameSite, and Domain attributes are not covered in this lab.

Previous lab: HTTP/1.1, 2, 3 · Next lab: HTTP caching and ETag

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these