Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

HTTP server cookie parsing and serialization

License

NotificationsYou must be signed in to change notification settings

jshttp/cookie

Repository files navigation

NPM VersionNPM DownloadsBuild StatusCoverage Status

Basic HTTP cookie parser and serializer for HTTP servers.

Installation

$ npm install cookie

API

constcookie=require("cookie");// import * as cookie from 'cookie';

cookie.parse(str, options)

Parse a HTTPCookie header string and returning an object of all cookie name-value pairs.Thestr argument is the string representing aCookie header value andoptions is anoptional object containing additional parsing options.

constcookies=cookie.parse("foo=bar; equation=E%3Dmc%5E2");// { foo: 'bar', equation: 'E=mc^2' }

Options

cookie.parse accepts these properties in the options object.

decode

Specifies a function that will be used to decode acookie-value.Since the value of a cookie has a limited character set (and must be a simple string), this function can be used to decodea previously-encoded cookie value into a JavaScript string.

The default function is the globaldecodeURIComponent, wrapped in atry..catch. If an erroris thrown it will return the cookie's original value. If you provide your own encode/decodescheme you must ensure errors are appropriately handled.

cookie.serialize(name, value, options)

Serialize a cookie name-value pair into aSet-Cookie header string. Thename argument is thename for the cookie, thevalue argument is the value to set the cookie to, and theoptionsargument is an optional object containing additional serialization options.

constsetCookie=cookie.serialize("foo","bar");// foo=bar

Options

cookie.serialize accepts these properties in the options object.

encode

Specifies a function that will be used to encode acookie-value.Since value of a cookie has a limited character set (and must be a simple string), this function can be used to encodea value into a string suited for a cookie's value, and should mirrordecode when parsing.

The default function is the globalencodeURIComponent.

maxAge

Specifies thenumber (in seconds) to be the value for theMax-AgeSet-Cookie attribute.

Thecookie storage model specification states that if bothexpires andmaxAge are set, thenmaxAge takes precedence, but it is possible not all clients by obey this,so if both are set, they should point to the same date and time.

expires

Specifies theDate object to be the value for theExpiresSet-Cookie attribute.When no expiration is set, clients consider this a "non-persistent cookie" and delete it when the current session is over.

Thecookie storage model specification states that if bothexpires andmaxAge are set, thenmaxAge takes precedence, but it is possible not all clients by obey this,so if both are set, they should point to the same date and time.

domain

Specifies the value for theDomainSet-Cookie attribute.When no domain is set, clients consider the cookie to apply to the current domain only.

path

Specifies the value for thePathSet-Cookie attribute.When no path is set, the path is considered the"default path".

httpOnly

Enables theHttpOnlySet-Cookie attribute.When enabled, clients will not allow client-side JavaScript to see the cookie indocument.cookie.

secure

Enables theSecureSet-Cookie attribute.When enabled, clients will only send the cookie back if the browser has a HTTPS connection.

partitioned

Enables thePartitionedSet-Cookie attribute.When enabled, clients will only send the cookie back when the current domainand top-level domain matches.

This is an attribute that has not yet been fully standardized, and may change in the future.This also means clients may ignore this attribute until they understand it. More informationabout can be found inthe proposal.

priority

Specifies the value for thePrioritySet-Cookie attribute.

  • 'low' will set thePriority attribute toLow.
  • 'medium' will set thePriority attribute toMedium, the default priority when not set.
  • 'high' will set thePriority attribute toHigh.

More information about priority levels can be found inthe specification.

sameSite

Specifies the value for theSameSiteSet-Cookie attribute.

  • true will set theSameSite attribute toStrict for strict same site enforcement.
  • 'lax' will set theSameSite attribute toLax for lax same site enforcement.
  • 'none' will set theSameSite attribute toNone for an explicit cross-site cookie.
  • 'strict' will set theSameSite attribute toStrict for strict same site enforcement.

More information about enforcement levels can be found inthe specification.

Example

The following example uses this module in conjunction with the Node.js core HTTP serverto prompt a user for their name and display it back on future visits.

