JavaScript > Security > Security Best Practices > Secure cookies
Secure Cookie Implementation in JavaScript
This snippet demonstrates how to set and use secure cookies in JavaScript to protect sensitive user data from unauthorized access. It focuses on the `Secure`, `HttpOnly`, and `SameSite` attributes to enhance cookie security.
Understanding Secure Cookies
Cookies are small pieces of data stored on a user's computer by a web browser. By default, cookies are vulnerable to interception via man-in-the-middle attacks if transmitted over unencrypted connections (HTTP). Secure cookies address this by only being transmitted over HTTPS connections. The `HttpOnly` flag prevents client-side scripts (like JavaScript) from accessing the cookie, mitigating the risk of Cross-Site Scripting (XSS) attacks. `SameSite` helps protect against Cross-Site Request Forgery (CSRF) attacks.
Setting a Secure Cookie
This code snippet illustrates how to set a secure cookie on the server-side. It uses `express` and the `cookie` method provided by the `res` object. The `secure: true` option ensures the cookie is only sent over HTTPS. `httpOnly: true` prevents JavaScript from accessing the cookie, reducing the risk of XSS attacks. `sameSite: 'strict'` is the most restrictive setting and helps prevent CSRF attacks by only sending the cookie with requests originating from the same site.
// Server-side code (e.g., Node.js with Express)
const express = require('express');
const app = express();
app.get('/set-cookie', (req, res) => {
res.cookie('mySecureCookie', 'myValue', {
secure: true, // Only send over HTTPS
httpOnly: true, // Prevent client-side JavaScript access
sameSite: 'strict', // Protect against CSRF attacks. 'strict', 'lax', or 'none'. 'strict' is generally the most secure.
maxAge: 3600000 // Cookie expires in 1 hour (in milliseconds)
});
res.send('Cookie has been set securely!');
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
Client-Side Limitations
Due to the `HttpOnly` flag, client-side JavaScript cannot directly read, modify, or delete cookies set with this flag. This is a crucial security measure to prevent XSS attacks. While `document.cookie` can be used to see non-HttpOnly cookies, it won't reveal the content of the `mySecureCookie` if it was set with `httpOnly: true`.
// Client-side JavaScript (browser)
// Attempting to access the cookie will return an empty string if HttpOnly is true.
// document.cookie;
Concepts Behind the Snippet
The core concept is defense in depth. By using `secure`, `HttpOnly`, and `SameSite` attributes, we create multiple layers of protection for the cookie. `secure` protects against network interception, `HttpOnly` protects against client-side script vulnerabilities, and `SameSite` protects against cross-site request forgery.
Real-Life Use Case
Secure cookies are commonly used to store session IDs, authentication tokens, or other sensitive user data. For example, after a user logs in, a secure cookie might be set containing a unique session ID. The server uses this ID to identify the user on subsequent requests, without needing to resend credentials on every request. The `HttpOnly` flag would prevent malicious scripts from stealing the session ID.
Best Practices
Interview Tip
When discussing secure cookies in an interview, be sure to emphasize the importance of the `secure`, `HttpOnly`, and `SameSite` attributes and how they contribute to overall application security. Explain the vulnerabilities they mitigate (MITM, XSS, and CSRF) and provide real-world examples of their usage. Also, be prepared to discuss the tradeoffs associated with each `SameSite` value.
When to Use Them
Use secure cookies whenever you need to store sensitive information or maintain a user session. If you're storing non-sensitive data that doesn't require protection, you might skip the `secure` and `HttpOnly` flags, but it's generally good practice to use them regardless. If you use a cookie for anonymous tracking, `SameSite=Lax` is often sufficient.
Alternatives
Alternatives to cookies for storing user-specific data include:
Pros
Cons
FAQ
-
What happens if I set `secure: true` but don't use HTTPS?
The cookie will still be set by the browser, but it will *not* be sent to the server over HTTP connections. This means the server will not receive the cookie and any functionality relying on it will fail. Browsers may also prevent the cookie from being set at all if it's being set from a non-secure context. -
Why use `HttpOnly` if I'm already using HTTPS?
HTTPS protects against man-in-the-middle attacks, but it doesn't protect against XSS attacks. If a malicious script is injected into your page, it can still access cookies without the `HttpOnly` flag. `HttpOnly` provides an additional layer of defense against XSS. -
What's the difference between `SameSite=Strict` and `SameSite=Lax`?
`SameSite=Strict` only sends the cookie with requests originating from the same site. This provides the strongest protection against CSRF attacks. `SameSite=Lax` sends the cookie with same-site requests and top-level navigation (e.g., clicking a link from another site). It's a bit less secure than `Strict`, but more user-friendly. `SameSite=None` is the least secure, requiring `Secure=true` and allowing the cookie to be sent on all requests, including cross-site requests. -
Can I read `HttpOnly` cookies from server-side code?
Yes, `HttpOnly` only restricts access from client-side JavaScript. Your server-side code can still read and manipulate `HttpOnly` cookies.