</> Code Corner

JavaScript · JS Browser BOM · Lesson 57

JS Cookies

Store small pieces of data in the browser.

Cookies are small text files stored on your computer. They are sent to the server with every request and are used to remember information about the user.

Example

<p id="demo"></p>
<script>
function setCookie(name, value, days) {
  const d = new Date();
  d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
  document.cookie = name + "=" + encodeURIComponent(value) + ";expires=" + d.toUTCString() + ";path=/";
}
function getCookie(name) {
  const match = document.cookie.split("; ").find(row => row.startsWith(name + "="));
  return match ? decodeURIComponent(match.split("=")[1]) : "";
}
setCookie("username", "John Doe", 7);
document.getElementById("demo").innerHTML = "Cookie value: " + (getCookie("username") || "(cookies blocked in this frame)");
</script>
Tip: For data that does not need to go to the server, prefer localStorage — it is larger and simpler.

Keep reading “JS Cookies”

Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.

Chat with us 👋