🧁 🧁 🧁 not quite… 🍪🍪🍪 Better! The cookie 🍪 is one of the web’s favorite emoji and it’s also one of web’s most important technology.
Let’s take a look at what it’s all about, shall we?
Browser cookies were introduced to the web in order to keep persistent information about the user. The first use case was to check if a user had already visited Netscape’s website.
Cookies are strings that have a name field, a value field and additional optional attributes. The values are strings and you can store whatever you think is best for your application. Google Analytics’ _ga
is probably one of || the
most common cookie out there, it usually looks like this:
Cookies can store up to 4096 bytes of data (this includes name, value, domain, expiry date and whatever else you can fit in there). You can add a limited number of cookies per domain which changes depending on your browser.
There are two main ways to create cookies:
Set-Cookie
in your HTTP response header. Depending on the technologies you are using for your web server; you can use different tools and libraries to manage cookie headers. These tools should create HTTP responses which will roughly look like this:HTTP/2.0 200 OK
Content-type: text/html
Set-Cookie: alligator_name=barry
Set-Cookie: tasty_cookie=strawberry
... More http Content
You can add information to your cookies like an expiration date, and security features such as the Secure directive and the HttpOnly flag.
Set-Cookie: cookie_name=cookie_value; Expires=Wed, 17 Sep 2021 07:00:00 GMT; Secure; HttpOnly
The HttpOnly flag means that the cookies cannot be read or modified by the browser. And Secure means that the cookie can only be transferred over HTTPS. These are really important to protect your application.
document.cookie
, which stores our cookies and can be reassigned. For example on a site that has Google Analytics installed, and in the developer console, we can do:console.log(document.cookie)
// logs something like "_ga=GA1.3.210706468.1583989741; _gid=GA1.3.1734708005.1583989741"
// This equal sign does not work as you expect
document.cookie = "alligator=alligator_cookie_content;"
console.log(document.cookie)
// logs "_ga=GA1.3.210706468.1583989741; _gid=GA1.3.1734708005.1583989741; alligator=alligator_cookie_content"
// Notice that the previous piece of code appends the new cookie we created
// A rough implementation of a cookie interface could look like this:
const createCookie = (name, value) => document.cookie = name + '=' + value + ';'
// For a real update we would first check if the cookie exists
const updateCookie = (name, value) => document.cookie = name + '=' + value + ';'
const deleteCookie = (name) => document.cookie = name + '=; Max-Age=-1;';
Session cookies often refer to a type of cookie that exist until the browser is closed. To setup a session cookie you just need to NOT specify any expiration date.
For example, you can store your user’s name in the cookie. Whoever has access to the cookie will have access to the user’s name. Since it is in the cookie we don’t need to add it to our requests.
Session cookies
is a confusing expression. Session cookies also refer to cookies which you use to manage sessions. Cookies that are deleted when the browser is closed are not the only cookies you can use for session management.
Persistent cookies are not deleted by the browser when the user closes it. These cookies have an expiration date that you can set in your server. You can set a cookie to expire in a day or ten years.
We can differentiate cookies that are on the same domain from cookies which come from third-party providers. The example we gave earlier with Google Analytics is an example of a third-party cookie. Third-party cookies can be used to track user activities. To set a third-party cookie, you have to set ';domain=thirdpartydomain.com'
.
Cookies are usually temporary, so you might want to set a precise expiry date. You have two strategies:
Expires
and set a fixed expiration date. The date uses the HTTP date formate: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT
. So for example if we want our cookie to expire September 17 2020 we can do:const jacksBirthday = new Date(2020, 8, 17);
document.cookie = 'jacksage=27; expires =' + jacksBirthday.toUTCString() + ';';
// Expires after one day
const oneDayToSeconds = 24 * 60 * 60;
document.cookie = 'daily_cookie=session_identifierXYZ; max-age = ' + oneDayToSeconds + ';';
🍪 That’s about it! I hope you now have a better idea of how to use cookies on the client side with JavaScript. If you have any question ask us on Twitter. Next time, we will see how to manage sessions with cookies and Express.js.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
I feel that framing expires and max-age as an option of one or the other is incorrect, the best option is to use both. Modern browsers only use expires if max-age is absent, so expires is a good fallback for older browsers.