{"id":13679662,"url":"https://github.com/expressjs/cookie-session","last_synced_at":"2025-05-12T13:20:23.596Z","repository":{"id":14395756,"uuid":"17106306","full_name":"expressjs/cookie-session","owner":"expressjs","description":"Simple cookie-based session middleware","archived":false,"fork":false,"pushed_at":"2025-04-17T14:14:17.000Z","size":202,"stargazers_count":1135,"open_issues_count":7,"forks_count":208,"subscribers_count":21,"default_branch":"master","last_synced_at":"2025-04-23T16:01:48.150Z","etag":null,"topics":["cookie","expressjs","javascript","middleware","nodejs","session"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/expressjs.png","metadata":{"files":{"readme":"README.md","changelog":"HISTORY.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"open_collective":"express"}},"created_at":"2014-02-23T10:52:57.000Z","updated_at":"2025-04-22T05:10:11.000Z","dependencies_parsed_at":"2024-01-12T01:57:09.630Z","dependency_job_id":"a0a4675d-3ffe-471d-a0b1-85547e961564","html_url":"https://github.com/expressjs/cookie-session","commit_stats":{"total_commits":414,"total_committers":17,"mean_commits":"24.352941176470587","dds":0.05555555555555558,"last_synced_commit":"a9466a898b6017db710bae3c6734d7b039e0ded5"},"previous_names":[],"tags_count":19,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/expressjs%2Fcookie-session","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/expressjs%2Fcookie-session/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/expressjs%2Fcookie-session/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/expressjs%2Fcookie-session/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/expressjs","download_url":"https://codeload.github.com/expressjs/cookie-session/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253745197,"owners_count":21957320,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cookie","expressjs","javascript","middleware","nodejs","session"],"created_at":"2024-08-02T13:01:08.059Z","updated_at":"2025-05-12T13:20:23.575Z","avatar_url":"https://github.com/expressjs.png","language":"JavaScript","readme":"# cookie-session\n\n[![NPM Version][npm-version-image]][npm-url]\n[![NPM Downloads][npm-downloads-image]][npm-url]\n[![Build Status][ci-image]][ci-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\nSimple cookie-based session middleware.\n\nA user session can be stored in two main ways with cookies: on the server or on\nthe client. This module stores the session data on the client within a cookie,\nwhile a module like [express-session](https://www.npmjs.com/package/express-session)\nstores only a session identifier on the client within a cookie and stores the\nsession data on the server, typically in a database.\n\nThe following points can help you choose which to use:\n\n  * `cookie-session` does not require any database / resources on the server side,\n    though the total session data cannot exceed the browser's max cookie size.\n  * `cookie-session` can simplify certain load-balanced scenarios.\n  * `cookie-session` can be used to store a \"light\" session and include an identifier\n    to look up a database-backed secondary store to reduce database lookups.\n\n**NOTE** This module does not encrypt the session contents in the cookie, only provides\nsigning to prevent tampering. The client will be able to read the session data by\nexamining the cookie's value. Secret data should not be set in `req.session` without\nencrypting it, or use a server-side session instead.\n\n**NOTE** This module does not prevent session replay, as the expiration set is that\nof the cookie only; if that is a concern of your application, you can store an expiration\ndate in `req.session` object and validate it on the sever, and implement any other logic\nto extend the session as your application needs.\n\n## Install\n\nThis is a [Node.js](https://nodejs.org/en/) module available through the\n[npm registry](https://www.npmjs.com/). Installation is done using the\n[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):\n\n```sh\n$ npm install cookie-session\n```\n\n## API\n\n```js\nvar cookieSession = require('cookie-session')\nvar express = require('express')\n\nvar app = express()\n\napp.use(cookieSession({\n  name: 'session',\n  keys: [/* secret keys */],\n\n  // Cookie Options\n  maxAge: 24 * 60 * 60 * 1000 // 24 hours\n}))\n```\n\n### cookieSession(options)\n\nCreate a new cookie session middleware with the provided options. This middleware\nwill attach the property `session` to `req`, which provides an object representing\nthe loaded session. This session is either a new session if no valid session was\nprovided in the request, or a loaded session from the request.\n\nThe middleware will automatically add a `Set-Cookie` header to the response if the\ncontents of `req.session` were altered. _Note_ that no `Set-Cookie` header will be\nin the response (and thus no session created for a specific user) unless there are\ncontents in the session, so be sure to add something to `req.session` as soon as\nyou have identifying information to store for the session.\n\n#### Options\n\nCookie session accepts these properties in the options object.\n\n##### name\n\nThe name of the cookie to set, defaults to `session`.\n\n##### keys\n\nThe list of keys to use to sign \u0026 verify cookie values, or a configured\n[`Keygrip`](https://www.npmjs.com/package/keygrip) instance. Set cookies are always\nsigned with `keys[0]`, while the other keys are valid for verification, allowing\nfor key rotation. If a `Keygrip` instance is provided, it can be used to\nchange signature parameters like the algorithm of the signature.\n\n##### secret\n\nA string which will be used as single key if `keys` is not provided.\n\n##### Cookie Options\n\nOther options are passed to `cookies.get()` and `cookies.set()` allowing you\nto control security, domain, path, and signing among other settings.\n\nThe options can also contain any of the following (for the full list, see\n[cookies module documentation](https://www.npmjs.org/package/cookies#readme):\n\n  - `maxAge`: a number representing the milliseconds from `Date.now()` for expiry\n  - `expires`: a `Date` object indicating the cookie's expiration date (expires at the end of session by default).\n  - `path`: a string indicating the path of the cookie (`/` by default).\n  - `domain`: a string indicating the domain of the cookie (no default).\n  - `partitioned`: a boolean indicating whether to partition the cookie in Chrome for the [CHIPS Update](https://developers.google.com/privacy-sandbox/3pcd/chips) (`false` by default). If this is true, Cookies from embedded sites will be partitioned and only readable from the same top level site from which it was created.\n  - `priority`: a string indicating the cookie priority. This can be set to `'low'`, `'medium'`, or `'high'`.\n  - `sameSite`: a boolean or string indicating whether the cookie is a \"same site\" cookie (`false` by default). This can be set to `'strict'`, `'lax'`, `'none'`, or `true` (which maps to `'strict'`).\n  - `secure`: a boolean indicating whether the cookie is only to be sent over HTTPS (`false` by default for HTTP, `true` by default for HTTPS). If this is set to `true` and Node.js is not directly over a TLS connection, be sure to read how to [setup Express behind proxies](https://expressjs.com/en/guide/behind-proxies.html) or the cookie may not ever set correctly.\n  - `httpOnly`: a boolean indicating whether the cookie is only to be sent over HTTP(S), and not made available to client JavaScript (`true` by default).\n  - `signed`: a boolean indicating whether the cookie is to be signed (`true` by default).\n  - `overwrite`: a boolean indicating whether to overwrite previously set cookies of the same name (`true` by default).\n\n### req.session\n\nRepresents the session for the given request.\n\n#### .isChanged\n\nIs `true` if the session has been changed during the request.\n\n#### .isNew\n\nIs `true` if the session is new.\n\n#### .isPopulated\n\nDetermine if the session has been populated with data or is empty.\n\n### req.sessionOptions\n\nRepresents the session options for the current request. These options are a\nshallow clone of what was provided at middleware construction and can be\naltered to change cookie setting behavior on a per-request basis.\n\n### Destroying a session\n\nTo destroy a session simply set it to `null`:\n\n```js\nreq.session = null\n```\n\n### Saving a session\n\nSince the entire contents of the session is kept in a client-side cookie, the\nsession is \"saved\" by writing a cookie out in a `Set-Cookie` response header.\nThis is done automatically if there has been a change made to the session when\nthe Node.js response headers are being written to the client and the session\nwas not destroyed.\n\n## Examples\n\n### Simple view counter example\n\n```js\nvar cookieSession = require('cookie-session')\nvar express = require('express')\n\nvar app = express()\n\napp.set('trust proxy', 1) // trust first proxy\n\napp.use(cookieSession({\n  name: 'session',\n  keys: ['key1', 'key2']\n}))\n\napp.get('/', function (req, res, next) {\n  // Update views\n  req.session.views = (req.session.views || 0) + 1\n\n  // Write response\n  res.end(req.session.views + ' views')\n})\n\napp.listen(3000)\n```\n\n### Per-user sticky max age\n\n```js\nvar cookieSession = require('cookie-session')\nvar express = require('express')\n\nvar app = express()\n\napp.set('trust proxy', 1) // trust first proxy\n\napp.use(cookieSession({\n  name: 'session',\n  keys: ['key1', 'key2']\n}))\n\n// This allows you to set req.session.maxAge to let certain sessions\n// have a different value than the default.\napp.use(function (req, res, next) {\n  req.sessionOptions.maxAge = req.session.maxAge || req.sessionOptions.maxAge\n  next()\n})\n\n// ... your logic here ...\n```\n\n### Extending the session expiration\n\nThis module does not send a `Set-Cookie` header if the contents of the session\nhave not changed. This means that to extend the expiration of a session in the\nuser's browser (in response to user activity, for example) some kind of\nmodification to the session needs be made.\n\n```js\nvar cookieSession = require('cookie-session')\nvar express = require('express')\n\nvar app = express()\n\napp.use(cookieSession({\n  name: 'session',\n  keys: ['key1', 'key2']\n}))\n\n// Update a value in the cookie so that the set-cookie will be sent.\n// Only changes every minute so that it's not sent with every request.\napp.use(function (req, res, next) {\n  req.session.nowInMinutes = Math.floor(Date.now() / 60e3)\n  next()\n})\n\n// ... your logic here ...\n```\n\n### Using a custom signature algorithm\n\nThis example shows creating a custom `Keygrip` instance as the `keys` option\nto provide keys and additional signature configuration.\n\n```js\nvar cookieSession = require('cookie-session')\nvar express = require('express')\nvar Keygrip = require('keygrip')\n\nvar app = express()\n\napp.use(cookieSession({\n  name: 'session',\n  keys: new Keygrip(['key1', 'key2'], 'SHA384', 'base64')\n}))\n\n// ... your logic here ...\n```\n\n## Usage Limitations\n\n### Max Cookie Size\n\nBecause the entire session object is encoded and stored in a cookie, it is\npossible to exceed the maximum cookie size limits on different browsers. The\n[RFC6265 specification](https://tools.ietf.org/html/rfc6265#section-6.1)\nrecommends that a browser **SHOULD** allow\n\n\u003e At least 4096 bytes per cookie (as measured by the sum of the length of\n\u003e the cookie's name, value, and attributes)\n\nIn practice this limit differs slightly across browsers. See a list of\n[browser limits here](http://browsercookielimits.iain.guru). As a rule\nof thumb **don't exceed 4093 bytes per domain**.\n\nIf your session object is large enough to exceed a browser limit when encoded,\nin most cases the browser will refuse to store the cookie. This will cause the\nfollowing requests from the browser to either a) not have any session\ninformation or b) use old session information that was small enough to not\nexceed the cookie limit.\n\nIf you find your session object is hitting these limits, it is best to\nconsider if  data in your session should be loaded from a database on the\nserver instead of transmitted to/from the browser with every request. Or\nmove to an [alternative session strategy](https://github.com/expressjs/session#compatible-session-stores)\n\n## License\n\n[MIT](LICENSE)\n\n[ci-image]: https://badgen.net/github/checks/expressjs/cookie-session/master?label=ci\n[ci-url]: https://github.com/expressjs/cookie-session/actions?query=workflow%3Aci\n[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/cookie-session/master\n[coveralls-url]: https://coveralls.io/r/expressjs/cookie-session?branch=master\n[npm-downloads-image]: https://badgen.net/npm/dm/cookie-session\n[npm-url]: https://npmjs.org/package/cookie-session\n[npm-version-image]: https://badgen.net/npm/v/cookie-session\n","funding_links":["https://opencollective.com/express"],"categories":["JavaScript","中间件","Framework agnostic packages"],"sub_categories":["Node"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fexpressjs%2Fcookie-session","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fexpressjs%2Fcookie-session","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fexpressjs%2Fcookie-session/lists"}