varcookie=require("cookie");varescapeHtml=require("escape-html");varhttp=require("http");varurl=require("url");functiononRequest(req,res){// Parse the query stringvarquery=url.parse(req.url,true,true).query;if(query&&query.name){// Set a new cookie with the nameres.setHeader("Set-Cookie",cookie.serialize("name",String(query.name),{httpOnly:true,maxAge:60*60*24*7,// 1 week}),);// Redirect back after setting cookieres.statusCode=302;res.setHeader("Location",req.headers.referer||"/");res.end();return;}// Parse the cookies on the requestvarcookies=cookie.parse(req.headers.cookie||"");// Get the visitor name set in the cookievarname=cookies.name;res.setHeader("Content-Type","text/html; charset=UTF-8");if(name){res.write("<p>Welcome back, <b>"+escapeHtml(name)+"</b>!</p>");}else{res.write("<p>Hello, new visitor!</p>");}res.write('<form method="GET">');res.write('<input placeholder="enter your name" name="name"> <input type="submit" value="Set Name">',);res.end("</form>");}http.createServer(onRequest).listen(3000);

Testing

npmtest

Benchmark

npm run bench
     name                   hz     min     max    mean     p75     p99    p995    p999     rme  samples   · simple       8,566,313.09  0.0000  0.3694  0.0001  0.0001  0.0002  0.0002  0.0003  ±0.64%  4283157   fastest   · decode       3,834,348.85  0.0001  0.2465  0.0003  0.0003  0.0003  0.0004  0.0006  ±0.38%  1917175   · unquote      8,315,355.96  0.0000  0.3824  0.0001  0.0001  0.0002  0.0002  0.0003  ±0.72%  4157880   · duplicates   1,944,765.97  0.0004  0.2959  0.0005  0.0005  0.0006  0.0006  0.0008  ±0.24%   972384   · 10 cookies     675,345.67  0.0012  0.4328  0.0015  0.0015  0.0019  0.0020  0.0058  ±0.75%   337673   · 100 cookies     61,040.71  0.0152  0.4092  0.0164  0.0160  0.0196  0.0228  0.2260  ±0.71%    30521   slowest   ✓ parse top-sites (15) 22945ms     name                                  hz     min     max    mean     p75     p99    p995    p999     rme   samples   · parse accounts.google.com   7,164,349.17  0.0000  0.0929  0.0001  0.0002  0.0002  0.0002  0.0003  ±0.09%   3582184   · parse apple.com             7,817,686.84  0.0000  0.6048  0.0001  0.0001  0.0002  0.0002  0.0003  ±1.05%   3908844   · parse cloudflare.com        7,189,841.70  0.0000  0.0390  0.0001  0.0002  0.0002  0.0002  0.0003  ±0.06%   3594921   · parse docs.google.com       7,051,765.61  0.0000  0.0296  0.0001  0.0002  0.0002  0.0002  0.0003  ±0.06%   3525883   · parse drive.google.com      7,349,104.77  0.0000  0.0368  0.0001  0.0001  0.0002  0.0002  0.0003  ±0.05%   3674553   · parse en.wikipedia.org      1,929,909.49  0.0004  0.3598  0.0005  0.0005  0.0007  0.0007  0.0012  ±0.16%    964955   · parse linkedin.com          2,225,658.01  0.0003  0.0595  0.0004  0.0005  0.0005  0.0005  0.0006  ±0.06%   1112830   · parse maps.google.com       4,423,511.68  0.0001  0.0942  0.0002  0.0003  0.0003  0.0003  0.0005  ±0.08%   2211756   · parse microsoft.com         3,387,601.88  0.0002  0.0725  0.0003  0.0003  0.0004  0.0004  0.0005  ±0.09%   1693801   · parse play.google.com       7,375,980.86  0.0000  0.1994  0.0001  0.0001  0.0002  0.0002  0.0003  ±0.12%   3687991   · parse support.google.com    4,912,267.94  0.0001  2.8958  0.0002  0.0002  0.0003  0.0003  0.0005  ±1.28%   2456134   · parse www.google.com        3,443,035.87  0.0002  0.2783  0.0003  0.0003  0.0004  0.0004  0.0007  ±0.51%   1721518   · parse youtu.be              1,910,492.87  0.0004  0.3490  0.0005  0.0005  0.0007  0.0007  0.0011  ±0.46%    955247   · parse youtube.com           1,895,082.62  0.0004  0.7454  0.0005  0.0005  0.0006  0.0007  0.0013  ±0.64%    947542   slowest   · parse example.com          21,582,835.27  0.0000  0.1095  0.0000  0.0000  0.0001  0.0001  0.0001  ±0.13%  10791418

References

License

MIT

About

HTTP server cookie parsing and serialization

Topics

Resources

License

Security policy

Stars

Watchers

Forks

Sponsor this project

    Packages

    No packages published

    [8]ページ先頭

    ©2009-2025 Movatter.jp