Home / A JavaScript developer's guide to browser cookies

A JavaScript developer's guide to browser cookies - LogRocket Blog

8 min read
Learn how JavaScript browser cookies work, from accessing, manipulating, and controlling their visibility across browsers.
I'm a frontend engineer currently building Devfolio who likes to build awesome products and write about React, JavaScript, and TypeScript.

If you're a JavaScript developer and you want to learn about browser cookies and what you can do with them, you're at the right place. This article will cover how browser cookies work, how you can access and manipulate them both from the client and server, and how to control their visibility across browsers using their attributes.

What are cookies and how do they work?

A browser cookie is a small piece of data stored on a browser that's created either by the client-side JavaScript or a server during an HTTP request. The browser can then send that cookie back with requests to the same server and/or let the client-side JavaScript of the webpage access the cookie when a user revisits the page.

Cookies are generally used for session management, personalization (such as themes or similar settings), and tracking user behavior across websites.

There was a time when cookies were used for all kinds of client-side storage, but there was an issue with this approach.

Since all domain cookies are sent with every request to the server on that domain, they can significantly affect performance, especially with low-bandwidth mobile data connections. For the same reason, browsers also typically set limits for cookie size and the number of cookies allowed for a particular domain (typically 4kb and 20 cookies per domain).

With the modern web, we got the new Web Storage APIs ( localStorage and sessionStorage ) for client-side storage, which allows browsers to store client-side data in the form of key-value pairs.

So, if you want to persist data only on the client-side, it's better to use the APIs because they are more intuitive and easier to use than cookies and can store more data (usually up to 5MB).

Setting and accessing cookies

You can set and access cookies both via the server and the client. Cookies also have various attributes that…
I'M A Frontend Engineer Currently Building Devfolio Who Likes To Build Awesome Products, Write About React, Javascript
Read full article