JavaScript Cookies
Cookies allow you to store user information on web pages.
What are Cookies?
Cookies are small text files stored on your computer. When a web server sends a page to a browser, the connection is closed, and the server forgets everything about the user. Cookies solve the problem of remembering user information:
- When a user visits a page, their name can be stored in a cookie.
- The next time the user visits the page, the cookie "remembers" their name.
Cookies are saved in name-value pairs like:
username=John Doe
When a browser requests a web page from a server, cookies associated with the page are sent with the request, allowing the server to remember user information.
Create a Cookie with JavaScript
JavaScript can create, read, and delete cookies with the document.cookie property.
To create a cookie:
document.cookie = "username=John Doe";
To add an expiry date (in UTC time):
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
To specify the path the cookie belongs to:
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
Read a Cookie with JavaScript
To read a cookie:
let x = document.cookie;
This returns all cookies as a single string: cookie1=value; cookie2=value; cookie3=value;
Change a Cookie with JavaScript
To change a cookie:
document.cookie = "username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
The old cookie is overwritten.
Delete a Cookie with JavaScript
To delete a cookie, set its expiry date to a past date:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Specify the cookie path to ensure the correct cookie is deleted.
The Cookie String
The document.cookie property looks like a normal text string but only shows the name-value pairs. Setting a new cookie adds to document.cookie without overwriting existing cookies.
JavaScript Cookie Example
Create a cookie to store a visitor's name. The first time a visitor arrives, they will be asked to fill in their name. The name is stored in a cookie, and the next time the visitor arrives, they will see a welcome message.
Function to Set a Cookie
function setCookie(cname, cvalue, exdays) { const d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); let expires = "expires=" + d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";}
Parameters:
- cname: Cookie name
- cvalue: Cookie value
- exdays: Number of days until the cookie expires
Function to Get a Cookie
function getCookie(cname) { let name = cname + "="; let decodedCookie = decodeURIComponent(document.cookie); let ca = decodedCookie.split(';'); for (let i = 0; i < ca.length; i++) { let c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return "";}
Parameters:
- cname: Cookie name to search for
Function to Check a Cookie
function checkCookie() { let username = getCookie("username"); if (username != "") { alert("Welcome again " + username); } else { username = prompt("Please enter your name:", ""); if (username != "" && username != null) { setCookie("username", username, 365); } }}
All Together
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
let name = cname + "=";
let ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
let user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}