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.

257 lines
8.8 KiB

  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. 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. ##### path
  75. Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6265-5.2.4]. By default, the path
  76. is considered the ["default path"][rfc-6265-5.1.4].
  77. ##### sameSite
  78. Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][rfc-6265bis-03-4.1.2.7].
  79. - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
  80. - `false` will not set the `SameSite` attribute.
  81. - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement.
  82. - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.
  83. - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
  84. More information about the different enforcement levels can be found in
  85. [the specification][rfc-6265bis-03-4.1.2.7].
  86. **note** This is an attribute that has not yet been fully standardized, and may change in the future.
  87. This also means many clients may ignore this attribute until they understand it.
  88. ##### secure
  89. Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6265-5.2.5]. When truthy,
  90. the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set.
  91. **note** be careful when setting this to `true`, as compliant clients will not send the cookie back to
  92. the server in the future if the browser does not have an HTTPS connection.
  93. ## Example
  94. The following example uses this module in conjunction with the Node.js core HTTP server
  95. to prompt a user for their name and display it back on future visits.
  96. ```js
  97. var cookie = require('cookie');
  98. var escapeHtml = require('escape-html');
  99. var http = require('http');
  100. var url = require('url');
  101. function onRequest(req, res) {
  102. // Parse the query string
  103. var query = url.parse(req.url, true, true).query;
  104. if (query && query.name) {
  105. // Set a new cookie with the name
  106. res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), {
  107. httpOnly: true,
  108. maxAge: 60 * 60 * 24 * 7 // 1 week
  109. }));
  110. // Redirect back after setting cookie
  111. res.statusCode = 302;
  112. res.setHeader('Location', req.headers.referer || '/');
  113. res.end();
  114. return;
  115. }
  116. // Parse the cookies on the request
  117. var cookies = cookie.parse(req.headers.cookie || '');
  118. // Get the visitor name set in the cookie
  119. var name = cookies.name;
  120. res.setHeader('Content-Type', 'text/html; charset=UTF-8');
  121. if (name) {
  122. res.write('<p>Welcome back, <b>' + escapeHtml(name) + '</b>!</p>');
  123. } else {
  124. res.write('<p>Hello, new visitor!</p>');
  125. }
  126. res.write('<form method="GET">');
  127. res.write('<input placeholder="enter your name" name="name"> <input type="submit" value="Set Name">');
  128. res.end('</form>');
  129. }
  130. http.createServer(onRequest).listen(3000);
  131. ```
  132. ## Testing
  133. ```sh
  134. $ npm test
  135. ```
  136. ## Benchmark
  137. ```
  138. $ npm run bench
  139. > cookie@0.3.1 bench cookie
  140. > node benchmark/index.js
  141. http_parser@2.8.0
  142. node@6.14.2
  143. v8@5.1.281.111
  144. uv@1.16.1
  145. zlib@1.2.11
  146. ares@1.10.1-DEV
  147. icu@58.2
  148. modules@48
  149. napi@3
  150. openssl@1.0.2o
  151. > node benchmark/parse.js
  152. cookie.parse
  153. 6 tests completed.
  154. simple x 1,200,691 ops/sec ±1.12% (189 runs sampled)
  155. decode x 1,012,994 ops/sec ±0.97% (186 runs sampled)
  156. unquote x 1,074,174 ops/sec ±2.43% (186 runs sampled)
  157. duplicates x 438,424 ops/sec ±2.17% (184 runs sampled)
  158. 10 cookies x 147,154 ops/sec ±1.01% (186 runs sampled)
  159. 100 cookies x 14,274 ops/sec ±1.07% (187 runs sampled)
  160. ```
  161. ## References
  162. - [RFC 6265: HTTP State Management Mechanism][rfc-6265]
  163. - [Same-site Cookies][rfc-6265bis-03-4.1.2.7]
  164. [rfc-6265bis-03-4.1.2.7]: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7
  165. [rfc-6265]: https://tools.ietf.org/html/rfc6265
  166. [rfc-6265-5.1.4]: https://tools.ietf.org/html/rfc6265#section-5.1.4
  167. [rfc-6265-5.2.1]: https://tools.ietf.org/html/rfc6265#section-5.2.1
  168. [rfc-6265-5.2.2]: https://tools.ietf.org/html/rfc6265#section-5.2.2
  169. [rfc-6265-5.2.3]: https://tools.ietf.org/html/rfc6265#section-5.2.3
  170. [rfc-6265-5.2.4]: https://tools.ietf.org/html/rfc6265#section-5.2.4
  171. [rfc-6265-5.2.5]: https://tools.ietf.org/html/rfc6265#section-5.2.5
  172. [rfc-6265-5.2.6]: https://tools.ietf.org/html/rfc6265#section-5.2.6
  173. [rfc-6265-5.3]: https://tools.ietf.org/html/rfc6265#section-5.3
  174. ## License
  175. [MIT](LICENSE)
  176. [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/cookie/master
  177. [coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master
  178. [node-version-image]: https://badgen.net/npm/node/cookie
  179. [node-version-url]: https://nodejs.org/en/download
  180. [npm-downloads-image]: https://badgen.net/npm/dm/cookie
  181. [npm-url]: https://npmjs.org/package/cookie
  182. [npm-version-image]: https://badgen.net/npm/v/cookie
  183. [travis-image]: https://badgen.net/travis/jshttp/cookie/master
  184. [travis-url]: https://travis-ci.org/jshttp/cookie