Cookies & Sessions
By default, HTTP is stateless. To remember a user between requests (e.g., for a shopping cart or login), we use Cookies or Sessions.
1. Managing Cookies
Cookies are small pieces of data stored on the client browser. Use cookie-parser to read them.
// Setting a cookie
res.cookie('theme', 'dark', { maxAge: 900000, httpOnly: true });
// Reading a cookie
console.log(req.cookies.theme);
// Clearing a cookie
res.clearCookie('theme');
2. Managing Sessions
A Session is stored on the server, and only a unique session ID is stored in a cookie on the client. This is more secure for storing sensitive info.
const session = require('express-session');
app.use(session({
secret: 'my-secret-key',
resave: false,
saveUninitialized: true,
cookie: { secure: false } // Set to true for HTTPS
}));
// Usage
app.get('/login', (req, res) => {
req.session.isLoggedIn = true;
res.send('Logged In');
});
3. Local Storage vs Cookies vs Sessions
- Local Storage: Client-side only. Not secure for auth.
- Cookies: Can be accessed by server. Limited size.
- Sessions: Server-side storage. Secure. Best for complex state.
Security Tip: Always use the httpOnly: true flag for auth cookies to prevent them from being stolen via XSS attacks.