What are Cookies

Course- Javascript >

Something that the JavaScript techniques that you have seen so far can’t do is transfer information from one page to another. Cookies provide a convenient way to give your web pages the means to store and retrieve small pieces of information on a user’s own computer, allowing your website to save details such as a user’s preferences or dates of his or her prior visits to your site.

In this section you learn how to create, save, retrieve, and delete cookies using JavaScript.

What Are Cookies?

The HTTP protocol that you use to load web pages into your browser is a so-called stateless protocol. This means that once the server has delivered the requested page to your browser, it considers the transaction complete and retains no memory of it. This makes it difficult to maintain certain sorts of continuity during a browsing session (or between one session and the next) such as keeping track of which information the visitor has already read or downloaded, or of his or her login status to a private area of the site.

Cookies are a way to get around this problem; you could, for example, use cookies to remember a user’s last visit, save a list of that user’s preferences, or keep track of shopping cart items while he or she continues to shop. Correctly used, cookies can help improve the experience perceived by the user while using your site.

The cookies themselves are small strings of information that can be stored on a user’s computer by the web pages he or she visits, to be later read by any other web pages from within the correct domain and path. Cookies are set to expire after a specified length of time.

Limitations of Cookies

Your browser may have a limit to how many cookies it can store—normally a few hundred cookies or more. Usually, 20 cookies per domain name are permitted. A total of 4KB of cookie information can be stored for an individual domain.

In addition to the potential problems created by these size limitations, cookies can also vanish from a hard disk for various reasons, such as the cookie’s expiry date being reached or the user clearing cookie information or switching browsers. Cookies should therefore never be used to store critical data, and your code should always be written to cope with situations where an expected cookie cannot be retrieved.