Sobes.tech
Middle

What are HTTP-only cookies?

sobes.tech AI

Answer from AI

HTTP-only cookies are a type of cookie that have the HttpOnly flag. This flag prevents access to the cookie via JavaScript through document.cookie.

Advantages:

  • Enhanced security: Protection against XSS attacks. If an attacker manages to inject malicious JavaScript code into the page, they will not be able to access HTTP-only cookies using document.cookie.

Disadvantages:

  • Limited access from JavaScript: Cannot be read or modified by client-side scripts.

Usage:

Ideal for storing confidential information such as session identifiers or tokens. The browser automatically sends such cookies with every HTTP request to the server, but they are not accessible on the client side via JavaScript.

Setting an HTTP-only cookie on the server (example in Node.js with Express):

// Setting a cookie with the HttpOnly flag
res.cookie('sessionId', 'your_session_id', { httpOnly: true });