Flat Preloader Icon

JS Cookies

Cookies are small pieces of data stored on a user’s device by a web browser. They are commonly used to store information about the user’s browsing session, preferences, authentication tokens, and other data that can be useful for personalizing the user experience or tracking user behavior.

Creating Cookies:

  • Cookies are created using the document.cookie property in JavaScript. You can set cookies by assigning a string in the format "key=value" to document.cookie.
				
					document.cookie = "username=John Doe";
document.cookie = "language=en";

				
			

Reading Cookies:

  • You can read cookies using the document.cookie property. It returns a semicolon-separated string containing all cookies associated with the current document.
				
					console.log(document.cookie); 
// Output: "username=John Doe;
language=en"

				
			
  • To extract specific cookies, you need to parse the document.cookie string. This is typically done using helper functions or regular expressions.

Deleting Cookies:

  • To delete a cookie, you can set its value to an empty string and optionally specify an expiration date in the past.
				
					document.cookie = "username=; expires=Thu,
01 Jan 1970 00:00:00 UTC";

				
			

Cookie Attributes:

  • Expires: Specifies the expiration date and time for the cookie.
  • Max-Age: Specifies the maximum age of the cookie in seconds.
  • Domain: Specifies the domain for which the cookie is valid.
  • Path: Specifies the path within the domain for which the cookie is valid.
  • Secure: Specifies whether the cookie should only be sent over secure HTTPS connections.
  • HttpOnly: Specifies whether the cookie is accessible only through HTTP requests and not through JavaScript.
				
					document.cookie = "username=John Doe;
expires=Thu, 18 Dec 2024 12:00:00 UTC; path=/";
document.cookie = "language=en;
max-age=3600; path=/";

				
			

Limitations and Security Concerns:

  • Size Limit: Cookies are limited in size (typically a few kilobytes per cookie) and the number of cookies per domain.
  • Security: Cookies are susceptible to security vulnerabilities such as cross-site scripting (XSS) and cross-site request forgery (CSRF). It’s important to sanitize and validate cookie data to prevent attacks.
  • Privacy Concerns: Cookies can be used for tracking user behavior across websites, raising privacy concerns. Regulations such as the GDPR require websites to obtain user consent before storing certain types of cookies.

Alternatives:

  • Web Storage: Web storage APIs (localStorage and sessionStorage) provide alternatives to cookies for storing larger amounts of data locally on the user’s device.
  • IndexedDB: IndexedDB is a more powerful client-side storage mechanism for storing structured data in the browser.