Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Js Cookies in JavaScript

Js Cookies in JavaScript

? JavaScript Cookies


What are Cookies?

  • Small pieces of data stored in the user's browser.

  • Used to remember information between page reloads or visits (e.g., user sessions, preferences).


How to Set a Cookie

document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/";
  • Format: "key=value; expires=DATE; path=PATH; domain=DOMAIN; secure"

  • expires — sets expiration date. If omitted, cookie lasts until browser closes.

  • path — limits cookie to a specific path (default is current path).

  • secure — cookie sent only over HTTPS.


How to Get Cookies

console.log(document.cookie);// Output: "username=JohnDoe; theme=dark"
  • Returns all cookies as a single string separated by ; .

  • You need to parse this string to get individual cookies.

Example function to get a cookie by name:

function getCookie(name) {  const cookies = document.cookie.split('; ');  for (const cookie of cookies) {    const [key, value] = cookie.split('=');    if (key === name) return value;  }  return null;}console.log(getCookie("username")); // JohnDoe

How to Delete a Cookie

Set the cookie with a past expiration date:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";

Important Notes

  • Cookies size limit ~4KB.

  • Cookies are sent with every HTTP request to the domain.

  • For complex data, consider localStorage or sessionStorage.


Want me to show you how to manage cookies with a ready-to-use JS utility function or explain differences between cookies, localStorage, and sessionStorage?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql