JAVASCRIPT

Set Secure and HttpOnly Cookies in Node.js Express

Learn to set secure cookies in Node.js Express applications, using `HttpOnly` to prevent XSS access and `Secure` to ensure cookies are sent only over HTTPS.

const express = require('express');
const cookieParser = require('cookie-parser');

const app = express();
app.use(cookieParser());

// Configuration for production environment
const isProduction = process.env.NODE_ENV === 'production';

app.get('/login', (req, res) => {
    // In a real application, you'd authenticate the user here
    const userToken = 'some_secure_jwt_token_here';

    // Set the cookie with security flags
    res.cookie('sessionToken', userToken, {
        httpOnly: true, // Prevents client-side JavaScript from accessing the cookie
        secure: isProduction, // Ensures cookie is sent only over HTTPS in production
        sameSite: 'Lax', // Protects against some CSRF attacks (Strict or None also available)
        maxAge: 3600000, // Cookie expires in 1 hour (in milliseconds)
        path: '/', // Cookie is valid for all paths on the domain
    });

    res.send('Logged in and session cookie set securely!');
});

app.get('/dashboard', (req, res) => {
    const sessionToken = req.cookies.sessionToken;
    if (sessionToken) {
        res.send(`Welcome to your dashboard! Your token: ${sessionToken}`);
    } else {
        res.status(401).send('Unauthorized. Please log in.');
    }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
    if (!isProduction) {
        console.log('WARNING: Running in development mode. Cookies will not be "Secure".');
    }
});
How it works: This Node.js Express snippet demonstrates how to set cookies with critical security flags. The `httpOnly: true` flag prevents client-side JavaScript from accessing the cookie, mitigating XSS risks. The `secure: true` flag ensures the cookie is only sent over HTTPS, protecting it from eavesdropping during transmission (this is conditionally set for production environments). `sameSite: 'Lax'` provides a defense against some CSRF attacks by controlling when cookies are sent with cross-site requests. These flags are essential for safeguarding session tokens and other sensitive cookie data.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs