owencm
owencm

Reputation: 8894

Read cookies from within a Service Worker?

I would like to read a cookie within my service worker to use it when setting up my caches, but can't find any way of doing it.

Is there any way of doing that, or will I need to duplicate cookie data into IDB or similar?

Upvotes: 9

Views: 12665

Answers (2)

Piotrek
Piotrek

Reputation: 11221

Now there is cookieStore property available in some browsers. It is experimental and does not work on every browser though.

https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/cookieStore

So you just need to access ServiceWorkerGlobalScope and call get function.

const cookie = await this.cookieStore.get("_ga");

return cookie?.value;

It's not currectly available in firefox, but it seems to be work in progress: https://github.com/mozilla/standards-positions/issues/94#issuecomment-2192528669

Upvotes: 0

Marco Castelluccio
Marco Castelluccio

Reputation: 10802

Currently, you can't access them. There's a discussion in the W3C ServiceWorker repo about adding methods to access them in the future.

Upvotes: 14

Related Questions