6fa08988cabc1d90f6523d3ca2d09e89622aecbf2e954e67241a076f43d3db0eca3bb16b28cd0259e851305631f8dc42299a78aa400ce0623ac90b7c56c218 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. # cookie
  2. [![NPM Version][npm-version-image]][npm-url]
  3. [![NPM Downloads][npm-downloads-image]][npm-url]
  4. [![Node.js Version][node-image]][node-url]
  5. [![Build Status][ci-image]][ci-url]
  6. [![Coverage Status][coveralls-image]][coveralls-url]
  7. Basic HTTP cookie parser and serializer for HTTP servers.
  8. ## Installation
  9. This is a [Node.js](https://nodejs.org/en/) module available through the
  10. [npm registry](https://www.npmjs.com/). Installation is done using the
  11. [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
  12. ```sh
  13. $ npm install cookie
  14. ```
  15. ## API
  16. ```js
  17. var cookie = require('cookie');
  18. ```
  19. ### cookie.parse(str, options)
  20. Parse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs.
  21. The `str` argument is the string representing a `Cookie` header value and `options` is an
  22. optional object containing additional parsing options.
  23. ```js
  24. var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2');
  25. // { foo: 'bar', equation: 'E=mc^2' }
  26. ```
  27. #### Options
  28. `cookie.parse` accepts these properties in the options object.
  29. ##### decode
  30. Specifies a function that will be used to decode a cookie's value. Since the value of a cookie
  31. has a limited character set (and must be a simple string), this function can be used to decode
  32. a previously-encoded cookie value into a JavaScript string or other object.
  33. The default function is the global `decodeURIComponent`, which will decode any URL-encoded
  34. sequences into their byte representations.
  35. **note** if an error is thrown from this function, the original, non-decoded cookie value will
  36. be returned as the cookie's value.
  37. ### cookie.serialize(name, value, options)
  38. Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the
  39. name for the cookie, the `value` argument is the value to set the cookie to, and the `options`
  40. argument is an optional object containing additional serialization options.
  41. ```js
  42. var setCookie = cookie.serialize('foo', 'bar');
  43. // foo=bar
  44. ```
  45. #### Options
  46. `cookie.serialize` accepts these properties in the options object.
  47. ##### domain
  48. Specifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6265-5.2.3]. By default, no
  49. domain is set, and most clients will consider the cookie to apply to only the current domain.
  50. ##### encode
  51. Specifies a function that will be used to encode a cookie's value. Since value of a cookie
  52. has a limited character set (and must be a simple string), this function can be used to encode
  53. a value into a string suited for a cookie's value.
  54. The default function is the global `encodeURIComponent`, which will encode a JavaScript string
  55. into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range.
  56. ##### expires
  57. Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6265-5.2.1].
  58. By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and
  59. will delete it on a condition like exiting a web browser application.
  60. **note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and
  61. `maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,
  62. so if both are set, they should point to the same date and time.
  63. ##### httpOnly
  64. Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6265-5.2.6]. When truthy,
  65. the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set.
  66. **note** be careful when setting this to `true`, as compliant clients will not allow client-side
  67. JavaScript to see the cookie in `document.cookie`.
  68. ##### maxAge
  69. Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6265-5.2.2].
  70. The given number will be converted to an integer by rounding down. By default, no maximum age is set.
  71. **note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and
  72. `maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,
  73. so if both are set, they should point to the same date and time.
  74. ##### partitioned
  75. Specifies the `boolean` value for the [`Partitioned` `Set-Cookie`](rfc-cutler-httpbis-partitioned-cookies)
  76. attribute. When truthy, the `Partitioned` attribute is set, otherwise it is not. By default, the
  77. `Partitioned` attribute is not set.
  78. **note** This is an attribute that has not yet been fully standardized, and may change in the future.
  79. This also means many clients may ignore this attribute until they understand it.
  80. More information about can be found in [the proposal](https://github.com/privacycg/CHIPS).
  81. ##### path
  82. Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6265-5.2.4]. By default, the path
  83. is considered the ["default path"][rfc-6265-5.1.4].
  84. ##### priority
  85. Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribute][rfc-west-cookie-priority-00-4.1].
  86. - `'low'` will set the `Priority` attribute to `Low`.
  87. - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set.
  88. - `'high'` will set the `Priority` attribute to `High`.
  89. More information about the different priority levels can be found in
  90. [the specification][rfc-west-cookie-priority-00-4.1].
  91. **note** This is an attribute that has not yet been fully standardized, and may change in the future.
  92. This also means many clients may ignore this attribute until they understand it.
  93. ##### sameSite
  94. Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][rfc-6265bis-09-5.4.7].
  95. - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
  96. - `false` will not set the `SameSite` attribute.
  97. - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement.
  98. - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.
  99. - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
  100. More information about the different enforcement levels can be found in
  101. [the specification][rfc-6265bis-09-5.4.7].
  102. **note** This is an attribute that has not yet been fully standardized, and may change in the future.
  103. This also means many clients may ignore this attribute until they understand it.
  104. ##### secure
  105. Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6265-5.2.5]. When truthy,
  106. the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set.
  107. **note** be careful when setting this to `true`, as compliant clients will not send the cookie back to
  108. the server in the future if the browser does not have an HTTPS connection.
  109. ## Example
  110. The following example uses this module in conjunction with the Node.js core HTTP server
  111. to prompt a user for their name and display it back on future visits.
  112. ```js
  113. var cookie = require('cookie');
  114. var escapeHtml = require('escape-html');
  115. var http = require('http');
  116. var url = require('url');
  117. function onRequest(req, res) {
  118. // Parse the query string
  119. var query = url.parse(req.url, true, true).query;
  120. if (query && query.name) {
  121. // Set a new cookie with the name
  122. res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), {
  123. httpOnly: true,
  124. maxAge: 60 * 60 * 24 * 7 // 1 week
  125. }));
  126. // Redirect back after setting cookie
  127. res.statusCode = 302;
  128. res.setHeader('Location', req.headers.referer || '/');
  129. res.end();
  130. return;
  131. }
  132. // Parse the cookies on the request
  133. var cookies = cookie.parse(req.headers.cookie || '');
  134. // Get the visitor name set in the cookie
  135. var name = cookies.name;
  136. res.setHeader('Content-Type', 'text/html; charset=UTF-8');
  137. if (name) {
  138. res.write('<p>Welcome back, <b>' + escapeHtml(name) + '</b>!</p>');
  139. } else {
  140. res.write('<p>Hello, new visitor!</p>');
  141. }
  142. res.write('<form method="GET">');
  143. res.write('<input placeholder="enter your name" name="name"> <input type="submit" value="Set Name">');
  144. res.end('</form>');
  145. }
  146. http.createServer(onRequest).listen(3000);
  147. ```
  148. ## Testing
  149. ```sh
  150. $ npm test
  151. ```
  152. ## Benchmark
  153. ```
  154. $ npm run bench
  155. > cookie@0.5.0 bench
  156. > node benchmark/index.js
  157. node@18.18.2
  158. acorn@8.10.0
  159. ada@2.6.0
  160. ares@1.19.1
  161. brotli@1.0.9
  162. cldr@43.1
  163. icu@73.2
  164. llhttp@6.0.11
  165. modules@108
  166. napi@9
  167. nghttp2@1.57.0
  168. nghttp3@0.7.0
  169. ngtcp2@0.8.1
  170. openssl@3.0.10+quic
  171. simdutf@3.2.14
  172. tz@2023c
  173. undici@5.26.3
  174. unicode@15.0
  175. uv@1.44.2
  176. uvwasi@0.0.18
  177. v8@10.2.154.26-node.26
  178. zlib@1.2.13.1-motley
  179. > node benchmark/parse-top.js
  180. cookie.parse - top sites
  181. 14 tests completed.
  182. parse accounts.google.com x 2,588,913 ops/sec ±0.74% (186 runs sampled)
  183. parse apple.com x 2,370,002 ops/sec ±0.69% (186 runs sampled)
  184. parse cloudflare.com x 2,213,102 ops/sec ±0.88% (188 runs sampled)
  185. parse docs.google.com x 2,194,157 ops/sec ±1.03% (184 runs sampled)
  186. parse drive.google.com x 2,265,084 ops/sec ±0.79% (187 runs sampled)
  187. parse en.wikipedia.org x 457,099 ops/sec ±0.81% (186 runs sampled)
  188. parse linkedin.com x 504,407 ops/sec ±0.89% (186 runs sampled)
  189. parse maps.google.com x 1,230,959 ops/sec ±0.98% (186 runs sampled)
  190. parse microsoft.com x 926,294 ops/sec ±0.88% (184 runs sampled)
  191. parse play.google.com x 2,311,338 ops/sec ±0.83% (185 runs sampled)
  192. parse support.google.com x 1,508,850 ops/sec ±0.86% (186 runs sampled)
  193. parse www.google.com x 1,022,582 ops/sec ±1.32% (182 runs sampled)
  194. parse youtu.be x 332,136 ops/sec ±1.02% (185 runs sampled)
  195. parse youtube.com x 323,833 ops/sec ±0.77% (183 runs sampled)
  196. > node benchmark/parse.js
  197. cookie.parse - generic
  198. 6 tests completed.
  199. simple x 3,214,032 ops/sec ±1.61% (183 runs sampled)
  200. decode x 587,237 ops/sec ±1.16% (187 runs sampled)
  201. unquote x 2,954,618 ops/sec ±1.35% (183 runs sampled)
  202. duplicates x 857,008 ops/sec ±0.89% (187 runs sampled)
  203. 10 cookies x 292,133 ops/sec ±0.89% (187 runs sampled)
  204. 100 cookies x 22,610 ops/sec ±0.68% (187 runs sampled)
  205. ```
  206. ## References
  207. - [RFC 6265: HTTP State Management Mechanism][rfc-6265]
  208. - [Same-site Cookies][rfc-6265bis-09-5.4.7]
  209. [rfc-cutler-httpbis-partitioned-cookies]: https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/
  210. [rfc-west-cookie-priority-00-4.1]: https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1
  211. [rfc-6265bis-09-5.4.7]: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7
  212. [rfc-6265]: https://tools.ietf.org/html/rfc6265
  213. [rfc-6265-5.1.4]: https://tools.ietf.org/html/rfc6265#section-5.1.4
  214. [rfc-6265-5.2.1]: https://tools.ietf.org/html/rfc6265#section-5.2.1
  215. [rfc-6265-5.2.2]: https://tools.ietf.org/html/rfc6265#section-5.2.2
  216. [rfc-6265-5.2.3]: https://tools.ietf.org/html/rfc6265#section-5.2.3
  217. [rfc-6265-5.2.4]: https://tools.ietf.org/html/rfc6265#section-5.2.4
  218. [rfc-6265-5.2.5]: https://tools.ietf.org/html/rfc6265#section-5.2.5
  219. [rfc-6265-5.2.6]: https://tools.ietf.org/html/rfc6265#section-5.2.6
  220. [rfc-6265-5.3]: https://tools.ietf.org/html/rfc6265#section-5.3
  221. ## License
  222. [MIT](LICENSE)
  223. [ci-image]: https://badgen.net/github/checks/jshttp/cookie/master?label=ci
  224. [ci-url]: https://github.com/jshttp/cookie/actions/workflows/ci.yml
  225. [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/cookie/master
  226. [coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master
  227. [node-image]: https://badgen.net/npm/node/cookie
  228. [node-url]: https://nodejs.org/en/download
  229. [npm-downloads-image]: https://badgen.net/npm/dm/cookie
  230. [npm-url]: https://npmjs.org/package/cookie
  231. [npm-version-image]: https://badgen.net/npm/v/cookie