What records are present in JavaScript cookies?

Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.

Cookies are a plain text data record of 5 variable-length fields ?

Cookie Fields Structure

  • Name = Value ? Cookies are set and retrieved in the form of key-value pairs. This is the actual data being stored.
  • Expires ? The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
  • Domain ? The domain name of your site that can access the cookie.
  • Path ? The path to the directory or web page that sets the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
  • Secure ? If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.

Example: Setting a Cookie

<html>
<head>
<title>Cookie Example</title>
</head>
<body>

<script>
// Setting a cookie with all fields
document.cookie = "username=john_doe; expires=Thu, 18 Dec 2024 12:00:00 UTC; path=/; domain=.example.com; secure";

// Display the cookie
console.log("Cookie set:", document.cookie);
</script>

</body>
</html>

Example: Reading Cookie Information

<html>
<head>
<title>Read Cookie</title>
</head>
<body>

<script>
// Set a simple cookie
document.cookie = "user=alice; path=/";

// Read all cookies
console.log("All cookies:", document.cookie);

// Function to get specific cookie value
function getCookie(name) {
    let nameEQ = name + "=";
    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, c.length);
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

console.log("User cookie:", getCookie("user"));
</script>

</body>
</html>

Cookie Structure Breakdown

Field Purpose Example
Name=Value The actual data stored username=john_doe
Expires When cookie expires expires=Thu, 18 Dec 2024 12:00:00 UTC
Domain Which domain can access domain=.example.com
Path Which paths can access path=/admin
Secure HTTPS only flag secure

Conclusion

JavaScript cookies consist of five key fields that control their behavior: name-value pairs for data storage, expiration dates, domain and path restrictions, and security flags. Understanding these fields helps you manage cookie data effectively in web applications.

Updated on: 2026-03-15T23:18:59+05:30

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements