What is an HTTP cookie?
An HTTP cookie (a.k.a web browser cookie) is a small piece of data that a server sends to a user’s web browser, which stores them on the client and sends it back to the server with every HTTP request. They are used for various purposes such as identifying users, store their preferences and track their behavior for advertisment targeting. Below are some common applications:
- Authentication and session management: The server needs to remember whether the user is authenticated or not by sending a session token to the client, which is stored by the browser and sent back to the server for every subsequent request. The server typically regenerates and resends session cookies to avoid Man-in-the-middle (MitM) attacks (session hijacking).
- Personalization: The user may choose a particular language or theme once and the browser stores these preferences in cookies to be sent back to the server with future requests, so the server remembers the user preferences.
- Tracking: Analyzing user behavior and providing recomendations accordingly.
On the client side, cookies are stored by the browser and accessible from the browser window
Note: The browser stores cookies on the client and sends them back to the server with every HTTP request. This may impact performance especially on small devices such mobile devices.
How cookies are created
1) Setting Cookies in the HTTP Response by the Web Server
Cookies are often created by the web server when sending an HTTP response by adding an HTTP header called Set-Cookie
. Below is an example of a simple Set-Cookie
HTTP response header:
Syntax:
Set-Cookie: <cookie-name>=<cookie-value>
Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>
Set-Cookie: <cookie-name>=<cookie-value>; Max-Age=<number>
Examples:
Set-Cookie: theme=dark
Set-Cookie: lang=ar; Expires=Wed, 21 Oct 2022 07:30:00 GMT
Set-Cookie: clientId=yfr4747hgh; Max-Age=86400
These cookies are stored by the browser on the client device.
2) Creating and Accessing Cookies in JavaScript
Cookies can be created and accessed via JavaScript using the document.cookie
API.
Example: creating cookies
|
|
background=dark; lang=ar; zone=arabian; profileId=1dsf32f39
The document.cookie
API allows you to read and write cookies associated with the document. It behaves as a getter and setter for values of the web page cookies. Cookie values are stored as a string containing a semicolon-separated list of all cookies (key=value pairs) with a single space after the semicolon. Note that we set a cookie using document.cookie
using one statement per cookie since we can’t set multiple cookies in one statement.
Example: accessing cookies
To access a cookie, we need to treat it as a string and split the key value pairs by the ;
separator.
// accessing the previous cookies (background=dark; lang=ar; zone=arabian; profileId=1dsf32f39)
let myCookies = document.cookie.split(";");
let backgroundColor = myCookies[0].split("=")[1];
let language = myCookies[1].split("=")[1];
let zone = myCookies[2].split("=")[1];
let profileId = myCookies[3].split("=")[1];
console.log(backgroundColor, language, zone, profileId);
dark ar arabian 1dsf32f39
Cookies lifetime
Cookies may expire in one of the following ways:
- Session cookies are deleted when the current session ends (e.g., logging out or after a period of inactivity). These cookies are set with no expiration date (no
expires
normax-age
attribute when the cookie is created). - Permanent cookies are deleted at the date specified by the
expires
attribute when the cookie is created or after expiration as indicated in themax-age
.
Example: Setting cookies in an HTTP response
To set an HTTP cookie by the server, send an HTTP response with the following header:
Set-Cookie: theme=dark; Expires=Mon, 12 Dec 2022 00:00:00 GMT;
Set-Cookie: lang=ar; Max-Age=86400;
Example: Setting Cookies with JavaScript
// setting a cookie that expires on a specific data
document.cookie = "lang=ar; expires=Thu, 03 Mar 2022 23:59:00 UTC";
// setting a cookie that expires in 1 day (24*60*60=86400 seconds)
document.cookie = "profileId=1dsf32f39; max-age=86400";
Note: The cookie expiration date is always the date on the client not the server.
Cookies are set by browser may be deleted by the browser’s user by clearing the session.
Cookie Storage Inspector: View and Delete Cookies
You can inspect all cookies created by a webpage or any iframes inside the web page in your web browser’s inspector/DevTools.
Chrome:
- Open Chrome DevTools: press
Control
+Shift
+I
(Windows, Linux, Chrome OS) orCommand
+Option
+I
(Mac). - Click the Application tab to open the Application panel.
- Under Storage, expand Cookies, then select the origin of the cookie (the URL of the web page that created the cookie).
- Open Chrome DevTools: press
Firefox:
- Open Firefox Developer Tools: press
Control
+Shift
+I
(Windows, Linux, Chrome OS) orCommand
+Option
+I
(Mac). - Click the Storage tab to open the Storage panel.
- Expand Cookies, then select the origin of the cookie (the URL of the web page that created the cookie).
- Open Firefox Developer Tools: press
To delete a cookie, right click on a cookie and select delete. To clear cookies, right click on the expanded Cookies and select clear or delete all.
You may also view all cookies for any web page by going through the history of your browser. For example, in Chrome, you can view all stored cookies by going to chrome://settings/cookies in the address bar.
Accessing Cookies Sent by the Web Server
When the web server sends a response to the client, the response may include cookies in the HTTP response header Set-Cookie
. Below is how you can access these cookies:
- Open the Browser’s developer tools and click on the network tab. Then, go to https://google.com.
- Click on the origin www.google.com.
- Expand the response header and scroll down until you see a header that starts with
Set-Cookie:
as shown below.
Restricting Access to Cookies
Cookies that are sent with the HttpOnly
attribute are NOT available to JavaScript and inaccessible to the Document.cookie
API.
Cookies that are sent with the Secure
attribute are only sent over HTTPS and are never sent with unsecured HTTP (except on localhost for testing).
Set-Cookie: theme=dark; Expires=Mon, 12 Dec 2022 00:00:00 GMT; HttpOnly; Secure;
For more information on cookies, refer to the MDN’s article Using HTTP cookies.
Example: Storing User’s Preferences
Other Options for Storing on the Client
In addition to cookies, data can be stored on the client in two other mechanisms:
- Session Storage: The browser maintains additional storage area for a given origin until the browser (window or tab) is closed. The advantage of using session storage over a cookie or session storage is that data is always kept on the client and never sent to the server. Session storage also has a larger limit than a cookie (~ 5MB per origin). Session storage is available via the
Window.sessionStorage
property of thewindow
object.
- Example:
window.sessionStorage.setItem('key', 'value'); console.log(window.sessionStorage.getItem('key');
- Local Storage: Similar to session storage but data is kept even if the browser (window or tab) is closed. The advantage of using local storage over the other two options (cookie and session storage) is that data is stored with no expiration date and has a much larger storage limit amongst the two other options (~ 10MB per origin). Local storage is available via the
Window.localStorage
property of thewindow
object.
- Example:
window.localStorage.setItem('key', 'value'); let val = window.localStorage.getItem('key'); console.log(val);