You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

253 lines
8.6 KiB

4 years ago
  1. # cookie
  2. [![NPM Version][npm-version-image]][npm-url]
  3. [![NPM Downloads][npm-downloads-image]][npm-url]
  4. [![Node.js Version][node-version-image]][node-version-url]
  5. [![Build Status][travis-image]][travis-url]
  6. [![Test Coverage][coveralls-image]][coveralls-url]
  7. Basic HTTP cookie parser and serializer for HTTP servers.
  8. ## Installation
  9. ```sh
  10. $ npm install cookie
  11. ```
  12. ## API
  13. ```js
  14. var cookie = require('cookie');
  15. ```
  16. ### cookie.parse(str, options)
  17. Parse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs.
  18. The `str` argument is the string representing a `Cookie` header value and `options` is an
  19. optional object containing additional parsing options.
  20. ```js
  21. var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2');
  22. // { foo: 'bar', equation: 'E=mc^2' }
  23. ```
  24. #### Options
  25. `cookie.parse` accepts these properties in the options object.
  26. ##### decode
  27. Specifies a function that will be used to decode a cookie's value. Since the value of a cookie
  28. has a limited character set (and must be a simple string), this function can be used to decode
  29. a previously-encoded cookie value into a JavaScript string or other object.
  30. The default function is the global `decodeURIComponent`, which will decode any URL-encoded
  31. sequences into their byte representations.
  32. **note** if an error is thrown from this function, the original, non-decoded cookie value will
  33. be returned as the cookie's value.
  34. ### cookie.serialize(name, value, options)
  35. Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the
  36. name for the cookie, the `value` argument is the value to set the cookie to, and the `options`
  37. argument is an optional object containing additional serialization options.
  38. ```js
  39. var setCookie = cookie.serialize('foo', 'bar');
  40. // foo=bar
  41. ```
  42. #### Options
  43. `cookie.serialize` accepts these properties in the options object.
  44. ##### domain
  45. Specifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6265-5.2.3]. By default, no
  46. domain is set, and most clients will consider the cookie to apply to only the current domain.
  47. ##### encode
  48. Specifies a function that will be used to encode a cookie's value. Since value of a cookie
  49. has a limited character set (and must be a simple string), this function can be used to encode
  50. a value into a string suited for a cookie's value.
  51. The default function is the global `encodeURIComponent`, which will encode a JavaScript string
  52. into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range.
  53. ##### expires
  54. Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6265-5.2.1].
  55. By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and
  56. will delete it on a condition like exiting a web browser application.
  57. **note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and
  58. `maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,
  59. so if both are set, they should point to the same date and time.
  60. ##### httpOnly
  61. Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6265-5.2.6]. When truthy,
  62. the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set.
  63. **note** be careful when setting this to `true`, as compliant clients will not allow client-side
  64. JavaScript to see the cookie in `document.cookie`.
  65. ##### maxAge
  66. Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6265-5.2.2].
  67. The given number will be converted to an integer by rounding down. By default, no maximum age is set.
  68. **note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and
  69. `maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,
  70. so if both are set, they should point to the same date and time.
  71. ##### path
  72. Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6265-5.2.4]. By default, the path
  73. is considered the ["default path"][rfc-6265-5.1.4].
  74. ##### sameSite
  75. Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][rfc-6265bis-03-4.1.2.7].
  76. - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
  77. - `false` will not set the `SameSite` attribute.
  78. - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement.
  79. - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.
  80. - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
  81. More information about the different enforcement levels can be found in
  82. [the specification][rfc-6265bis-03-4.1.2.7].
  83. **note** This is an attribute that has not yet been fully standardized, and may change in the future.
  84. This also means many clients may ignore this attribute until they understand it.
  85. ##### secure
  86. Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6265-5.2.5]. When truthy,
  87. the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set.
  88. **note** be careful when setting this to `true`, as compliant clients will not send the cookie back to
  89. the server in the future if the browser does not have an HTTPS connection.
  90. ## Example
  91. The following example uses this module in conjunction with the Node.js core HTTP server
  92. to prompt a user for their name and display it back on future visits.
  93. ```js
  94. var cookie = require('cookie');
  95. var escapeHtml = require('escape-html');
  96. var http = require('http');
  97. var url = require('url');
  98. function onRequest(req, res) {
  99. // Parse the query string
  100. var query = url.parse(req.url, true, true).query;
  101. if (query && query.name) {
  102. // Set a new cookie with the name
  103. res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), {
  104. httpOnly: true,
  105. maxAge: 60 * 60 * 24 * 7 // 1 week
  106. }));
  107. // Redirect back after setting cookie
  108. res.statusCode = 302;
  109. res.setHeader('Location', req.headers.referer || '/');
  110. res.end();
  111. return;
  112. }
  113. // Parse the cookies on the request
  114. var cookies = cookie.parse(req.headers.cookie || '');
  115. // Get the visitor name set in the cookie
  116. var name = cookies.name;
  117. res.setHeader('Content-Type', 'text/html; charset=UTF-8');
  118. if (name) {
  119. res.write('<p>Welcome back, <b>' + escapeHtml(name) + '</b>!</p>');
  120. } else {
  121. res.write('<p>Hello, new visitor!</p>');
  122. }
  123. res.write('<form method="GET">');
  124. res.write('<input placeholder="enter your name" name="name"> <input type="submit" value="Set Name">');
  125. res.end('</form>');
  126. }
  127. http.createServer(onRequest).listen(3000);
  128. ```
  129. ## Testing
  130. ```sh
  131. $ npm test
  132. ```
  133. ## Benchmark
  134. ```
  135. $ npm run bench
  136. > cookie@0.3.1 bench cookie
  137. > node benchmark/index.js
  138. http_parser@2.8.0
  139. node@6.14.2
  140. v8@5.1.281.111
  141. uv@1.16.1
  142. zlib@1.2.11
  143. ares@1.10.1-DEV
  144. icu@58.2
  145. modules@48
  146. napi@3
  147. openssl@1.0.2o
  148. > node benchmark/parse.js
  149. cookie.parse
  150. 6 tests completed.
  151. simple x 1,200,691 ops/sec ±1.12% (189 runs sampled)
  152. decode x 1,012,994 ops/sec ±0.97% (186 runs sampled)
  153. unquote x 1,074,174 ops/sec ±2.43% (186 runs sampled)
  154. duplicates x 438,424 ops/sec ±2.17% (184 runs sampled)
  155. 10 cookies x 147,154 ops/sec ±1.01% (186 runs sampled)
  156. 100 cookies x 14,274 ops/sec ±1.07% (187 runs sampled)
  157. ```
  158. ## References
  159. - [RFC 6265: HTTP State Management Mechanism][rfc-6265]
  160. - [Same-site Cookies][rfc-6265bis-03-4.1.2.7]
  161. [rfc-6265bis-03-4.1.2.7]: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7
  162. [rfc-6265]: https://tools.ietf.org/html/rfc6265
  163. [rfc-6265-5.1.4]: https://tools.ietf.org/html/rfc6265#section-5.1.4
  164. [rfc-6265-5.2.1]: https://tools.ietf.org/html/rfc6265#section-5.2.1
  165. [rfc-6265-5.2.2]: https://tools.ietf.org/html/rfc6265#section-5.2.2
  166. [rfc-6265-5.2.3]: https://tools.ietf.org/html/rfc6265#section-5.2.3
  167. [rfc-6265-5.2.4]: https://tools.ietf.org/html/rfc6265#section-5.2.4
  168. [rfc-6265-5.2.5]: https://tools.ietf.org/html/rfc6265#section-5.2.5
  169. [rfc-6265-5.2.6]: https://tools.ietf.org/html/rfc6265#section-5.2.6
  170. [rfc-6265-5.3]: https://tools.ietf.org/html/rfc6265#section-5.3
  171. ## License
  172. [MIT](LICENSE)
  173. [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/cookie/master
  174. [coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master
  175. [node-version-image]: https://badgen.net/npm/node/cookie
  176. [node-version-url]: https://nodejs.org/en/download
  177. [npm-downloads-image]: https://badgen.net/npm/dm/cookie
  178. [npm-url]: https://npmjs.org/package/cookie
  179. [npm-version-image]: https://badgen.net/npm/v/cookie
  180. [travis-image]: https://badgen.net/travis/jshttp/cookie/master
  181. [travis-url]: https://travis-ci.org/jshttp/cookie