HTTP Cookie vs Session ?

HTTP Cookie

An HTTP cookie (also known as web cookie, Internet cookie, browser cookie, or simply cookie) is a small piece of data that is stored on the user’s computer by the web browser while browsing a website.

For example, if I go to medium.com in my web browser, I can see all the cookies that are used by medium.com:

Cookies are designed to be a reliable mechanism for websites to remember stateful information (such as items added in the shopping cart in an online store) or to record the user’s browsing activity (including clicking particular buttons, logging in, or recording which pages were visited in the past).

  • When a user visits a website for the first time, the server sends a set of cookies to the user’s browser. The browser will then store these cookies and send them back to the server with each subsequent request.
  • The server can then use these cookies to identify the user, remember their preferences, track their session, etc. This enables the server to send a personalized response based on the information it receives.

Cookies can also be used for more controversial purposes, such as tracking user behavior across multiple sites for advertising profiling. This has raised privacy concerns and led to the development of laws and regulations in some places to provide users with more control over how their data is used.

How Does Cookie Work?

  • When a user visits a website for the first time, the server sends a set of cookies to the user’s browser. The browser will then store these cookies and send them back to the server with each subsequent request.
  • The server can then use these cookies to identify the user, remember their preferences, track their session, etc. This enables the server to send a personalized response based on the information it receives.

Setting a Cookie

When a server wants to set a cookie, it includes a Set-Cookie header in the HTTP response.

HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: sessionId=38afes7a8; Expires=Wed, 21 Oct 2025 07:28:00 GMT; Secure; HttpOnly
...

In this example, the server sends a Set-Cookie header with the cookie's name (sessionId) and the cookie's value (38afes7a8). The Expires attribute tells the browser when to delete the cookie. The Secure attribute instructs the browser to only send the cookie over an encrypted HTTPS connection. The HttpOnly attribute restricts the cookie from being accessed by JavaScript.

Sending a Cookie

After a cookie has been set, the browser will include it in the Cookie header for every subsequent HTTP request to the same domain.

GET /sample_page.html HTTP/1.1
Host: www.example.com
Cookie: sessionId=38afes7a8
...

Then the browser sends the sessionId cookie with its value back to the server in the Cookie header.

Where is Cookie Stored?

HTTP cookies are stored on the client’s computer in the web browser’s storage. The exact location on the file system depends on the browser and the operating system.

Here are the default storage locations for some popular web browsers:

  • Google Chrome: In Windows, Chrome stores cookies in a SQLite database file located in the user’s profile folder: C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default\Cookies. In macOS, this file is located at ~/Library/Application Support/Google/Chrome/Default/Cookies.
  • Internet Explorer and Microsoft Edge: Both Internet Explorer and the original version of Microsoft Edge store cookies in text files in the user’s profile folder under C:\Users\YourUsername\AppData\Local\Microsoft\Windows\INetCookies.

How Does Browser Use Cookie?

  1. Setting Cookies: When your browser sends a request to a website, the server can respond with not only the requested webpage but also a Set-Cookie HTTP header. This header contains the name, value, and other attributes of the cookie, including when it should expire, whether it should only be sent over secure connections, and so on.
  2. Storing Cookies: Your browser will store this cookie, typically in a file on your computer’s hard drive. This file is managed by the browser and is separate from other user files for security and privacy reasons.
  3. Reading Cookies: The next time you request a page from the same site, the browser adds the stored cookies to the HTTP request in a Cookie header. This way, the website can "remember" information about your previous interactions with the site.
  4. Updating Cookies: If the server needs to update the value of a cookie or set a new cookie, it does so using the Set-Cookie header in the HTTP response. The browser will update its stored cookies accordingly.

Python Example

from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/')
def index():
    username = request.cookies.get('username')
    # use cookies.get(key) instead of cookies[key] to not get a
    # KeyError if the cookie is missing
    return 'Username: {}'.format(username)

@app.route('/setcookie', methods=['POST'])
def setcookie():
    resp = make_response('Setting cookie!')
    resp.set_cookie('username', request.form['username'])
    return resp

@app.route('/delcookie')
def delcookie():
    resp = make_response('Deleting cookie!')
    resp.delete_cookie('username')
    return respSession

An HTTP session is a sequence of network request-response transactions. When either party sends a TCP FIN packet (signifying the end of the communication), the session is considered closed.

HTTP itself is a stateless protocol, meaning each request-response pair is independent and does not maintain any information about the state of communication. However, in a web application, it is often necessary to maintain state across multiple HTTP transactions. This is typically done using sessions.

A session is started when a user logs into a web application or starts interacting with the application in some way (like adding an item to a shopping cart).

A session identifier (often a long, randomly generated string) is created and sent to the client, typically in a cookie, but sometimes as a parameter in the URL. The server associates this session identifier with the user’s state, such as their authentication status, user profile information, and so on.

For every subsequent request the client makes to the server, it includes the session identifier (from the cookie or the URL). The server looks up this session identifier and retrieves the associated state information. This allows the server to “remember” the user and their interactions with the application across multiple HTTP requests.

Python Example

from flask import Flask, session

app = Flask(__name__)
app.secret_key = 'some_secret_key'

@app.route('/')
def index():
    if 'username' in session:
        return 'Logged in as %s' % escape(session['username'])
    return 'You are not logged in'

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        session['username'] = request.form['username']
        return redirect(url_for('index'))
    return '''
        <form method="post">
            <p><input type=text name=username>
            <p><input type=submit value=Login>
        </form>
    '''

@app.route('/logout')
def logout():
    # remove the username from the session if it's there
    session.pop('username', None)
    return redirect(url_for('index'))Cookie vs Session

Cookie is a part of the HTTP protocol, while Session can be independent of HTTP (TCP, WebSocket, etc., can also use session)

Client side vs Server side

A cookie is a small piece of data stored on the client’s computer by the web browser at the request of a server.

An HTTP session is a server-side storage mechanism to store user-specific data during a series of requests to a web application.

Security

Since session data is stored on the server, it is generally considered safer than cookie storage because it’s less susceptible to certain types of attacks like cross-site scripting (XSS). However, the session ID stored in the client’s cookie must also be secured to prevent session hijacking.

Data Lifespan

Cookie data has a set lifespan defined by its expiry date. Once this date is reached, the data is deleted. Session data, on the other hand, persists for the duration of the user’s interaction with the web application and is typically deleted when the session is explicitly closed (such as when a user logs out) or after a period of inactivity.

Storage Capacity

Cookies have a maximum size limit (4KB is a common limit across most browsers). Sessions don’t have this limit, but storing large amounts of data in a session can affect the performance of your web server.

Content

Cookies can store various key-value pairs (and can store other things); Sessions are specifically used to save user information.


#cockie #session

HTTP Cookie vs Session ?
1.05 GEEK