Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Cookies Case Studies

Introduction

Cookies are small pieces of data stored on the client-side that are sent back to the server with each HTTP request. They are essential for maintaining state and user sessions in web applications.

Case Study 1: User Preferences

Scenario

In this case study, we will explore how a website can use cookies to store user preferences such as theme choice and language.

Implementation

function setUserPreferences(theme, language) {
    document.cookie = "theme=" + theme + "; path=/; max-age=" + 60 * 60 * 24 * 30; // 30 days
    document.cookie = "language=" + language + "; path=/; max-age=" + 60 * 60 * 24 * 30; // 30 days
}

Retrieving Preferences

function getUserPreferences() {
    const cookies = document.cookie.split('; ');
    let preferences = {};
    cookies.forEach(cookie => {
        const [key, value] = cookie.split('=');
        preferences[key] = value;
    });
    return preferences;
}

Case Study 2: Session Management

Scenario

This case study examines how cookies can be used to manage user sessions securely.

Implementation

function startSession(userId) {
    const sessionId = generateSessionId(); // Assume this generates a unique session ID
    document.cookie = "sessionId=" + sessionId + "; path=/; HttpOnly; secure; max-age=" + 60 * 60; // 1 hour
    // Store session data on the server associated with userId and sessionId
}

Validating Sessions

function validateSession() {
    const cookies = document.cookie.split('; ');
    const sessionCookie = cookies.find(cookie => cookie.startsWith('sessionId='));
    if (sessionCookie) {
        const sessionId = sessionCookie.split('=')[1];
        // Validate sessionId on the server
    }
}

Best Practices

  • Use the HttpOnly flag for cookies that should not be accessible via JavaScript.
  • Set the Secure flag for cookies that should only be transmitted over HTTPS.
  • Limit the max-age of cookies to minimize the risk of session hijacking.
  • Use SameSite attribute to prevent CSRF attacks.

FAQ

What are cookies?

Cookies are small text files stored on the user's device that hold data relevant to web sessions.

How long do cookies last?

The duration of a cookie's lifespan can be set using the max-age attribute; it can last from a few seconds to several years.

Can cookies be accessed via JavaScript?

Yes, unless the HttpOnly flag is set, which prevents JavaScript from accessing the cookie.