2

What are HTTP Cookies?

 4 months ago
source link: https://blog.bitsrc.io/web-http-cookies-bc84ed1816b0
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

What are HTTP Cookies?

Understand HTTP Cookies when building web apps in 2024!

1*zUC6qNw3wgO7gxHrNuuo7Q.png

Ever wondered how websites remember your preferences, keep you logged in, or even recommend personalized content?

Well, the answer lies in a small but clever technology called HTTP cookies. Let’s understand this in detail

What are HTTP Cookies?

Whenever a user makes an HTTP request to a server, the server creates a tiny packet of data known as cookies and includes them in the response. Upon receiving this response, the browser caches and retains these cookies in its memory. Subsequently, when the user initiates future requests to the same server, the stored cookies are automatically included in the request.

How do Cookies work?

Creation

When a user visits a website, the server sends a response header that includes a Set-Cookie header with the information to be stored.

HTTP/1.1 200 OK
Content-Type: text/html
Set-Cookie: theme=dark; name=makesh;

Storage

The browser stores this information, associating it with the specific domain.

Sending

Every subsequent request to the same domain includes the stored cookies in the Cookie header.

GET /path HTTP/1.1
Host: www.example.com
Cookie:theme=dark; name=makesh;

How cookies are useful?

Cookies might seem tiny, but they play a big role in making your internet experience smoother and more personalized.

Remembering You:

As HTTP is a stateless protocol, cookies help to maintain the state by storing the session identifiers, When a user logs in, a unique session cookie is created, allowing the server to recognize and maintain the user’s state throughout their visit.

Personalization and Preferences:

Cookies store user preferences, themes, and settings, enabling websites to present customized content based on individual choices.

Tracking and Analytics:

Cookies helps to monitor and record user activities as they navigate through the website, and it is used for personalized advertising, website analytics, and marketing.

Types of cookies

Cookies can be classified into the following types based on their usage and behavior

Session Cookies:

These cookies are created when a user visits a website and deleted when the browser is closed. Used to maintain the session, such as keeping the user logged in during a browsing session.

Persistent Cookies:

These cookies are stored on the user’s device for a specific period, even after closing the browser. Used to remember user preferences or login information.

First-Party Cookies:

These cookies are directly associated with the website being currently visited, being set by the domain featured in the browser’s address bar.

Third-Party Cookies:

These cookies are associated with a domain other than the one currently being visited, commonly set by external entities such as advertising networks or analytics services.

HTTP Headers and Attributes Related to Cookies

Cookies are handled by two major headers,

Set-Cookie: It is used by the server to set or update cookies on the HTTP response sent to the client

Set-Cookie: theme=dark; name=makesh;

Cookie: It is used by the client to send cookies back to the server with each HTTP request.

Cookie: theme=dark; name=makesh;

Cookie Attributes

Cookie attributes are additional parameters that developers can set to control aspects such as expiration, scope, security, and cross-site request behaviour for more precise management of cookies in web applications.

Below are the major cookie attributes

expires: It isused to specify the expiration date and time of a cookie.

Set-Cookie: name=makesh; expires=Sun, 10 Dec 2023 12:00:00 GMT;

this ensures that the particular cookie remains valid only till the specified date and time, If the expire attribute is not set, then the cookie is treated as a session cookie and expires when the browser is closed.

max-age: It is used to set the maximum age/ lifetime of a cookie in seconds.

Set-Cookie: name=makesh; max-age=3600;

it is an alternative to the expires attribute to define the lifetime of the cookie

If both expires and max-age is present in a cookie, then max-age attribute will take precedence and will be applied.

domain: It is used to specify the domains on which the cookie will be applicable.

Set-Cookie: name=makesh; domain=example.com;

this helps to allow cookies to be accessible across subdomains, If not specified, the cookie is valid only for the domain that set it.

path: It is used to specify the paths in allowed domains on which the cookie will be applicable.

Set-Cookie: name=makesh; path=/proile;

this helps to control which URLs within a domain can access the cookie, If not set the cookie is valid for the entire domain.

secure: Itensures the cookie is only sent over secure & encrypted connections (HTTPS)

Set-Cookie: name=makesh; secure;

this helps to enhance security by preventing the transmission of the cookie over unsecured connections, safeguarding sensitive information.

HttpOnly: It is used to restrict access to the cookie through client-side scripts (javascript)

Set-Cookie: name=makesh; HttpOnly;

this helps to mitigate the risk of cross-site scripting (XSS) attacks by preventing client-side scripts from accessing the cookie.

SameSite: It helps to determine whether a cookie should be sent with cross-site requests.

It can take three values,

Strict — Cookie will be sent in a first-party context. This means the cookie is sent only if the cookie belongs to the site currently shown in the browser's address bar.

Lax — Cookie will be sent if it is a safe HTTP request, such as a top-level HTTP GET or HEAD. A top-level request is an address that is entered into the navigation bar on a browser, or when a user clicks on a link from the current site that visibly changes the domain name in the bar.

If the SameSite attribute is not set, then lax becomes the default value.

None — Cookie will be sent with all same/ cross-origin requests. However, for security reasons, this should only be used when the cookie is marked as secure (only over HTTPS)

Accessing Cookies from the Client Side

Accessing cookies on the client side empowers developers to retrieve stored information, personalize user experiences, and dynamically modify the cookies

Cookies are represented as a lengthy string, where each set of values is separated by a semicolon (;)

Cookie: name=makesh; theme=dark; language=en; secure;

we can access it from javascript via documemt object

Reading a cookie

we can read all the cookies by accessing cookie property of document object.

const allCookies = document.cookie;
console.log(allCookies); // 'name=makesh; theme=dark; language=en;'

While usingdocument.cookie to access cookies in JavaScript, it only returns a semicolon-separated string containing the cookie name-value pairs. The document.cookie API does not expose other cookie attributes, such as the secure attribute or expiration date.

Adding/updating a cookie

To add or update a cookie, we can write directly to the document.cookie. If a cookie with the given key already exists, it will be updated; otherwise, a new cookie will be added.

document.cookie = 'sessionID=abc123; language=us';

const allCookies = document.cookie;
console.log(allCookies); // 'name=makesh; theme=dark; language=us; sessionID=abc123;'

Deleting a Cookie

To delete a cookie, we can modify the document.cookie property by setting its expiration date to a time in the past. This effectively invalidates the cookie, causing it to be removed by the browser.

const pastDate = new Date().getTime() - 1;

// removing sessionID
document.cookie = 'sessionID=; expires:' + pastDate.toUTCString();

const allCookies = document.cookie;
console.log(allCookies); // 'name=makesh; theme=dark; language=us;'

Prioritizing Privacy

When using cookies, especially for tracking and analytics, it’s vital to respect user privacy. Make sure you follow rules like the General Data Protection Regulation (GDPR). For official details related to GDPR rules, please check here.

So, that’s cookies — little web helpers making things smoother. They remember stuff and enhance our web experience.

Thanks for reading! I hope this article adds a little something to your web knowledge.

Keep learning and keep coding!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK