JAVASCRIPT

Configure Secure and HttpOnly Cookies in JavaScript (Server-Side)

Learn to set essential `HttpOnly`, `Secure`, and `SameSite` attributes for cookies in Node.js, bolstering web application security against XSS and CSRF attacks.

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

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

// Middleware to simulate a login and set a secure session cookie
app.get('/login', (req, res) => {
  // In a real application, you would authenticate the user here
  const userId = 'user123'; 
  const sessionToken = 'aVerySecureSessionToken12345'; // Generated after successful login

  // Set a secure, HttpOnly, and SameSite=Lax cookie
  res.cookie('session_id', sessionToken, {
    httpOnly: true,  // Prevents client-side JavaScript access
    secure: process.env.NODE_ENV === 'production', // Send only over HTTPS in production
    maxAge: 3600000, // 1 hour expiration (in milliseconds)
    sameSite: 'Lax', // Protects against some CSRF attacks
    // 'Strict' is more secure but can break some cross-site navigations.
    // 'None' requires 'Secure: true' and explicitly states cross-site intention.
    path: '/', // The path from which the cookie will be accessible
  });

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

// Route to access the cookie (server-side only, due to HttpOnly)
app.get('/dashboard', (req, res) => {
  const sessionId = req.cookies.session_id;
  if (sessionId) {
    res.send(`Welcome to your secure dashboard! Session ID: ${sessionId}`);
  } else {
    res.status(401).send('Not authenticated.');
  }
});

// Logout route to clear the cookie
app.get('/logout', (req, res) => {
  res.clearCookie('session_id');
  res.send('Logged out successfully!');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This Node.js Express snippet demonstrates how to set cookies with critical security attributes. By setting `httpOnly: true`, the cookie becomes inaccessible to client-side JavaScript, mitigating XSS risks. `secure: true` ensures the cookie is only sent over HTTPS, protecting against eavesdropping. The `sameSite: 'Lax'` attribute helps prevent certain types of Cross-Site Request Forgery (CSRF) attacks by restricting when the browser sends the cookie with cross-site requests.

Need help integrating this into your project?

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

Hire DigitalCodeLabs