JavaScript and Cookies
This article explains JavaScript and cookies.
We will carefully explain everything step by step, from the basics of cookies, reading and writing, security, to practical examples.
YouTube Video
javascript-cookie.html
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>JavaScript & HTML</title>
6 <style>
7 * {
8 box-sizing: border-box;
9 }
10
11 body {
12 margin: 0;
13 padding: 1em;
14 padding-bottom: 10em;
15 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
16 background-color: #f7f9fc;
17 color: #333;
18 line-height: 1.6;
19 }
20
21 .container {
22 max-width: 800px;
23 margin: 0 auto;
24 padding: 1em;
25 background-color: #ffffff;
26 border: 1px solid #ccc;
27 border-radius: 10px;
28 box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
29 }
30
31 .container-flex {
32 display: flex;
33 flex-wrap: wrap;
34 gap: 2em;
35 max-width: 1000px;
36 margin: 0 auto;
37 padding: 1em;
38 background-color: #ffffff;
39 border: 1px solid #ccc;
40 border-radius: 10px;
41 box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
42 }
43
44 .left-column, .right-column {
45 flex: 1 1 200px;
46 min-width: 200px;
47 }
48
49 h1, h2 {
50 font-size: 1.2rem;
51 color: #007bff;
52 margin-top: 0.5em;
53 margin-bottom: 0.5em;
54 border-left: 5px solid #007bff;
55 padding-left: 0.6em;
56 background-color: #e9f2ff;
57 }
58
59 button {
60 display: block;
61 margin: 1em auto;
62 padding: 0.75em 1.5em;
63 font-size: 1rem;
64 background-color: #007bff;
65 color: white;
66 border: none;
67 border-radius: 6px;
68 cursor: pointer;
69 transition: background-color 0.3s ease;
70 }
71
72 button:hover {
73 background-color: #0056b3;
74 }
75
76 #output {
77 margin-top: 1em;
78 background-color: #1e1e1e;
79 color: #0f0;
80 padding: 1em;
81 border-radius: 8px;
82 min-height: 200px;
83 font-family: Consolas, monospace;
84 font-size: 0.95rem;
85 overflow-y: auto;
86 white-space: pre-wrap;
87 }
88
89 .highlight {
90 outline: 3px solid #ffc107; /* yellow border */
91 background-color: #fff8e1; /* soft yellow background */
92 transition: background-color 0.3s ease, outline 0.3s ease;
93 }
94
95 .active {
96 background-color: #28a745; /* green background */
97 color: #fff;
98 box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
99 transition: background-color 0.3s ease, box-shadow 0.3s ease;
100 }
101 </style>
102</head>
103<body>
104 <div class="container">
105 <h1>JavaScript Console</h1>
106 <button id="executeBtn">Execute</button>
107 <div id="output"></div>
108 </div>
109
110 <script>
111 // Override console.log to display messages in the #output element
112 (function () {
113 // Override console.log
114 const originalLog = console.log;
115 console.log = function (...args) {
116 originalLog.apply(console, args);
117 const message = document.createElement('div');
118 message.textContent = args.map(String).join(' ');
119 output.appendChild(message);
120 };
121
122 // Override console.error
123 const originalError = console.error;
124 console.error = function (...args) {
125 originalError.apply(console, args);
126 const message = document.createElement('div');
127 message.textContent = args.map(String).join(' ');
128 message.style.color = 'red'; // Color error messages red
129 output.appendChild(message);
130 };
131 })();
132
133 document.getElementById('executeBtn').addEventListener('click', () => {
134 // Prevent multiple loads
135 if (document.getElementById('externalScript')) return;
136
137 const script = document.createElement('script');
138 script.src = 'javascript-cookie.js';
139 script.id = 'externalScript';
140 //script.onload = () => console.log('javascript-cookie.js loaded and executed.');
141 //script.onerror = () => console.log('Failed to load javascript-cookie.js.');
142 document.body.appendChild(script);
143 });
144 </script>
145</body>
146</html>
JavaScript and Cookies
Cookie
refers to small pieces of data stored in the user's browser. They are mainly used for the following purposes:.
- User authentication (maintaining login state)
- Saving user settings (language, theme, etc.)
- Tracking (browsing history, etc.)
In JavaScript, you can read and write cookies using document.cookie
.
Creating (writing) cookies
Cookies are created with the following syntax:.
1document.cookie = "username=JohnDoe";
- This code saves a cookie named
"username=JohnDoe"
in the browser.
Creating cookies with an expiration date
Cookies can have an expiration date set. If no expiration date is set, it is treated as a session cookie and is deleted when the browser is closed.
1const date = new Date();
2date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days
3const cookieText = "username=JohnDoe; expires=" + date.toUTCString() + "; path=/; SameSite=None; Secure"
4document.cookie = cookieText;
5console.log(`Cookie Text : ${cookieText}`);
6console.log(`Cookie Value : ${document.cookie}`);
- The
expires
attribute specifies the cookie’s expiration date in UTC format. - The
path
attribute specifies the path where the cookie will be sent./
means the entire site. - If you specify
SameSite=None
, theCookie
will be sent even with cross-site requests. However, in this case, you must always include theSecure
attribute. - Specifying
Secure
restricts theCookie
to HTTPS communication only, enhancing security. - By referring to
document.cookie
, you can obtain allCookie
s available on the current page as a string. - By using
console.log
, you can check the difference between the actualCookie
values set in the browser and the values that can be retrieved.
Getting (reading) cookies
You can retrieve all cookies as a string with document.cookie
.
1const date = new Date();
2date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days
3document.cookie = "theme=dark; expires=" + date.toUTCString() + "; path=/; SameSite=None; Secure"
4
5console.log(document.cookie);
6// Output: "username=JohnDoe; theme=dark"
- The return value of
document.cookie
is a single string in which allCookie
s are concatenated in the 'key=value;
' format. - It is convenient to use a function to parse this string and extract the desired value.
Function to get the value of a cookie
1function getCookie(name) {
2 const cookies = document.cookie.split('; ');
3 for (const cookie of cookies) {
4 const [key, value] = cookie.split('=');
5 if (key === name) {
6 return decodeURIComponent(value);
7 }
8 }
9 return null;
10}
11
12console.log(getCookie("username")); // "JohnDoe"
- This function splits the keys and values using
split()
and returns the value if it matches the specified key. - By using
decodeURIComponent
, you can correctly retrieve encoded characters. - If the corresponding key does not exist, it returns
null
.
Deleting cookies
A cookie can be deleted by setting its expiration date to a date in the past.
1document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=None; Secure";
2
3console.log(document.cookie);
4// Output: "theme=dark"
- By assigning an empty value to
username
and setting the expiration date to the past, it will be deleted. - When deleting a
Cookie
, you must also match thepath
,SameSite
, andSecure
attributes to those used when it was created. - In this example,
username
is deleted, and otherCookie
s such astheme=dark
remain.
Cookie options
You can specify various options to control the behavior of a cookie. The main ones are as follows:.
-
expires
Specifies the cookie’s expiration date in UTC format. If not specified, the cookie becomes a session cookie and is deleted when the browser is closed. -
max-age
Specifies the cookie’s expiration date in seconds. This takes precedence overexpires
. -
path
Specifies the path for which the cookie will be sent. For example, if you specify/admin
, the cookie will only be sent to pages under that path. -
domain
Specifies the domain for which the cookie is valid. Usually, it is set for the current domain, but you can apply it to all subdomains, such as.example.com
. -
secure
When this attribute is specified, the cookie is sent only via HTTPS. For increased security, always set this attribute for sensitive information. -
SameSite
Controls whether cookies are sent on cross-site requests. You can specify one of the following three values:.-
Strict
Cookies are sent only for requests from the same site. -
Lax
Cookies are sent for regular navigation, but with some limitations. -
None
Cookies can be sent even for cross-site requests. However, theSecure
attribute is also required.
-
Example: Secure cookie
1document.cookie = "sessionId=abc123; secure; SameSite=Strict";
- If you specify
secure
, theCookie
will only be sent over HTTPS communication. - If you specify
SameSite=Strict
, theCookie
will not be sent for cross-site requests, making it effective as a CSRF countermeasure. - Such secure attributes are essential for important
Cookie
s used for authentication or session management.
Encoding and decoding
Since cookie values may contain special characters, it is safer to use encodeURIComponent
.
1const date = new Date();
2date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days
3
4const username = "JohnDoe";
5document.cookie =
6 "username=" + encodeURIComponent(username) +
7 "; max-age=604800; path=/; SameSite=None; Secure";
8
9console.log(decodeURIComponent(getCookie("username"))); // "JohnDoe"
- By using
encodeURIComponent
, you can safely store spaces, symbols, and so on in aCookie
. - When reading it out, use
decodeURIComponent
to return the original string. - In this example,
max-age=604800
is used to set the expiration period to 7 days (604,800 seconds). This is a method of specifying the expiration date, similar toexpires
.max-age
can be specified in seconds and is often easier to use.
Practical example: Saving and loading a theme
The following is an example of saving the user's selected theme in a cookie and automatically applying it on the next visit.
1function setTheme(theme) {
2 document.cookie =
3 "theme=" + encodeURIComponent(theme) +
4 "; max-age=604800; path=/; SameSite=None; Secure"; // 1 week
5 applyTheme(theme);
6}
7
8function applyTheme(theme) {
9 document.body.style.backgroundColor = theme === "dark" ? "#333" : "#fff";
10 document.body.style.color = theme === "dark" ? "#fff" : "#000";
11}
12
13function getCookie(name) {
14 const cookies = document.cookie.split('; ');
15 for (const cookie of cookies) {
16 const [key, value] = cookie.split('=');
17 if (key === name) {
18 return decodeURIComponent(value);
19 }
20 }
21 return null;
22}
23
24const savedTheme = getCookie("theme");
25if (savedTheme) {
26 applyTheme(savedTheme);
27}
1<button onclick="setTheme('light')">Light</button>
2<button onclick="setTheme('dark')">Dark</button>
- The
setTheme
function saves the selected theme to aCookie
and immediately callsapplyTheme
to update the screen. - The
applyTheme
function switches the background and text colors of thebody
according to the theme. - In this example, since
max-age=604800
is set, the theme setting is preserved for one week. - Since the user's selection can be retained upon revisiting the page, UX is improved.
Cookie limitations and cautions
Be aware of the following points when using cookies:.
-
Size Limitations The size of a single cookie is limited to about 4KB.
-
Limit on the number of cookies that can be saved Depending on the browser, you can only save about 20 to 50 per domain.
-
Security Precautions The content of
Cookie
s is basically saved in plain text, so it is not suitable for storing confidential information such as passwords. -
Cookies inaccessible from JavaScript
Cookies
with theHttpOnly
attribute cannot be read from JavaScript for security reasons.
Server and Cookie
s
1Set-Cookie: sessionId=abc123; HttpOnly; Secure; SameSite=Strict
Some Cookie
attributes, such as HttpOnly
, cannot be set via JavaScript. These must be set on the server side.
Summary
Manipulating Cookie
s with JavaScript can enhance user experience and maintain state. However, please keep the following points in mind to handle them safely and appropriately.
-
Store only the minimum necessary information From a privacy and security perspective, avoid storing personal or sensitive information and record only the necessary data.
-
Properly set security attributes Set attributes like
Secure
andSameSite
to prevent cross-site attacks such as XSS and CSRF. -
Encoding and Decoding Data Use
encodeURIComponent
anddecodeURIComponent
to safely store and readCookie
values so that special characters and Japanese can be handled correctly.
By learning the correct way to use Cookie
s, you can build more advanced and secure web applications.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.