Skip to content

Cookie security attributes (HttpOnly and Secure)

Cookie security attributes are flags used in the Set-Cookie HTTP response header to enhance the security of web applications. Specifically, the HttpOnly and Secure attributes help mitigate risks such as Cross-Site Scripting (XSS) and ensure data integrity during transmission^[600-developer__tools__security__Strict-Transport-Security.md].

HttpOnly

The HttpOnly attribute is designed to defend against Cross-Site Scripting (XSS) attacks^[600-developer__tools__security__Strict-Transport-Security.md]. When a cookie is set with this flag, it becomes inaccessible to client-side scripts. Consequently, the cookie cannot be read or modified via document.cookie or any other JavaScript APIs^[600-developer__tools__security__Strict-Transport-Security.md].

This isolation prevents malicious scripts injected into a page from hijacking session tokens or other sensitive cookie data.

Secure

The Secure attribute ensures that cookies are only transmitted over encrypted connections^[600-developer__tools__security__Strict-Transport-Security.md]. When this flag is set, the browser will refuse to send the cookie if the protocol is not HTTPS^[600-developer__tools__security__Strict-Transport-Security.md]. In simpler terms, a cookie marked as Secure will effectively be rendered non-functional in non-HTTPS environments^[600-developer__tools__security__Strict-Transport-Security.md].

Implementation

In application code, such as a Node.js environment using Express, these attributes are typically configured when setting a response cookie^[600-developer__tools__security__Strict-Transport-Security.md]:

res.cookie('cookie_name', 'jack', {  
    httpOnly: true,  
    secure: true  
})

Sources

^[600-developer__tools__security__Strict-Transport-Security.md]