JAVASCRIPT

Mitigate CSRF with SameSite Cookies in Express.js

Protect your Express.js application from Cross-Site Request Forgery (CSRF) attacks by setting the `SameSite` attribute on your session and authentication cookies.

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

const app = express();
const port = 3000;

// Use cookie-parser middleware for parsing cookies
app.use(cookieParser());

// Configure express-session with SameSite attribute
app.use(session({
    secret: 'your_strong_secret_key_for_session', // Should be a strong, unique secret
    resave: false,
    saveUninitialized: false,
    cookie: {
        secure: process.env.NODE_ENV === 'production', // Use secure cookies in production
        httpOnly: true, // Prevents client-side JavaScript from accessing cookies
        maxAge: 3600000, // 1 hour (in milliseconds)
        sameSite: 'Lax' // 'Strict' or 'Lax' recommended for CSRF protection
                        // 'Strict': Prevents cookie from being sent with any cross-site request.
                        // 'Lax': Allows cookie to be sent with top-level navigation GET requests.
                        //       This is a good balance for user experience.
                        // 'None': Allows cross-site requests, but requires 'secure: true'. Use with caution.
    }
}));

app.get('/', (req, res) => {
    if (req.session.views) {
        req.session.views++;
        res.send(`You have visited this page ${req.session.views} times. Session ID: ${req.session.id}`);
    } else {
        req.session.views = 1;
        res.send('Welcome to the session page! Refresh to see count increase.');
    }
});

app.post('/transfer-money', (req, res) => {
    // In a real application, you'd also implement CSRF tokens
    // alongside SameSite cookies for robust protection.
    res.send('Money transferred (simulated). CSRF protection active via SameSite cookie.');
});

app.listen(port, () => {
    console.log(`Server listening at http://localhost:${port}`);
    console.log(`Open in browser, then try navigating from another site. `);
    console.log(`With SameSite=Lax, a POST from another site won't send the session cookie.`);
});
How it works: This Express.js snippet demonstrates how to mitigate Cross-Site Request Forgery (CSRF) attacks using the `SameSite` cookie attribute. By setting `cookie.sameSite` to `'Lax'` (or `'Strict'`) in your session configuration, you instruct browsers to restrict when session cookies are sent with cross-site requests. `'Lax'` is often a good balance, allowing cookies for safe top-level navigations (like clicking a link) but preventing them for most other cross-site requests (like POST forms from external sites), significantly reducing the risk of CSRF. `httpOnly` prevents client-side script access, and `secure` ensures cookies are only sent over HTTPS, further enhancing security.

Need help integrating this into your project?

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

Hire DigitalCodeLabs