Express.js Masterclass
The Professional Backend Framework01.Home02.Introduction03.Express vs Native Node04.Express Generator05.Request Object (req)06.Response Object (res)07.Advanced Routing08.URL Params & Query09.Body Parsing10.Template Engines (EJS)11.Serving Static Files12.Middleware Architecture13.Must-Have Middleware14.File Uploads (Multer)15.Custom Error Handling16.Cookies & Sessions17.User Auth (Passport)18.Database Integration19.Data Validation20.Socket.io in Express21.Security & Helmet
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.