How To Create, Read, Update, & Delete Cookies In JavaScript
Web servers and HTTP servers are stateless, so when a web server sends a web page to a browser, the connection is cut off and the server forgets about everything related to the user.
How can the browser and web server remember information about the user? Cookies were invented to solve this problem.
When a user comes to a web page, their name, unique id, or any other information can be stored in a cookie in their browser. And the next time the user comes back to the webpage, the cookie will remember their name or unique id.
Cookies are simply small text files of data that are stored in your computer's browser. They contain this data:
- Name-value pair with actual data.
- Expiry date for when the cookie becomes invalid.
- Domain and path of the server it should be sent to.
And cookies also have some limitations that are worth mentioning:
- Maximum size of 4096 Bytes per individual cookie.
- Maximum of 20 cookies per domain (this is slightly different for each browser).
- Cookies are private to its own domain (a site cannot read other domain's cookies, only it's own).
- Size limits apply to the entire cookie, not just its value.
In the browser, cookies are exposed via the document object as document.cookies
.
In the sections below, we'll go over how to set, get, update, and delete cookie data in your browser using JavaScript.
Let's get started!
Table Of Contents
Create Cookies
Setting a cookie in your browser using JavaScript is easy! We'll show you how below.
Set A Cookie
Here is the JavaScript to create a new cookie in the browser the code is executed in:
document.cookie = "userId=nick123"
Once you run that code, open a browser and you should find the cookie in the Developer Tools Application (Safari or Chrome) or Storage (Firefox) section.
Set A Cookie Expiration Date
You can also add an expiration date (in UTC) to the cookie that tells the browser when it should be deleted:
document.cookie = "userId=nick123; expires=Wed, 15 Jan 2020 12:00:00 UTC"
Set A Cookie Path
You can also tell the browser the path that the cookie belongs to (default value is the path of the current page):
document.cookie = "userId=nick123; expires=Wed, 15 Jan 2020 12:00:00 UTC; path=/user"
Set A Cookie Domain
And the last piece of data we'll cover is the domain that the cookie belongs to (defaults to the current domain):
document.cookie = "userId=nick123; expires=Wed, 15 Jan 2020 12:00:00 UTC; path=/user; domain=mysite.com"
Read Cookies
Reading cookies is also really simple using JavaScript by accessing the document.cookie
object:
Read All Cookies For A Page
To get all the cookies for a single page as a string with each one separated by semicolons:
const cookies = document.cookie
Read Cookie With A Specific Name
To access a cookie with a specific name, we need to get all the cookies on the page and parse the string to find a match for the name of the cookie we're looking for.
Here is a function that does the job using a regular expression:
function getCookieValue(name) {
let result = document.cookie.match("(^|[^;]+)\s*" + name + "\s*=\s*([^;]+)")
return result ? result.pop() : ""
}
And you use the function like this:
getCookieValue("userId") //returns nick123
That will return the string value of the name
parameter you provide to the function.
If regex expressions aren't your thing, here is another function that works:
function getCookieValue(name) {
const nameString = name + "="
const value = document.cookie.split(";").filter(item => {
return item.includes(nameString)
})
if (value.length) {
return value[0].substring(nameString.length, value[0].length)
} else {
return ""
}
}
The function is used the same way:
getCookieValue("userId") //returns nick123
Update Cookies
You can change a cookie the same way you create them by overwriting it with a new value.
You could use this code to override the userId
cookie created earlier in this article:
document.cookie = "userId=new_value"
And the new value will be returned when you run the getCookieValue
function again:
getCookieValue("userId") //returns new_value
Delete Cookies
You can delete a cookie by giving it an empty value and setting its expiration date to any time in the past.
If we wanted to delete the userId
cookie from previous examples, here is how we'd do it:
document.cookie = "userId=; expires=Thu, 01 Jan 1970 00:00:00 UTC;"
Pretty simple right?
Thanks for reading!