🌐 Web Development

Cookie

Cookie

Small data stored in the browser. Used for session management and user tracking.

πŸ“– Detailed Explanation

A cookie is a small piece of text data stored in the browser, invented in 1994 by Netscape developer Lou Montulli to implement a shopping cart feature. Because HTTP is a stateless protocol, a mechanism such as cookies is essential for a server to identify users and maintain state.

The maximum size of a cookie is about 4KB per domain, and the maximum number of cookies per browser is about 150 to 180. Depending on the expiration date, cookies are divided into session cookies (deleted when the browser is closed) and persistent cookies (kept until a specified date and time). Lifetime is controlled with the Expires or Max-Age attribute.

Three attributes are important for security: HttpOnly, Secure, and SameSite. HttpOnly blocks JavaScript's access to document.cookie to defend against XSS attacks, Secure sends the cookie only over HTTPS connections, and SameSite restricts sending the cookie on cross-site requests to prevent CSRF attacks.

Recently, as blocking of 3rd-party cookies is being enforced in major browsers, business models based on ad tracking are changing. Safari has been blocking them since 2020, and Chrome is blocking them in phases starting in 2024. 1st-party cookies, server-side sessions, and the Privacy Sandbox API are emerging as alternatives.

πŸ’» Code Example

// Express.jsμ—μ„œ λ³΄μ•ˆ μΏ ν‚€ μ„€μ •
import express from 'express';
import cookieParser from 'cookie-parser';

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

// 둜그인 μ‹œ μ„Έμ…˜ μΏ ν‚€ μ„€μ •
app.post('/api/login', async (req, res) => {
  const { email, password } = req.body;
  const user = await authenticate(email, password);

  if (user) {
    // λ³΄μ•ˆ μΏ ν‚€ μ„€μ • (HttpOnly, Secure, SameSite)
    res.cookie('sessionId', generateSessionId(), {
      httpOnly: true,    // XSS λ°©μ§€: JSμ—μ„œ μ ‘κ·Ό λΆˆκ°€
      secure: true,      // HTTPSμ—μ„œλ§Œ 전솑
      sameSite: 'strict',// CSRF λ°©μ§€: 같은 μ‚¬μ΄νŠΈμ—μ„œλ§Œ 전솑
      maxAge: 24 * 60 * 60 * 1000, // 24μ‹œκ°„
      path: '/',
      domain: '.example.com'
    });

    res.json({ success: true });
  }
});

// μΏ ν‚€ 읽기
app.get('/api/profile', (req, res) => {
  const sessionId = req.cookies.sessionId;

  if (!sessionId) {
    return res.status(401).json({ error: 'Not authenticated' });
  }

  // μ„Έμ…˜ 검증 둜직
  const user = validateSession(sessionId);
  res.json(user);
});

// λ‘œκ·Έμ•„μ›ƒ μ‹œ μΏ ν‚€ μ‚­μ œ
app.post('/api/logout', (req, res) => {
  res.clearCookie('sessionId', {
    httpOnly: true,
    secure: true,
    sameSite: 'strict'
  });
  res.json({ success: true });
});

πŸ—£οΈ How It's Said in Practice

πŸ’Ό In a security review meeting

"If you store a JWT in local storage, it's vulnerable to XSS. If you store it in an HttpOnly cookie, it can't be accessed from JavaScript at all, so security is much higher. Instead, you need to use a CSRF token together with it."

🎯 In a technical interview

"Interviewer: What is the difference between session-based and token-based authentication?

Candidate: Session-based authentication stores state on the server and passes only the session ID via a cookie. Token-based authentication (JWT) puts the state in the token itself, so the server becomes stateless. Sessions place a burden on server memory but can be invalidated immediately, while JWTs scale well but make it difficult to force a logout before expiration."

πŸ” In a code review

"The SameSite option is missing from the cookie. The default is 'Lax', so the cookie is sent on GET requests, but if the API uses POST, it may be exposed to CSRF attacks. It would be good to specify 'Strict' explicitly and, if necessary, add a separate CSRF token."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

πŸ”— Related Terms

πŸ“š Learn More