Cookies are the most widely used solution to implement a stateful communication between the web client (i.e., browser) and the web server, over a stateless protocol (HTTP/HTTPS).
Specifically, cookies come to hand when the client is requesting to present its credentials to log in and authenticate to the web server. How?
Assume the client C wants to log in at the server S. To do that, C usually sends to S its credentials (i.e., typically a
username and a
password), hopefully over a secure channel (HTTPS). Upon verifying the received credentials are actually valid, i.e., there’s a valid entry corresponding to the received (username, password) pair in the server back-end, S replies to C with a status code to tell C that its request was handled correctly (e.g.,
200 OK). Furthermore, S stores a cookie in its back-end, which uniquely identifies the client C, and it attaches that cookie to its HTTP(S) response header. Once C receives back the HTTP(S) response from S, it also receives the cookie that the server has previously associated with it. The client will automatically attach that cookie to any subsequent HTTP(S) request to the server. In such a way, S is always able to recognize C across several distinct HTTP(S) requests, thus to possibly restore any state information about C.
To clarify better on this, please refer to the picture below.