DEV Community

Maxim Logunov
Maxim Logunov

Posted on

The New Cookie Store API: Modern Cookie Management for the Web

Introduction

For decades, web developers have relied on the document.cookie interface to manage cookies in browsers. While functional, this API has always been clunky and limited. Enter the new Cookie Store API - a modern, promise-based interface that provides a more powerful and intuitive way to work with cookies in web applications.

What is the Cookie Store API?

The Cookie Store API is a new JavaScript API that offers a better way to read and write cookies compared to the traditional document.cookie approach. It's designed to address several limitations of the old method while adding new capabilities that are essential for modern web development.

Key Features and Benefits

1. Promise-based Interface

Unlike document.cookie which operates synchronously, the Cookie Store API uses promises, making it work seamlessly with modern asynchronous JavaScript code.

// Writing a cookie
await cookieStore.set({
  name: "session_id",
  value: "12345",
  expires: Date.now() + 24 * 60 * 60 * 1000, // 1 day
  domain: "example.com"
});

// Reading a cookie
const sessionCookie = await cookieStore.get("session_id");
console.log(sessionCookie.value);
Enter fullscreen mode Exit fullscreen mode

2. Better Error Handling

The API provides proper error handling through rejected promises rather than silent failures.

3. Full Cookie Metadata Access

You can access all cookie attributes (domain, path, expiration, etc.) not just the name-value pairs.

const allCookies = await cookieStore.getAll();
allCookies.forEach(cookie => {
  console.log(`Name: ${cookie.name}, Secure: ${cookie.secure}`);
});
Enter fullscreen mode Exit fullscreen mode

4. Cookie Change Events

Subscribe to notifications when cookies are set or deleted.

cookieStore.addEventListener('change', (event) => {
  event.changed.forEach(cookie => {
    console.log(`Cookie changed: ${cookie.name}`);
  });
  event.deleted.forEach(cookie => {
    console.log(`Cookie deleted: ${cookie.name}`);
  });
});
Enter fullscreen mode Exit fullscreen mode

5. Service Worker Support

The API works in both window contexts and service workers, enabling better offline/PWA cookie management.

// In a service worker
self.addEventListener('fetch', (event) => {
  if (event.request.url.includes('auth')) {
    event.respondWith(
      cookieStore.get('session_token')
        .then(cookie => {
          if (!cookie) {
            return new Response('Unauthorized', { status: 401 });
          }
          return fetch(event.request);
        })
    );
  }
});
Enter fullscreen mode Exit fullscreen mode

Browser Support and Availability

As of 2023, the Cookie Store API is supported in:

  • Chrome 87+ (fully supported)
  • Edge 87+
  • Opera 73+
  • Firefox 140+
  • Safari 18.4+

You can check for API availability with:

if ('cookieStore' in window) {
  // API is available
}
Enter fullscreen mode Exit fullscreen mode

Migration from document.cookie

Here's how common operations translate between the old and new APIs:

Operation document.cookie Cookie Store API
Set cookie document.cookie = "name=value; expires=..." await cookieStore.set({name, value, expires})
Get cookie Parse document.cookie string await cookieStore.get(name)
Get all cookies Parse document.cookie string await cookieStore.getAll()
Delete cookie Set expiration in past await cookieStore.delete(name)

Security Considerations

The Cookie Store API follows the same security restrictions as document.cookie:

  • You can only access cookies for the current domain
  • Secure cookies (with HttpOnly flag) are still not readable via JavaScript
  • The API respects same-origin policy and cookie permission settings

Use Cases

  1. Authentication flows: More robust handling of session cookies
  2. Analytics: Better management of tracking consent cookies
  3. Feature flags: Easier management of feature toggle cookies
  4. PWAs: Cookie management in service workers
  5. Real-time updates: Reacting to cookie changes without polling

Conclusion

The Cookie Store API represents a significant improvement over the venerable but limited document.cookie interface. With its promise-based design, comprehensive metadata access, and change notifications, it provides web developers with the tools needed for proper cookie management in modern web applications.

While browser support is not yet universal, the API is worth adopting in compatible environments and can be polyfilled or feature-detected for graceful fallbacks. As the web platform continues to evolve, APIs like this demonstrate how even fundamental capabilities are being modernized for today's development needs.

For more information, check out the W3C specification and MDN documentation.

Top comments (0)