Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set cookies on a response in a ServiceWorker

In a fetch handler triggered by a page navigation, I tried to do this:

return event.respondWith(new Response('Hello!', {
  headers: {
    "Set-Cookie": "TestCookie=foo; path=/; Max-Age=60;"
    "TestHeader": "foo"
  }
}));

Then I loaded any URL in the browser, and got the "Hello!" body. In Chrome devtools, I see the TestHeader set in the network panel. But the cookie is not showing up in the network panel, nor in the Application > Cookies viewer. document.cookie also fails to produce it.

The request is initiated by a page navigation, so there's no opportunity to set credentials: "include" on the fetch from the browser tab.

Is it possible to add a cookie to a response in the ServiceWorker? If not, is it possible to write cookies in any other way?

like image 378
Andrew Avatar asked Nov 08 '22 21:11

Andrew


1 Answers

There's some relevant information in the Fetch specification.

As per https://fetch.spec.whatwg.org/#forbidden-response-header-name:

A forbidden response-header name is a header name that is a byte-case-insensitive match for one of:

  • Set-Cookie
  • Set-Cookie2

And then as per item 6 in https://fetch.spec.whatwg.org/#concept-headers-append:

Otherwise, if guard is "response" and name is a forbidden response-header name, return.

This restriction on adding in the Set-Cookie header applies to either constructing new Response objects with an initial set of headers, or adding in headers after the fact to an existing Response object.

There is a plan to add in support for reading and writing cookies inside of a service worker, but that will use a mechanism other than the Set-Cookie header in a Response object. There's more information about the plans in this GitHub issue.

like image 79
Jeff Posnick Avatar answered Nov 15 '22 06:11

Jeff Posnick