UNPKG

10.3 kBMarkdownView Raw
1# connect-mongo
2
3MongoDB session store for [Connect](https://github.com/senchalabs/connect) and [Express](http://expressjs.com/) written in Typescript.
4
5[![npm version](https://img.shields.io/npm/v/connect-mongo.svg)](https://www.npmjs.com/package/connect-mongo)
6[![downloads](https://img.shields.io/npm/dm/connect-mongo.svg)](https://www.npmjs.com/package/connect-mongo)
7[![Sanity check](https://github.com/jdesboeufs/connect-mongo/actions/workflows/sanity.yml/badge.svg)](https://github.com/jdesboeufs/connect-mongo/actions/workflows/sanity.yml)
8[![Coverage Status](https://coveralls.io/repos/jdesboeufs/connect-mongo/badge.svg?branch=master&service=github)](https://coveralls.io/github/jdesboeufs/connect-mongo?branch=master)
9
10> Breaking change in V4 and rewritten the whole project using Typescript. Please checkout the [migration guide](MIGRATION_V4.md) and [changelog](CHANGELOG.md) for details.
11
12```
13npm install connect-mongo
14yarn add connect-mongo
15```
16
17## Compatibility
18
19* Support Express up to `5.0`
20* Support [native MongoDB driver](http://mongodb.github.io/node-mongodb-native/) `>= 3.0`
21* Support Node.js 10, 12 and 14
22* Support [MongoDB](https://www.mongodb.com/) `3.2+`
23
24For extended compatibility, see previous versions [v3.x](https://github.com/jdesboeufs/connect-mongo/tree/v3.x).
25But please note that we are not maintaining v3.x anymore.
26
27## Usage
28
29### Express or Connect integration
30
31Express `4.x`, `5.0` and Connect `3.x`:
32
33```js
34const session = require('express-session');
35const MongoStore = require('connect-mongo').default;
36
37app.use(session({
38 secret: 'foo',
39 store: MongoStore.create(options)
40}));
41```
42
43### Connection to MongoDB
44
45In many circumstances, `connect-mongo` will not be the only part of your application which need a connection to a MongoDB database. It could be interesting to re-use an existing connection.
46
47Alternatively, you can configure `connect-mongo` to establish a new connection.
48
49#### Create a new connection from a MongoDB connection string
50
51[MongoDB connection strings](http://docs.mongodb.org/manual/reference/connection-string/) are __the best way__ to configure a new connection. For advanced usage, [more options](http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connect-options) can be configured with `mongoOptions` property.
52
53```js
54// Basic usage
55app.use(session({
56 store: MongoStore.create({ mongoUrl: 'mongodb://localhost/test-app' })
57}));
58
59// Advanced usage
60app.use(session({
61 store: MongoStore.create({
62 mongoUrl: 'mongodb://user12345:foobar@localhost/test-app?authSource=admin&w=1',
63 mongoOptions: advancedOptions // See below for details
64 })
65}));
66```
67
68#### Re-use an existing native MongoDB driver client promise
69
70In this case, you just have to give your `MongoClient` instance to `connect-mongo`.
71
72```js
73/*
74** There are many ways to create MongoClient.
75** You should refer to the driver documentation.
76*/
77
78// Database name present in the connection string will be used
79app.use(session({
80 store: MongoStore.create({ clientPromise })
81}));
82
83// Explicitly specifying database name
84app.use(session({
85 store: MongoStore.create({
86 clientPromise,
87 dbName: 'test-app'
88 })
89}));
90```
91
92## Events
93
94A `MongoStore` instance will emit the following events:
95
96| Event name | Description | Payload
97| ----- | ----- | ----- |
98| `create` | A session has been created | `sessionId` |
99| `touch` | A session has been touched (but not modified) | `sessionId` |
100| `update` | A session has been updated | `sessionId` |
101| `set` | A session has been created OR updated _(for compatibility purpose)_ | `sessionId` |
102| `destroy` | A session has been destroyed manually | `sessionId` |
103
104## Session expiration
105
106When the session cookie has an expiration date, `connect-mongo` will use it.
107
108Otherwise, it will create a new one, using `ttl` option.
109
110```js
111app.use(session({
112 store: MongoStore.create({
113 mongoUrl: 'mongodb://localhost/test-app',
114 ttl: 14 * 24 * 60 * 60 // = 14 days. Default
115 })
116}));
117```
118
119__Note:__ Each time an user interacts with the server, its session expiration date is refreshed.
120
121## Remove expired sessions
122`
123By default, `connect-mongo` uses MongoDB's TTL collection feature (2.2+) to have `mongod` automatically remove expired sessions. `connect-mongo` will create a TTL index for you at startup. But you can disable the creation of index with `createAutoRemoveIdx: false`
124
125```js
126app.use(session({
127 store: MongoStore.create({
128 mongoUrl: 'mongodb://localhost/test-app',
129 createAutoRemoveIdx: false
130 })
131}));
132```
133
134__Note:__ If you use `connect-mongo` in a very concurrent environment, you should avoid this mode and prefer setting the index yourself, once!
135
136## Lazy session update
137
138If you are using [express-session](https://github.com/expressjs/session) >= [1.10.0](https://github.com/expressjs/session/releases/tag/v1.10.0) and don't want to resave all the session on database every single time that the user refresh the page, you can lazy update the session, by limiting a period of time.
139
140```js
141app.use(express.session({
142 secret: 'keyboard cat',
143 saveUninitialized: false, // don't create session until something stored
144 resave: false, //don't save session if unmodified
145 store: MongoStore.create({
146 mongoUrl: 'mongodb://localhost/test-app',
147 touchAfter: 24 * 3600 // time period in seconds
148 })
149}));
150```
151
152by doing this, setting `touchAfter: 24 * 3600` you are saying to the session be updated only one time in a period of 24 hours, does not matter how many request's are made (with the exception of those that change something on the session data)
153
154
155## Transparent encryption/decryption of session data
156
157When working with sensitive session data it is [recommended](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md) to use encryption
158
159```js
160const store = MongoStore.create({
161 mongoUrl: 'mongodb://localhost/test-app',
162 crypto: {
163 secret: 'squirrel'
164 }
165})
166```
167
168## Options
169
170### Connection-related options (required)
171
172One of the following options should be provided. If more than one option are provided, each option will take precedence over others according to priority.
173
174|Priority|Option|Description|
175|:------:|------|-----------|
176|1|`mongoUrl`|A [connection string](https://docs.mongodb.com/manual/reference/connection-string/) for creating a new MongoClient connection. If database name is not present in the connection string, database name should be provided using `dbName` option. |
177|2|`clientPromise`|A Promise that is resolved with MongoClient connection. If the connection was established without database name being present in the connection string, database name should be provided using `dbName` option.|
178
179### More options
180
181|Option|Default|Description|
182|------|:-----:|-----------|
183|`mongoOptions`|`{ useUnifiedTopology: true }`|Options object for [`MongoClient.connect()`](https://mongodb.github.io/node-mongodb-native/3.3/api/MongoClient.html#.connect) method. Can be used with `mongoUrl` option.|
184|`dbName`||A name of database used for storing sessions. Can be used with `mongoUrl`, or `clientPromise` options. Takes precedence over database name present in the connection string.|
185|`collectionName`|`'sessions'`|A name of collection used for storing sessions.|
186|`ttl`|`1209600`|The maximum lifetime (in seconds) of the session which will be used to set `session.cookie.expires` if it is not yet set. Default is 14 days.|
187|`createAutoRemoveIdx`|`true`|Create TTL index in MongoDB collection or not.|
188|`touchAfter`|`0`|Interval (in seconds) between session updates.|
189|`stringify`|`true`|If `true`, connect-mongo will serialize sessions using `JSON.stringify` before setting them, and deserialize them with `JSON.parse` when getting them. This is useful if you are using types that MongoDB doesn't support.|
190|`serialize`||Custom hook for serializing sessions to MongoDB. This is helpful if you need to modify the session before writing it out.|
191|`unserialize`||Custom hook for unserializing sessions from MongoDB. This can be used in scenarios where you need to support different types of serializations (e.g., objects and JSON strings) or need to modify the session before using it in your app.|
192|`writeOperationOptions`||Options object to pass to every MongoDB write operation call that supports it (e.g. `update`, `remove`). Useful for adjusting the write concern. Only exception: If `autoRemove` is set to `'interval'`, the write concern from the `writeOperationOptions` object will get overwritten.|
193|`transformId`||Transform original `sessionId` in whatever you want to use as storage key.|
194|`crypto`||Crypto related options. See below.|
195
196### Crypto-related options
197
198|Option|Default|Description|
199|------|:-----:|-----------|
200|`secret`|`false`|Enables transparent crypto in accordance with [OWASP session management recommendations](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md).|
201|`algorithm`|`'aes-256-gcm'`|Allows for changes to the default symmetric encryption cipher. See [`crypto.getCiphers()`](https://nodejs.org/api/crypto.html#crypto_crypto_getciphers) for supported algorithms.|
202|`hashing`|`'sha512'`|May be used to change the default hashing algorithm. See [`crypto.getHashes()`](https://nodejs.org/api/crypto.html#crypto_crypto_gethashes) for supported hashing algorithms.|
203|`encodeas`|`'hex'`|Specify to change the session data cipher text encoding.|
204|`key_size`|`32`|When using varying algorithms the key size may be used. Default value `32` is based on the `AES` blocksize.|
205|`iv_size`|`16`|This can be used to adjust the default [IV](https://csrc.nist.gov/glossary/term/IV) size if a different algorithm requires a different size.|
206|`at_size`|`16`|When using newer `AES` modes such as the default `GCM` or `CCM` an authentication tag size can be defined.|
207
208## Development
209
210```
211yarn install
212docker-compose up -d
213# Run these 2 lines in 2 shell
214yarn watch:build
215yarn watch:test
216```
217
218### Example application
219
220```
221yarn link
222cd example
223yarn link "connect-mongo"
224yarn install
225yarn start
226```
227
228### Release
229
230Since I cannot access the setting page. I can only do it manually.
231
2321. Bump version, update `CHANGELOG.md` and README. Commit and push.
2332. Run `yarn build && yarn test && npm publish`
2343. `git tag vX.Y.Z && git push --tags`
235
236## License
237
238The MIT License