Let's start from beginning. You know browser has javascript engine, where we execute our javascript code, apart from this browser also have many things like Storage
, fetch() Api
, console.log()
, DOM Api
(all event listener, getElementById etc.), setTimeOut()
, Locations
and many more(Ya! you got it right, these things are not javascript, these are browsers things. These functionalities are browser features that are accessed through APIs).One of the feature which is provided by browser is Storage
(Ya! browser has its own storage which we can use in javascript code using Api's).
Browser has many types of storage namely Local Storage
, Session Storage
, Cookies
, IndexedDB
, Web SQL Database (Deprecated)
, Cache API
, Web Storage API (Deprecated)
etc.
You can see here.
You can see here, for storing data there are many types of Storage and one of it is cookies.
✒️Let's see what Cookie🍪 Storage is 😃😁 ...
Definition : Cookies are small pieces of data stored by websites on a user's web browser. They are commonly used to store information about the user's preferences, session state, and other data related to their interactions with a website.
So, It's used to store small data.
✒️Which type of data 🤔???.
We can store anything, but everything has purpose in this world. This Cookie storage is used to store specifically browsing data, session data, user behavior etc.
✒️Let's see an example😊.
You went a Travelling website "X". At start it will ask you to sign in/sign up. You logged in( means at back, it will send request to browser and will get a response related to log in(success/not success)). The response which website X's server sent back to website for successful login will also contain a data(cookie) with it (in response's header), which will be stored in Cookie Storage in yours browser.
This session cookie enables the website to maintain you the logged-in state throughout the Travelling booking process.
Means as you navigates through features in website or different pages in website, it will not ask every time Log in/Sign up.
It will use the cookie here, to identify that its the same user(you).
So, Here you saw how cookie helps in user to stay logged-in across different pages in a website..
There are many more things like User Tracking
,personalization
, Advertisement
(how you see Ads specific to your interest) etc, We will see in later part.
Let's first see cookie's features.
✒️How cookie looks 🤔🤔🤔...
Ya! you saw right😁. cookie are stored name=value pair.
🍪Structure
A cookie is represented as a key-value pair, where the
key is the name of the cookie
, andthe value is the data associated with it
. Cookies also have attributes such as expiration date, domain, and path, which provide additional control over how the cookies are used and accessed.
Zoom in 🔍the above to above image...
These are the attributes of cookies.
✒️Let's see one by one😃.
- expires: Specifies the expiration date of the cookie. Once the expiration date is reached, the cookie will be automatically deleted by the browser.
- domain: Specifies the domain for which the cookie is valid. By default, cookies are valid for the domain that set them. You can set any domain to which you want to keep the cookies.
- path: Specifies the URL path for which the cookie is valid. By default, cookies are valid for the entire domain.
- secure: If set to true, the cookie will only be sent over secure HTTPS connections.
- httponly: If set to true, the cookie will be inaccessible to JavaScript, reducing the risk of certain types of attacks like XSS.
OH!! Lot's of theory. Let's implement 💻and create a cookie🍪.
NOTE: There are many other ways to add cookies and many other library with which we can set cookie. This is simplest way to add cookie.
🍪Setting a Cookie:
document.cookie = 'username=John; expires=Thu, 17 Jul 2025 12:00:00 UTC; path=/';
First we write a cookie name and value, then after semicolon attributes. If want to add more attributes give semcolon then add.
Yo, cookie is set.
Zoomed in🔍.
Add one more cookie.
document.cookie = 'product=dairy';
It will not replace the previous one, it will add next cookie (no need of +=).
Ok, So you learned how to add a cookie. In second example, you just added a cookie, no attributes. In this case, in expires section it will set to session
which means that as soon as you close the browser(click on red cross button), the second cookie will expire because it is for this session only.
🍪Getting Cookies:
const allCookies = document.cookie;
console.log(allCookies);
Above code illustrates, If all cookies are get printed.
function getCookie(cookieName) {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.startsWith(cookieName + '=')) {
return cookie.substring(cookieName.length + 1);
}
}
return null; // Return null if the cookie is not found
}
Pass cookie name in function.
const myCookieValue = getCookie('your_cookie_name');
if (myCookieValue) {
console.log('Value of "your_cookie_name":', myCookieValue);
} else {
console.log('Cookie not found.');
}
Above code illustrates, If you want a specific cookie value
.
🍪Removing a Cookie:
The basic way to remove a cookie is to set to previous date which has passed.
document.cookie = 'username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
✒️Some important points to note.
- Cookies can have an expiration date, after which they will be automatically deleted by the browser.
- Cookies without an expiration date are called session cookies and are deleted when the user closes the browser.
- Cookies are specific to a domain. Each domain can set and access its own cookies, and one website cannot access cookies set by another website due to the same-origin policy, which enhances security.
- Cookies are accessed through the
document.cookie
property in JavaScript. This property contains a string representation of all the cookies associated with the current domain.
Let's conclude by writing a complete code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="box">
Here data will be there.
</div>
<button id="btn">click</button>
<script>
// Function to set the cookie with all the options
function setCookie(name, value, domain, path, expiration, secure, httpOnly, sameSite) {
let cookieOptions = `${name}=${encodeURIComponent(value)}`;
if (domain) {
cookieOptions += `; Domain=${domain}`;
}
if (path) {
cookieOptions += `; Path=${path}`;
}
if (expiration) {
const expirationDate = new Date(expiration * 1000).toUTCString();
cookieOptions += `; Expires=${expirationDate}`;
}
if (secure) {
cookieOptions += `; Secure`;
}
//if (httpOnly) {
//cookieOptions += `; HttpOnly`;
//}
if (sameSite) {
cookieOptions += `; SameSite=${sameSite}`;
}
document.cookie = cookieOptions;
console.log(document.cookie);
}
// Example usage
const userPreferences = { theme: "dark", language: "en", showNotifications: true };
const encodedPreferences = JSON.stringify(userPreferences);
// Set the cookie for localhost (Empty string for domain)
setCookie(
"user_preferences_cookie",
encodedPreferences,
"",
"/",
1697171200,//till 13/10/2023 9:56:40 AM
true, // Set to true for "Secure" attribute
true, // Set to true for "HttpOnly" attribute
"Strict"
);
</script>
</body>
</html>
Output :
This example demonstrates how to create a cookie with multiple options for localhost http://127.0.0.1/ => "" website ". The cookie named "user_preferences_cookie
" stores user preferences in JSON format and is set to expire on 13/10/2023. Additionally, the SameSite
attribute is set to "Strict
", ensuring that the cookie is sent only in first-party contexts.
✒️Advantages
-
Persistence: Cookies persist across different browser
sessions
and can be used to remember user preferences and maintain session state. - Client-Side Storage: Cookies are stored on the client-side, reducing the need for frequent server-side communication for certain types of data.
- Simple API: The document.cookie property provides a simple way to interact with cookies, making them accessible to developers of all skill levels.
✒️Disadvantages
-
Size Limit: Cookies are limited in size (usually
4 KB per cookie
and a total limit of around300 cookies per domain
), which can be a limitation for storing larger amounts of data. - Sent with Every Request: Cookies are sent with every HTTP request to the domain they belong to, which can add some overhead, especially if a website has many cookies.
-
Security Concerns: As cookies are accessible by JavaScript on the client-side, they can be susceptible to certain security risks, such as
Cross-Site Scripting (XSS)
attacks orCross-Site Request Forgery (CSRF)
attacks if not used and secured properly. - Limited to String Data: Cookies can only store data in string format. Complex data types like objects and arrays need to be serialized into strings before storage, which can add complexity to the code.
✒️Who actually sets Cookies??🤔🤔
Cookies are typically set by web servers and sent to the user's web browser during HTTP responses. When a user visits a website, the web server can include a "Set-Cookie" header in the HTTP response to instruct the browser to create and store a cookie on the user's device.
The "
Set-Cookie
" header contains the necessary information to create the cookie, including its name, value, attributes (e.g., expiration date, domain, path, etc.), and other optional settings like security attributes (Secure and HttpOnly). Once the browser receives the "Set-Cookie
" header, it creates the cookie and stores it locally on the user's device as instructed by the server.For example, when a user logs into a website, the server may respond with the following "
Set-Cookie
" header to create a session cookie:Set-Cookie: session_id=abc123; path=/; HttpOnly
In this example, the server instructs the browser to create a session cookie named "
session_id
" with the value "abc123
." The cookie is set to be accessible only via HTTP (HttpOnly) and is valid for all paths on the website (path=/).Once the cookie is set, the browser will automatically include the cookie in subsequent HTTP requests to the same domain. This allows the server to identify the user and maintain session state, personalization, and other relevant information.
It's important to note that certain types of cookies, such as HttpOnly cookies, can only be set by the server and cannot be accessed or modified by client-side JavaScript. This enhances security by preventing certain types of attacks, like
Cross-Site Scripting (XSS)
, from accessing sensitive cookie data.So concluding, Web servers set cookies to provide a way to store information on the user's browser, enabling stateful interactions between the user and the website and enhancing the overall user experience.
✒️What happens after a Cookie🍪 is set, and How it saves data and tracks user interactions🤔🤔
After a cookie is set and stored on the user's browser, it becomes part of the user's browsing experience, and its data and behavior depend on the attributes and settings defined when the cookie was created.
Here's what happens after a cookie is set, and how it saves data and tracks user interactions:
📍Subsequent Requests:
As the user continues to interact with the website or moves to different pages within the same domain, the browser automatically includes the cookie in the headers of all subsequent HTTP requests to that domain.For example, if the website has a navigation menu or loads additional resources, like images or scripts, the browser sends the cookie information along with each request to the server.
📍Retrieving Data:
When the browser includes the cookie in an HTTP request, the server can access the cookie data and use it to identify the user and maintain session state.For example, if the server set a session cookie with a user's
unique session ID
, it can retrieve the session ID from the cookie in subsequent requests to identify the user and provide personalized content or access to restricted areas of the website.📍Session Management:
Session cookies
are often used to manage user sessions. When the user logs into a website, the server sets a session cookie, and subsequent requests include the session cookie to maintain the user's login status.The server can use the session cookie data to determine if the user is logged in and provide access to authenticated features.
📍User Tracking and Personalization:
Persistent cookies
are commonly used to track user preferences and behaviors across different visits to the website. This tracking helps websites offer personalized content and recommendations to users based on their previous interactions.For example, if a user visits an online store and adds items to their cart without making a purchase, the website might use a
persistent cookie
to remember the user's cart contents when they return later.📍Expiry and Deletion:
If a cookie has an expiration date, the browser will automatically delete the cookie after that date is reached. This allows for time-limited functionality or data storage.For example, a website might use a
persistent cookie
to remember a user's language preference for a year, while a session cookie might only be valid for the duration of the browsing session.📍Security Considerations:
Secure
andHttpOnly
attributes in cookies enhance security. Secure cookies are only sent over HTTPS connections, ensuring that sensitive data is encrypted during transmission. HttpOnly cookies are inaccessible to client-side JavaScript, protecting against certain types of attacks like XSS.
✒️Types of Cookies🍪
📌Session Cookies:
Session cookies are temporary cookies that are stored in the browser's memory and are only active during a browsing session. They are typically used to remember user preferences or track the user's activities within a single session. Once the user closes the browser, session cookies are deleted.
Example: Shopping Cart
When a user adds items to their shopping cart on an online store, session cookies can be used to keep track of the items during their browsing session. Once the user completes their purchase or leaves the website, the session cookies are deleted, clearing the shopping cart.
📌Persistent Cookies:
Persistent cookies, also known as permanent cookies, are stored on the user's device even after the browser is closed. They have an expiration date set by the website and remain on the user's device until that date or until the user manually deletes them. Persistent cookies are used for long-term data storage, such as remembering login information or user preferences across multiple sessions.
Example: "Remember Me" Option
On a website's login page, users may have the option to check a "Remember Me" box. If they select this option, a persistent cookie is set with their login credentials. This allows them to stay logged in even after they close the browser or revisit the website at a later time.
📌First-party Cookies:
First-party cookies are set by the website domain that the user is directly visiting. These cookies are used to improve the user experience on that specific website, remember user preferences, and store session-related information.
Example: User Preferences
A website may use first-party cookies to remember a user's preferred theme (e.g., light or dark mode), font size, or language selection, providing a personalized experience for the user during their visit.
📌Third-party Cookies:
Third-party cookies are set by domains other than the one the user is directly visiting. These cookies are usually created by third-party services (such as advertising or analytics providers) that are embedded in the website the user is browsing. Third-party cookies are often used to track users across multiple websites and gather data for advertising and analytics purposes.
Example: Advertising Tracking
When a user visits a website that displays ads from an advertising network, the website may use third-party cookies to track the user's browsing behavior across different websites. This data is used to serve targeted ads based on the user's interests and activities.
📌Secure Cookies:
Secure cookies are cookies that are transmitted over HTTPS instead of HTTP. They are encrypted and provide an extra layer of security, ensuring that the data stored in the cookie is less susceptible to interception by malicious entities.
Example: Secure Login
For websites that handle sensitive information like online banking or personal data, secure cookies are used to store session identifiers securely. These cookies are transmitted over HTTPS, making it difficult for attackers to intercept and tamper with the cookie data.
📌HttpOnly Cookies:
HttpOnly cookies are designed to be inaccessible through client-side scripts (e.g., JavaScript). They can only be accessed and modified by the server, which helps mitigate the risk of cross-site scripting (XSS) attacks.
Example: Authentication Tokens
HttpOnly cookies are commonly used for storing authentication tokens. When a user logs in to a website, the server sets an HttpOnly cookie containing the authentication token. This prevents malicious scripts from accessing the token and helps protect against cross-site scripting (XSS) attacks.
📌SameSite Cookies:
SameSite cookies define whether a cookie should be sent with cross-origin requests. This attribute helps prevent certain types of CSRF (Cross-Site Request Forgery) attacks. SameSite cookies can have three possible values: "Strict," "Lax," or "None."
Example: CSRF Prevention
Websites often use SameSite cookies to prevent Cross-Site Request Forgery (CSRF) attacks. By setting SameSite attributes to "Strict" or "Lax," the website ensures that the cookie is not sent in cross-origin requests, making it harder for attackers to initiate unauthorized actions on behalf of the user.
📌Flash Cookies (Local Shared Objects):
Flash cookies are not related to traditional web browser cookies but serve a similar purpose in Flash applications. These cookies are stored by Adobe Flash Player and can track user preferences and data across different Flash-based websites.
Example: Flash Game Progress
In Flash-based games or applications, Flash cookies can be used to store game progress, user preferences, and other data locally. This allows users to resume their game from where they left off, even if they close the browser or visit the website on a different device.
Happy Learning!! , Until next time🫂.
If you liked the article, do hit like😃.
Top comments (0)