Tips & Tricks

How to Implement Cookie and Session Management with Claude Code

Learn how to implement cookie and session management using Claude Code. Includes practical code examples and step-by-step guidance.

Cookies are the foundation of user authentication and session management, but misconfigured security settings can lead to serious vulnerabilities. With Claude Code, you can correctly implement secure cookie management.

> Create a cookie utility that includes security settings.
> Make HttpOnly, Secure, and SameSite mandatory.
interface CookieOptions {
  maxAge?: number;
  path?: string;
  domain?: string;
  secure?: boolean;
  httpOnly?: boolean;
  sameSite?: 'strict' | 'lax' | 'none';
}

const DEFAULT_OPTIONS: CookieOptions = {
  path: '/',
  secure: true,
  httpOnly: true,
  sameSite: 'lax',
  maxAge: 86400, // 1 day
};

class CookieManager {
  static set(name: string, value: string, options: CookieOptions = {}) {
    const opts = { ...DEFAULT_OPTIONS, ...options };
    const parts = [`${encodeURIComponent(name)}=${encodeURIComponent(value)}`];

    if (opts.maxAge) parts.push(`Max-Age=${opts.maxAge}`);
    if (opts.path) parts.push(`Path=${opts.path}`);
    if (opts.domain) parts.push(`Domain=${opts.domain}`);
    if (opts.secure) parts.push('Secure');
    if (opts.httpOnly) parts.push('HttpOnly');
    if (opts.sameSite) parts.push(`SameSite=${opts.sameSite}`);

    return parts.join('; ');
  }

  static parse(cookieHeader: string): Record<string, string> {
    return cookieHeader.split(';').reduce((acc, pair) => {
      const [key, ...vals] = pair.trim().split('=');
      if (key) acc[decodeURIComponent(key)] = decodeURIComponent(vals.join('='));
      return acc;
    }, {} as Record<string, string>);
  }

  static delete(name: string, path = '/') {
    return this.set(name, '', { maxAge: 0, path });
  }
}

Session Management in Express

> Implement secure session management in Express.
> Use Redis as the session store and include CSRF protection.
import session from 'express-session';
import RedisStore from 'connect-redis';
import { createClient } from 'redis';
import csrf from 'csurf';

const redisClient = createClient({ url: process.env.REDIS_URL });
redisClient.connect();

const sessionConfig: session.SessionOptions = {
  store: new RedisStore({ client: redisClient }),
  secret: process.env.SESSION_SECRET!,
  name: '__session',
  resave: false,
  saveUninitialized: false,
  cookie: {
    secure: process.env.NODE_ENV === 'production',
    httpOnly: true,
    sameSite: 'lax',
    maxAge: 24 * 60 * 60 * 1000, // 24 hours
  },
};

app.use(session(sessionConfig));
app.use(csrf({ cookie: false })); // session-based CSRF

Claude Code can also generate utilities for cookies that are manipulated on the client (non-HttpOnly).

// Client-side cookie utility (for non-sensitive info like theme or language)
export const clientCookie = {
  get(name: string): string | null {
    const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
    return match ? decodeURIComponent(match[1]) : null;
  },

  set(name: string, value: string, days = 365) {
    const expires = new Date(Date.now() + days * 864e5).toUTCString();
    document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)};expires=${expires};path=/;SameSite=Lax`;
  },

  remove(name: string) {
    document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;
  },
};

// Usage example: persist a theme setting
clientCookie.set('theme', 'dark');
const theme = clientCookie.get('theme'); // 'dark'

Hardening Session Security

// Preventing session fixation attacks
app.post('/login', async (req, res) => {
  const user = await authenticate(req.body);

  // Regenerate the session ID on successful login
  req.session.regenerate((err) => {
    if (err) return res.status(500).json({ error: 'Session error' });
    req.session.userId = user.id;
    res.json({ success: true });
  });
});

Summary

With Claude Code, you can implement secure cookie settings, session management, and CSRF protection in one coherent package. For authentication more broadly, see the authentication implementation guide, and for comparisons with JWT auth, see the JWT authentication article. For security details, the security audit is also a useful reference.

For session management best practices, see OWASP Session Management.

#Claude Code #Cookie #session #security #TypeScript

Level up your Claude Code workflow

50 battle-tested prompt templates you can copy-paste into Claude Code right now.

Free

Free PDF: Claude Code Cheatsheet in 5 Minutes

Key commands, shortcuts, and prompt examples on a single printable page.

Download PDF
M

About the Author

Masa

Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.