Cookies and Sessions


A typical HTTP request-response cycle is stateless because servers consider each incoming request to be a brand new one. The primary reason for this kind of behavior is to enable the server-side to service many incoming requests and increase scalability as a result. Many use cases need the server-side to remember what the client has done before—meaning some state is required for each client. For example, if a customer wants to reserve an airplane ticket, they have to go through several steps involved in this process. This process requires many pages to be accessed, and the user’s state (information) must be kept across all the pages. Cookies and sessions are the two ways to maintain the user’s state and improve the user’s experience. Let's discuss them in detail in the following sections.


A cookie is a small amount of data stored by a specific website (server) on the user's computer. The data stored in the cookies is labeled with a unique ID. It’s exchanged between a client's browser and the server, where the server reads the cookies and decides what information needs to be provided to the user.

Cookies contain information about the user's activity on the website. This includes the user's IP address, web browser type, version, operating system, and the pages the user has visited. Some other relevant information stored in a cookie includes clicks on different items or objects and the actions performed by the client—for example, views, time spent, items added to a cart, and so on.

When a user sends a request to a web server to visit a website, a response from the server contains the Set-Cookie header representing details about the cookies, as shown below. The client sends this cookie in response to future requests to the web server.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.