What are secured cookies in JavaScript?

Secured cookies in JavaScript are cookies with special security attributes that protect against common web vulnerabilities. They use two main flags: Secure and HttpOnly to enhance security.

What Makes a Cookie Secured?

A secured cookie has two key attributes:

  • Secure flag - Cookie is only sent over HTTPS connections
  • HttpOnly flag - Cookie cannot be accessed via JavaScript

The Secure Attribute

The Secure attribute ensures cookies are only transmitted over encrypted HTTPS connections, preventing interception over unsecured HTTP.

// Setting a secure cookie (server-side example)
document.cookie = "sessionId=abc123; Secure; Path=/";

The HttpOnly Attribute

The HttpOnly flag prevents JavaScript from accessing the cookie, protecting against Cross-Site Scripting (XSS) attacks.

// This will NOT work with HttpOnly cookies
console.log(document.cookie); // HttpOnly cookies won't appear here

// Regular cookie (accessible via JavaScript)
document.cookie = "regularCookie=value123";
console.log(document.cookie); // Shows: "regularCookie=value123"

Complete Secured Cookie Example

Here's how to set a fully secured cookie with both flags:

// Server-side setting (Node.js Express example)
res.cookie('authToken', 'abc123', {
    secure: true,      // Only HTTPS
    httpOnly: true,    // No JavaScript access
    maxAge: 3600000,   // 1 hour
    sameSite: 'strict' // Additional CSRF protection
});

Security Benefits

Attribute Protection Against How It Works
Secure Man-in-the-middle attacks Only sends over HTTPS
HttpOnly XSS attacks Blocks JavaScript access
SameSite CSRF attacks Controls cross-site requests

Testing Cookie Security

// Check if cookies are accessible
function checkCookieAccess() {
    document.cookie = "testCookie=accessible; Path=/";
    
    if (document.cookie.includes('testCookie')) {
        console.log("Cookie is accessible via JavaScript");
    } else {
        console.log("Cookie may be HttpOnly or blocked");
    }
    
    // Clean up
    document.cookie = "testCookie=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
}

checkCookieAccess();
Cookie is accessible via JavaScript

Conclusion

Secured cookies use Secure and HttpOnly flags to prevent interception and XSS attacks. Always use these attributes for sensitive data like authentication tokens to ensure maximum security.

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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements