Skip to content

Cookies

Marcelo XP edited this page Jan 17, 2025 · 2 revisions

Cookies

The JsBaseClass library provides built-in methods to manage cookies using the js-cookie library. Below, you'll find a comprehensive guide with multiple examples to help you set, get, and remove cookies, including advanced options like expires, domain, path, and more. Additionally, the library includes helper methods for working with JSON data in cookies, making it easier to store and retrieve complex objects.


Basic Usage

1. Setting a Cookie

To set a cookie, use the this.setCookie(name, value, options) method. You can specify options like expires, domain, and path.

class ClassCookies extends JsBaseClass {
    async handle() {
        // Set a cookie with a name and value
        this.setCookie('username', 'MarceloXP');
        this.console.log('Username cookie set.');

        // Set a cookie with an expiration date (7 days from now)
        this.setCookie('session_id', 'abc123', { expires: 7 });
        this.console.log('Session ID cookie set with expiration.');

        // Set a cookie with a specific domain and path
        this.setCookie('preferences', 'dark_mode', { domain: 'example.com', path: '/settings' });
        this.console.log('Preferences cookie set with domain and path.');
    }
}

// Initialize the example
window.objCookies = new ClassCookies();
objCookies.init();

2. Getting a Cookie

To retrieve the value of a cookie, use the this.getCookie(name) method.

class ClassCookies extends JsBaseClass {
    async handle() {
        // Get the value of a cookie
        const username = this.getCookie('username');
        this.console.log('Username cookie:', username);

        const sessionId = this.getCookie('session_id');
        this.console.log('Session ID cookie:', sessionId);
    }
}

// Initialize the example
window.objCookies = new ClassCookies();
objCookies.init();

3. Removing a Cookie

To remove a cookie, use the this.removeCookie(name, options) method. You can specify domain and path if needed.

class ClassCookies extends JsBaseClass {
    async handle() {
        // Remove a cookie
        this.removeCookie('username');
        this.console.log('Username cookie removed.');

        // Remove a cookie with domain and path
        this.removeCookie('preferences', { domain: 'example.com', path: '/settings' });
        this.console.log('Preferences cookie removed.');
    }
}

// Initialize the example
window.objCookies = new ClassCookies();
objCookies.init();

Advanced Usage

1. Setting Cookies with Advanced Options

You can set cookies with additional options like secure, sameSite, and httpOnly.

class ClassCookies extends JsBaseClass {
    async handle() {
        // Set a secure cookie (only transmitted over HTTPS)
        this.setCookie('secure_cookie', 'value123', { secure: true });
        this.console.log('Secure cookie set.');

        // Set a cookie with SameSite attribute
        this.setCookie('samesite_cookie', 'value456', { sameSite: 'strict' });
        this.console.log('SameSite cookie set.');

        // Set a cookie with HttpOnly flag (not accessible via JavaScript)
        this.setCookie('httponly_cookie', 'value789', { httpOnly: true });
        this.console.log('HttpOnly cookie set.');
    }
}

// Initialize the example
window.objCookies = new ClassCookies();
objCookies.init();

2. Handling JSON Data in Cookies

You can store and retrieve JSON data in cookies by serializing and deserializing the data.

class ClassCookies extends JsBaseClass {
    async handle() {
        // Store JSON data in a cookie
        const userData = { name: 'MarceloXP', role: 'admin' };
        this.setJsonCookie('user_data', userData, { expires: 1 });
        this.console.log('User data cookie set.');

        // Retrieve and parse JSON data from a cookie
        const retrievedSettings = this.getJsonCookie('user_data');
        this.console.log('Retrieved user settings:', retrievedSettings);
    }
}

// Initialize the example
window.objCookies = new ClassCookies();
objCookies.init();

3. Setting Cookies for a Specific Path

You can restrict a cookie to a specific path on your website.

class ClassCookies extends JsBaseClass {
    async handle() {
        // Set a cookie for a specific path
        this.setCookie('path_cookie', 'value123', { path: '/dashboard' });
        this.console.log('Path-specific cookie set.');
    }
}

// Initialize the example
window.objCookies = new ClassCookies();
objCookies.init();

4. Setting Cookies for a Specific Domain

You can restrict a cookie to a specific domain or subdomain.

class ClassCookies extends JsBaseClass {
    async handle() {
        // Set a cookie for a specific domain
        this.setCookie('domain_cookie', 'value123', { domain: 'sub.example.com' });
        this.console.log('Domain-specific cookie set.');
    }
}

// Initialize the example
window.objCookies = new ClassCookies();
objCookies.init();

Practical Examples

Example 1: Managing User Preferences

Store and retrieve user preferences, such as theme (dark/light mode), using cookies.

class ClassCookies extends JsBaseClass {
    async handle() {
        // Set user preference for dark mode
        this.setCookie('theme', 'dark_mode', { expires: 365 });
        this.console.log('Theme preference set.');

        // Get user preference
        const theme = this.getCookie('theme');
        this.console.log('Current theme:', theme);
    }
}

// Initialize the example
window.objCookies = new ClassCookies();
objCookies.init();

Example 2: Session Management

Use cookies to manage user sessions, such as storing a session ID.

class ClassCookies extends JsBaseClass {
    async handle() {
        // Set a session ID cookie
        this.setCookie('session_id', 'abc123', { expires: 1 });
        this.console.log('Session ID cookie set.');

        // Get the session ID
        const sessionId = this.getCookie('session_id');
        this.console.log('Session ID:', sessionId);

        // Remove the session ID on logout
        this.removeCookie('session_id');
        this.console.log('Session ID cookie removed.');
    }
}

// Initialize the example
window.objCookies = new ClassCookies();
objCookies.init();

Example 3: Tracking User Activity

Use cookies to track user activity, such as the number of visits.

class ClassCookies extends JsBaseClass {
    async handle() {
        // Get the current visit count
        let visitCount = parseInt(this.getCookie('visit_count')) || 0;
        visitCount += 1;

        // Update the visit count
        this.setCookie('visit_count', visitCount, { expires: 365 });
        this.console.log(`Visit count: ${visitCount}`);
    }
}

// Initialize the example
window.objCookies = new ClassCookies();
objCookies.init();

Common Use Cases

  • User Preferences: Store user settings like theme, language, or layout.
  • Session Management: Manage user sessions and authentication tokens.
  • Analytics: Track user activity, such as visit counts or behavior.
  • Shopping Carts: Store temporary data like items in a shopping cart.

API Reference

Methods

  • this.setCookie(name, value, options): Sets a cookie with the specified name, value, and options.
  • this.getCookie(name): Retrieves the value of a cookie by its name.
  • this.removeCookie(name, options): Removes a cookie by its name. Specify domain and path if needed.
  • this.setJsonCookie(name, value, options): Stores a JSON object as a cookie. The object is automatically serialized to a string.
  • this.getJsonCookie(name, defaultValue): Retrieves a JSON object from a cookie. The string is automatically parsed back into an object.

Options

  • expires: Sets the expiration date (in days or as a Date object).
  • domain: Restricts the cookie to a specific domain.
  • path: Restricts the cookie to a specific path.
  • secure: Ensures the cookie is only transmitted over HTTPS.
  • sameSite: Prevents the cookie from being sent with cross-site requests.
  • httpOnly: Makes the cookie inaccessible to JavaScript (server-side only).

Notes

  • Cookies are limited to 4KB in size.
  • Use the expires option to control how long a cookie persists.
  • Be cautious with sensitive data; consider using secure and httpOnly flags for security.

For more details, refer to the js-cookie documentation.


With these methods, you can easily manage cookies in your application, including storing and retrieving complex JSON data. 🍪🚀

Clone this wiki locally