UNPKG

6.02 kBMarkdownView Raw
1# Request Cookie Store
2An implementation of the [Cookie Store API](https://wicg.github.io/cookie-store) for request handlers.
3
4It uses the `Cookie` header of a request to populate the store and
5keeps a record of changes that can be exported as a list of `Set-Cookie` headers.
6
7It is intended as a cookie middleware for Cloudflare Workers or other [Worker Runtimes][wks], but perhaps there are other uses as well.
8It is best combined with [**Signed Cookie Store**](https://github.com/worker-tools/signed-cookie-store) or [**Encrypted Cookie Store**](https://github.com/worker-tools/encrypted-cookie-store).
9
10## Recipes
11The following snippets should convey how this is intended to be used.
12Aso see [the interface](./src/interface.ts) for more usage options.
13
14
15### Creating a New Store
16```ts
17import { RequestCookieStore } from '@worker-tools/request-cookie-store';
18
19// Creating a request on the fly. Typically it will be provided by CF Workers, etc.
20const request = new Request('/', { headers: { 'cookie': 'foo=bar; fizz=buzz' } });
21
22const cookieStore = new RequestCookieStore(request);
23```
24
25We can now access cookie values from the store like so:
26
27```ts
28const value = (await cookieStore.get(name))?.value;
29```
30
31This is a bit verbose, so we'll make it more ergonomic in the next step.
32
33### Fast Read Access
34To avoid using `await` for every read, we can parse all cookies into a `Map` once:
35
36```ts
37type Cookies = ReadonlyMap<string, string>;
38
39const all = await cookieStore.getAll();
40
41new Map(all.map(({ name, value }) => [name, value])) as Cookies;
42// => Map { "foo" => "bar", "fizz" => "buzz" }
43```
44
45### Exporting Headers
46Use `set` on the cookie store to add cookies and include them in a response.
47```ts
48await cookieStore.set('foo', 'buzz');
49await cookieStore.set('fizz', 'bar');
50
51event.respondWith(new Response(null, cookieStore));
52```
53
54Will produce the following HTTP headers in Worker Runtimes that support multiple `Set-Cookie` headers:
55
56```http
57HTTP/1.1 200 OK
58content-length: 0
59set-cookie: foo=buzz
60set-cookie: fizz=bar
61```
62
63<!-- Note that [due to the weirdness][1] of the `Headers` class, inspecting the response in JS will not produce the intended result (`set-cookie` headers will appear concatenated).
64However, Worker Runtimes such as Cloudflare Workers will put multiple headers on the network when provided a "[header list](https://fetch.spec.whatwg.org/#concept-header-list)", i.e. an array of tuples. -->
65
66
67### Combine With Other Headers
68The above example above uses the fact that the cookie store will correctly destructure the `headers` key.
69To add additional headers to a response, you can do the following:
70
71```ts
72const response = new Response('{}', {
73 headers: [
74 ['content-type': 'application/json'],
75 ...cookieStore.headers,
76 ],
77});
78```
79
80[1]: https://fetch.spec.whatwg.org/#headers-class
81
82## Disclaimers
83_This is not a polyfill! It is intended as a cookie middleware for Cloudflare Workers or other [Worker Runtimes][wks]!_
84
85[Due to the weirdness][1] of the Fetch API `Headers` class w.r.t `Set-Cookie` (or rather, the lack of special treatment), it is not likely to work in a Service Worker.
86
87[wks]: https://workers.js.org/
88
89<br/>
90
91--------
92
93<br/>
94
95<p align="center"><a href="https://workers.tools"><img src="https://workers.tools/assets/img/logo.svg" width="100" height="100" /></a>
96<p align="center">This module is part of the Worker Tools collection<br/>⁕
97
98[Worker Tools](https://workers.tools) are a collection of TypeScript libraries for writing web servers in [Worker Runtimes](https://workers.js.org) such as Cloudflare Workers, Deno Deploy and Service Workers in the browser.
99
100If you liked this module, you might also like:
101
102- 🧭 [__Worker Router__][router] --- Complete routing solution that works across CF Workers, Deno and Service Workers
103- πŸ”‹ [__Worker Middleware__][middleware] --- A suite of standalone HTTP server-side middleware with TypeScript support
104- πŸ“„ [__Worker HTML__][html] --- HTML templating and streaming response library
105- πŸ“¦ [__Storage Area__][kv-storage] --- Key-value store abstraction across [Cloudflare KV][cloudflare-kv-storage], [Deno][deno-kv-storage] and browsers.
106- πŸ†— [__Response Creators__][response-creators] --- Factory functions for responses with pre-filled status and status text
107- 🎏 [__Stream Response__][stream-response] --- Use async generators to build streaming responses for SSE, etc...
108- πŸ₯ [__JSON Fetch__][json-fetch] --- Drop-in replacements for Fetch API classes with first class support for JSON.
109- πŸ¦‘ [__JSON Stream__][json-stream] --- Streaming JSON parser/stingifier with first class support for web streams.
110
111Worker Tools also includes a number of polyfills that help bridge the gap between Worker Runtimes:
112- ✏️ [__HTML Rewriter__][html-rewriter] --- Cloudflare's HTML Rewriter for use in Deno, browsers, etc...
113- πŸ“ [__Location Polyfill__][location-polyfill] --- A `Location` polyfill for Cloudflare Workers.
114- πŸ¦• [__Deno Fetch Event Adapter__][deno-fetch-event-adapter] --- Dispatches global `fetch` events using Deno’s native HTTP server.
115
116[router]: https://workers.tools/router
117[middleware]: https://workers.tools/middleware
118[html]: https://workers.tools/html
119[kv-storage]: https://workers.tools/kv-storage
120[cloudflare-kv-storage]: https://workers.tools/cloudflare-kv-storage
121[deno-kv-storage]: https://workers.tools/deno-kv-storage
122[kv-storage-polyfill]: https://workers.tools/kv-storage-polyfill
123[response-creators]: https://workers.tools/response-creators
124[stream-response]: https://workers.tools/stream-response
125[json-fetch]: https://workers.tools/json-fetch
126[json-stream]: https://workers.tools/json-stream
127[request-cookie-store]: https://workers.tools/request-cookie-store
128[extendable-promise]: https://workers.tools/extendable-promise
129[html-rewriter]: https://workers.tools/html-rewriter
130[location-polyfill]: https://workers.tools/location-polyfill
131[deno-fetch-event-adapter]: https://workers.tools/deno-fetch-event-adapter
132
133Fore more visit [workers.tools](https://workers.tools).
\No newline at end of file