Middle
What are secure cookies and how are they used in web development?
sobes.tech AI
Answer from AI
Secure cookies are cookies with the Secure and HttpOnly attributes, which help protect user data.
Secure: Indicates to the browser to send the cookie only over a secure HTTPS connection. This prevents cookie interception during transmission over unencrypted protocols.HttpOnly: Disallows access to the cookie from JavaScript. This protects against XSS attacks by preventing cookie theft through malicious scripts on the page.
They are used to store session IDs, authorization tokens, and user preferences that do not need to be accessed from client-side scripts. Access to them is only available on the server side during HTTP request processing.
Example of setting secure and HttpOnly cookies in Node.js (Express):
// Assuming the use of the cookie-parser library
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
app.get('/set-cookie', (req, res) => {
res.cookie('mySecureCookie', 'secretValue', {
secure: true, // Cookie will be sent only over HTTPS
httpOnly: true // Cookie is inaccessible from JavaScript
});
res.send('Secure cookie set!');
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});