How to set response cookies in ServiceWorker
In the fetch handler initiated by the 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 "Hello!" body. In Chrome devtools, I can see the set TestHeader
in the network bar. But the cookie does not appear in the network bar or in the app> Viewer Cookies. document.cookie
also cannot produce it.
The request is initiated by page navigation, so there is no way to set credentials: "include"
to fetch from browser tab.
Can a cookie be added to a response in a ServiceWorker? If not, is it possible to write cookies in any other way?
source to share
There is some relevant information in the Fetch specification.
According to https://fetch.spec.whatwg.org/#forbidden-response-header-name :
The forbidden response header name is the header name, which is byte-case insensitive to one of:
Set-Cookie
Set-Cookie2
And then according to point 6 in https://fetch.spec.whatwg.org/#concept-headers-append :
Otherwise, if guard is a "response" and name is the forbidden name of a response header, return.
This restriction when added to a title Set-Cookie
applies to constructing new features Response
with the original set of titles, or adding titles after the fact to an existing entity Response
.
There is a plan to add support for reading and writing cookies inside the service worker, but it will use a mechanism different from the header Set-Cookie
in the object Response
. There's more information about the plans in this GitHub issue .
source to share