Cookies are small text based files that are sent from a website and stored locally by the users browser. They are required because HTTP has no way to keep track of a user's activity (i.e. stateless).
They have a maximum size of 4KB, for all attributes (e.g. name, key/values pairs)
Cookies can be used for various purposes from storing the user's name to their last visit.
Cookies have a very specific format that must be adhered to, and cannot include white space, semi-colons or commas.
They consist of several name/value pairs that are separated by a semi-colon.
The key/value is separated with an equals sign.
An optional expiration can be included, after which time it's deleted. If there's no expiration date, the cookie is deleted at the end of the session, or when the browser is closed.
Date has to be in UTC/GMT format.
Domain and Path can be specified where the cookie can be read / written. Default path is '/' (meaning visible to all paths in the domain), and if no path is specified it will belong to the page that set the cookie
The specific order for setting a cookie should be:
- Name-value pair containing the actual data
- Expiry date after which it is no longer valid
- Path within the domain
- Domain of the server it should be sent to
To create, read and delete cookies the document.cookie method is used:
document.cookie = "lastVisit=Thurs, 02 Aug 2013 09:53:00 GMT; expires=Thurs, 09 Aug 2013 00:00:00 GMT;";
document.cookie = "userLevel=novice;"
Use the console with the following to see the result:
To delete a cookie, simply set its date in the past.
This example has three functions to create, read and delete cookies. Two cookies are created and two buttons trigger the read and delete functions: