In this lesson, you will learn how to use HTTP headers to bridge the gap between stateless network requests and persistent user sessions.
Since HTTP is a stateless protocol, the server forgets everything about a client the moment a response is sent. To maintain a "state" (like keeping a user logged in), we use Cookies. A cookie is essentially a small piece of data that the server asks the browser to store and return in every subsequent request.
The Mechanism
The process works through two specific HTTP headers:
- Setting State (
Set-Cookie): When the server wants to remember a client, it sends aSet-Cookieheader in its HTTP response. The browser saves this value locally. - Recalling State (
Cookie): On every subsequent request back to that domain, the browser automatically attaches the stored information to aCookieheader.
Practical Implementation
In a Node.js http server, you don't need a library to handle this manually—you simply manipulate the raw header strings.
const http = require('http');
http.createServer((req, res) => {
// Parsing: Look for the 'cookie' header sent by the client
const cookieHeader = req.headers.cookie;
if (!cookieHeader) {
// Injecting: Set a new cookie for the user
res.setHeader('Set-Cookie', 'user_id=12345; HttpOnly');
res.end('Welcome! I have set your session ID.');
} else {
res.end(`Welcome back! I found your cookie: ${cookieHeader}`);
}
}).listen(3000);
Why this matters
In our previous lessons, we discussed how TCP keeps a connection alive, but that only handles the transport. Cookies handle the application layer. By reading the Cookie header, your server identifies the specific user making the request, allowing you to associate requests with a persistent session ID even if the underlying TCP connection is closed and reopened.
When you send a Set-Cookie header, the browser becomes the temporary "storage unit" for your server's state, neatly solving the stateless nature of HTTP.
Key Takeaway: Cookies allow your stateless HTTP server to maintain identity by instructing the client to store and echo back small pieces of session data in every request header.