Javascript Cookies

You are currently viewing Javascript Cookies

Javascript Cookies

Cookies in JavaScript are small pieces of data that a web server sends to a user’s web browser and are stored on the user’s device. Cookies are used to store information on the client-side (the user’s browser) that can be sent back to the server with each HTTP request, providing a way to maintain state and store user-specific data across multiple page views or sessions. The next time the user visits the website, the browser sends the cookies back to the server, allowing it to retrieve the stored information.

How Cookies Works?

  • When a user sends a request to the server, then each of that request is treated as a new request sent by the different user.
  • So, to recognize the old user, we need to add the cookie with the response from the server.
  • browser at the client-side.
  • Now, whenever a user sends a request to the server, the cookie is added with that request automatically. Due to the cookie, the server recognizes the users.

In JavaScript, cookies can be created, read, and deleted using the document.cookie property.

  • With JavaScript, a cookie can be created like this:

				
					document.cookie = "username=Vishal";
				
			

we can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed:

				
					document.cookie = "username=Vishal; expires=sun, 5 Oct 2023 12:00:00 UTC";
				
			

With JavaScript, cookies can be read like this:

				
					var x = document.cookie;
				
			

document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;

cookies are commonly used for various purposes

  • Session Management: Storing session IDs to keep track of user sessions.
  • User Authentication: Remembering user login status.
  • Personalization: Storing user preferences or settings.
  • Shopping Carts: Storing items in a user’s shopping cart during an e-commerce session.
  • Tracking: Collecting analytics data or tracking user behavior.

Leave a Reply